branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>e1-one/smart-xml-analyzer<file_sep>/settings.gradle rootProject.name = 'smart-xml-analyzer' <file_sep>/README.md # smart-xml-analyzer Application that analyzes HTML and finds a specific element, even after changes, using a set of extracted attributes ### Brief guide how to build gradlew build fatJar ### Tool execution: java -jar <your_bundled_app>.jar <input_origin_file_path> <input_other_sample_file_path> <id_of_target_element_that_needs_to_be_found> ##### Execution example: java -jar ./build/libs/smart-xml-analyzer-1.0-SNAPSHOT.jar ./samples/sample-0-origin.html ./samples/sample-4-the-mash.html make-everything-ok-button ##### Comparison output for sample pages: __input_origin_file_path = ./samples/sample-0-origin.html__ - input_other_sample_file_path = ./samples/sample-1-evil-gemini.html \ [INFO] 2019-03-10 20:35:07,285 c.a.SmartXmlAnalyzer - Element: \<a class="btn btn-success" href="#check-and-ok" title="Make-Button" rel="done" onclick="javascript:window.okDone(); return false;"\>\</a\>\ [INFO] 2019-03-10 20:35:07,288 c.a.SmartXmlAnalyzer - Element Attributes and the values of their contribution to the result\ [INFO] 2019-03-10 20:35:07,289 c.a.SmartXmlAnalyzer - onclick with value: 1\ [INFO] 2019-03-10 20:35:07,289 c.a.SmartXmlAnalyzer - title with value: 10\ [INFO] 2019-03-10 20:35:07,289 c.a.SmartXmlAnalyzer - class with value: 7\ [INFO] 2019-03-10 20:35:07,289 c.a.SmartXmlAnalyzer - Total contribution score of this element is 18\ [INFO] 2019-03-10 20:35:07,290 c.a.Main - XML path to the element: /html[1]/body[2]/div[1]/div[5]/div[9]/div[1]/div[1]/div[5]/a[0] - input_other_sample_file_path = ./samples/sample-3-the-escape.html [INFO] 2019-03-11 20:10:37,702 c.a.SmartXmlAnalyzer - Element: \<a class="btn btn-success" href="#ok" title="Do-Link" rel="next" onclick="javascript:window.okDone(); return false;"\>\</a\> \ [INFO] 2019-03-10 20:10:37,703 c.a.Main - Element Attributes and the values of their contribution to the result\ [INFO] 2019-03-10 20:10:37,709 c.a.Main - onclick with value: 1\ [INFO] 2019-03-10 20:10:37,709 c.a.Main - rel with value: 3\ [INFO] 2019-03-10 20:10:37,709 c.a.Main - href with value: 6\ [INFO] 2019-03-10 20:10:37,709 c.a.Main - class with value: 7\ [INFO] 2019-03-10 20:10:37,710 c.a.Main - Total contribution score is 17\ [INFO] 2019-03-10 20:10:37,710 c.a.Main - XML path to the element: /html[1]/body[2]/div[1]/div[5]/div[9]/div[1]/div[1]/div[9]/a[0] <file_sep>/src/main/java/com/agileengine/Helper.java package com.agileengine; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public final class Helper { public static String printPathToElement(Element currentElement) { StringBuilder absPath = new StringBuilder(); Elements parents = currentElement.parents(); for (int j = parents.size() - 1; j >= 0; j--) { Element element = parents.get(j); absPath.append(printElement(element)); } return absPath.toString() + printElement(currentElement); } private static String printElement(Element element) { return "/" + element.tagName() + "[" + element.siblingIndex() + "]"; } } <file_sep>/build.gradle plugins { id 'java' } group 'com.agileengine' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile 'org.jsoup:jsoup:1.11.2' compile 'org.slf4j:slf4j-log4j12:1.7.25' testCompile group: 'junit', name: 'junit', version: '4.12' } jar { manifest { attributes "Main-Class": "com.agileengine.Main" } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } } task fatJar(type: Jar) { manifest { attributes 'Main-Class': 'com.baeldung.fatjar.Application' } baseName = 'smart-xml-analyzer-all' from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } with jar }
40f03bbaf60a4f7e04998c05bd285832305fd649
[ "Markdown", "Java", "Gradle" ]
4
Gradle
e1-one/smart-xml-analyzer
ba71d3308788bb6572ad4c30233742bdfb1aed6e
568fe00bf994f6f4086f7fa2ccb0cdcf72012f72
refs/heads/master
<file_sep>This is our final website products version. It contains both Qiwen Yan and Yan Zhao's coding. Those code are published to the sever, thus clinets could find our product on https://apisearch.herokuapp.com/. <file_sep>google-api-python-client==1.6.6 flask_table Flask-WTF <file_sep><!-- Results page 1 : all the information that clients input are wrong --> {% extends "reslayout.html" %} {% block body %} <h1>Sorry, Google did not return any results for these searches. </h1> <h1>Please search again.</h1> <h3>The following queries did not produce search results:</h3> {% for t in recog %} <p>{{ t }}</p> {% endfor %} <!-- Search again button --> <div class="container-fluid"> <form action="/back" method="POST"> <button type="search">Search again</button> </form> </div> {% endblock %} <file_sep>import os from urllib.parse import urlparse from flask import Flask, render_template, request, redirect, url_for from googleapiclient.discovery import build from operator import itemgetter app = Flask(__name__) # connect with google custom search engine def google_search(search_term): service = build("customsearch", "v1", developerKey="<KEY>") res = service.cse().list(q=search_term, cx='008154114684342405093:uuxrxyvjqsq', num=10).execute() dic = {} dic = res['searchInformation'] if dic['totalResults']!="0": return res['items'] else: return 1 # / means root directory, home page @app.route('/', methods=['GET']) def index(): return render_template('index.html') # / index page root # / call this user function when click the search button from the index page # / reaction to "form" function that in index.html @app.route('/search', methods=['POST']) def user(): # save number k = 0 list = [] # save all websites list2 = [] # save website without duplicate list3 = [] list4 = [] list5 = [] list6 = [] list7 = [] list8 = [] list9=[] recog=[] info = [] kind = [] table_data = [] sorted_listall = [] time = [] rank = [] new = [] new2 = [] new3 = [] # extract the input information from the clients name = request.form['name'] method = request.form['method'] # split the method information extracted from the clients to the mylist # ignore the none input and space input mylist = method.split(',') for i in range(0,len(mylist)): mylist[i] = mylist[i].strip() if mylist[i]!="": key=name+" "+mylist[i] if key not in new3: new3.append(key) for x in range(0, len(new3)): mysearch = new3[x] k += 1 # call google custom search engine # print links from the search engine results results = google_search(mysearch) #pprint.pprint(results) if results==1: recog.append(mysearch) if k==len(new3) and len(info)==0: return render_template('reempty.html', recog=recog) #*********************************** if k == len(new3): for e in range(0, len(list)): if list[e] not in list2: list2.append(list[e]) # list3 calculate the appearance of each website for e in range(0, len(list2)): temp = list.count(list2[e]) list3.append(temp) # table data save the website with its appearance for i in range(0, len(list)): list4.append(i) list5.append('1') table_data = [[list2[i], list3[i], list4[i], list5[i], list9[i]] for i in range(0, len(list2))] table_data = sorted(table_data, key=itemgetter(1), reverse=True) for i in range(0, len(table_data)): table_data[i][2] = i for i in range(0, len(info)): list7.append('0') list8.append('0') listall = [[info[a], kind[a], list7[a], list8[a], rank[a]] for a in range(0, len(info))] for a in range(0, len(info)): print(listall[a]) for t in range(0,len(listall)): print(t) for i in range(0, len(table_data)): list6.append(table_data[i]) for m in range(0, len(listall)): if not urlparse(listall[m][0]).scheme: listall[m][0] = 'https://' + listall[m][0] parsed_m = urlparse(listall[m][0]) judge = '{uri.netloc}/'.format(uri=parsed_m) if judge.startswith('www.'): judge = judge[4:] if table_data[i][0] == judge: listall[m][2] = table_data[i][2] list6.append(listall[m]) i = 0 while i <= (len(list6) - table_data[list6[len(list6) - 1][2]][1]): # print(i) b = [] a = list6[i][1] b.append(list6[i + 1][1]) c = list6[i + 1][1] time = 1 if int(a) != 1: if int(a) == 2: if c != list6[i + 2][1]: time += 1; if int(a) >= 3: for m in range(i + 2, int(a) + i + 1): if list6[m][1] not in b: b.append(list6[m][1]) time += 1 list6[i][1] = time i = i + int(a) + 1 for e in range(0, len(list6)): if list6[e][3] == '1': new.append(list6[e]) new = sorted(new, key=itemgetter(1), reverse=True) for e in range(0, len(new)): print(new[e]) for i in range(0, len(new)): new2.append(new[i]) for m in range(0, len(listall)): if not urlparse(listall[m][0]).scheme: listall[m][0] = 'https://' + listall[m][0] parsed_m = urlparse(listall[m][0]) judge = '{uri.netloc}/'.format(uri=parsed_m) if judge.startswith('www.'): judge = judge[4:] if new[i][0] == judge: listall[m][2] = new[i][2] new2.append(listall[m]) else: for i in range(1, 11): tem=i; rank.append(i) print(rank) #print(list_rank) for result in results: title = result['title'] link = result['formattedUrl'] info.append(link) kind2 = new3[x] kind2=kind2[len(name)+1:] kind.append(kind2) #print(link) if not urlparse(link).scheme: link = 'https://' + link parsed_url = urlparse(link) domain = '{uri.netloc}/'.format(uri=parsed_url) domain2 = '{uri.scheme}://'.format(uri=parsed_url) if domain.startswith('www.'): domain = domain[4:] domain3 = domain2 + domain if domain3 not in list9: list9.append(domain3) list.append(domain) # list2 have the elements in list without duplicate if k == len(new3): for e in range(0, len(list)): if list[e] not in list2: list2.append(list[e]) # list3 calculate the appearance of each website for e in range(0, len(list2)): temp = list.count(list2[e]) list3.append(temp) # table data save the website with its appearance for i in range(0, len(list)): list4.append(i) list5.append('1') table_data = [[list2[i], list3[i], list4[i], list5[i], list9[i]] for i in range(0, len(list2))] table_data = sorted(table_data, key=itemgetter(1), reverse=True) for i in range(0, len(table_data)): table_data[i][2] = i for i in range(0, len(info)): list7.append('0') list8.append('0') listall = [[info[a], kind[a], list7[a], list8[a], rank[a]] for a in range(0, len(info))] for i in range(0,len(kind)): print(kind[i]) for a in range(0, len(info)): print(listall[a]) for t in range(0,len(listall)): print(t) for i in range(0, len(table_data)): list6.append(table_data[i]) for m in range(0, len(listall)): if not urlparse(listall[m][0]).scheme: listall[m][0] = 'https://' + listall[m][0] parsed_m = urlparse(listall[m][0]) judge = '{uri.netloc}/'.format(uri=parsed_m) if judge.startswith('www.'): judge = judge[4:] if table_data[i][0] == judge: listall[m][2] = table_data[i][2] list6.append(listall[m]) i = 0 while i <= (len(list6) - table_data[list6[len(list6) - 1][2]][1]): # print(i) b = [] a = list6[i][1] b.append(list6[i + 1][1]) c = list6[i + 1][1] time = 1 if int(a) != 1: if int(a) == 2: if c != list6[i + 2][1]: time += 1; if int(a) >= 3: for m in range(i + 2, int(a) + i + 1): if list6[m][1] not in b: b.append(list6[m][1]) time += 1 list6[i][1] = time i = i + int(a) + 1 for e in range(0, len(list6)): if list6[e][3] == '1': new.append(list6[e]) new = sorted(new, key=itemgetter(1), reverse=True) for e in range(0, len(new)): print(new[e]) for i in range(0, len(new)): new2.append(new[i]) for m in range(0, len(listall)): if not urlparse(listall[m][0]).scheme: listall[m][0] = 'https://' + listall[m][0] parsed_m = urlparse(listall[m][0]) judge = '{uri.netloc}/'.format(uri=parsed_m) if judge.startswith('www.'): judge = judge[4:] if new[i][0] == judge: listall[m][2] = new[i][2] new2.append(listall[m]) # there is no data returned from the search engine if len(info)==0 and len(recog) != 0: return render_template('reempty.html', recog=recog) # all the information clients required has data returned elif len(recog)==0: return render_template('result.html', new2=new2,k=k) # some of the information clients required has data returned else: return render_template('results2.html', new2=new2,k=k,recog=recog) @app.route('/back', methods=['POST']) def back(): return render_template('index.html') if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)<file_sep>This project has several repositories: The "static" repository contains "js" folder and "style" folder. The js folder is used when we need to use tree table in the result page. While the style folder contains several css files. Those css files control the web pages' colors, layout, and fonts. Then, there is a "templates" repository. The layout.html file is the layout of index page and the reempty page. And the reslayout.html file is the layout of other result pages. 1. Index.html file is the searching page. 2. reempty.html file is the page that will be shown when there is no search results returned from google custom search engine. 3. result.html is a page with tree table function and will be displayed when all the input data is found from the google custom search engine. 4. results2.html is a page with tree table function and will be dispayed when some of the input information could not be found. The app.py is the back-end of this project. We use the Flask framework to design this project. In the app.py file, the function "google_search(search_term)" is to connect with the Google custom search engine. The index() function is to call the searching page. the @app.route is to react the form fuction that writes in index.html file. the user() function will happen after clients click the search button in the searching page.
0d04c01bd8e7e0f8942512348fdf9360afce479a
[ "Markdown", "Python", "Text", "HTML" ]
5
Markdown
ripley-yang/aip-project
0f5fb1a26b2feb8262a43fe4492ef2a06019a2ee
715a0aa4240bc90e7d72e88c2bc8f2eb5e6df5f3
refs/heads/master
<file_sep>context( "test that sortPW functions work") # Test preparation -------------------------------------------------------- # function inputs data = data.frame( facet = c( rep( 0, 6 ), rep( 1, 8 ) ), group = c( 1, 1, 2, 2, 3, 3, 1, 1, 3, 3, 2, 2, 4, 4 ), resp = c( 0.1, 0.3, 5, 2, -2, 1, 5, 2, 3, 4, 5, 6, 7, 3 ) ) plotTbl = data.frame( .id = c( rep( 0, 3 ), rep( 1, 6 ) ), x = c( '1', '1', '2', '1', '1', '1', '2', '2', '3' ), y = c( '2', '3', '3', '2', '3', '4', '3', '4', '4' ), origStat = c( -3.2, 0.7, 4, -2, 0, -1.5, 2, 0.5, -1.5 ) ) groupLabVec = c( "1" = "A", "2" = "B", "3" = "C", "4" = "D" ) calcStat = pryr::partial( mean, trim = 0.2 ) # expected function outputs ## findSortedTbl outTbl = data.frame( .id = c( rep( "0",3 ), rep( "1", 6 ) ), x = c( "0.1", "0.1", "0.2", "1.1", "1.1", "1.1", "1.2", "1.2", "1.3" ), y = c( "0.2", "0.3", "0.3", "1.2", "1.3", "1.4", "1.3", "1.4", "1.4"), origStat = c( 3.2, 4, 0.7, 0.5, 2, 2, 1.5, 1.5, 0 ), stringsAsFactors = FALSE ) ## sortGroupLabVec outVec = c( "0.3" = "C", "0.2" = "A", "0.1" = "B", "1.4" = "A", "1.3" = "C", "1.2" = "D", "1.1" = "B") # Tests ------------------------------------------------------------------- test_that( 'findSortedTbl function works', { expect_identical( findSortedTbl( data, plotTbl, calcStat ), outTbl ) } ) test_that( 'sortGroupLabVec function works', { expect_identical( sortGroupLabVec( data, groupLabVec, calcStat ), outVec ) } ) <file_sep>#' Calculate BCa #' #' @param bootObj object of class "boot". Object generated by \code{boot::boot} function. Optional #' if \code{bookPkgCI} is TRUE or if \code{bootStat} is \code{NULL}. If \code{bookPkgCI} is TRUE #' and \code{bootStat} is not \code{NULL}, then \code{bootObj} is used to calculate the confidence #' interval, rather than \code{bootStat}. #' @param bootPkgCI logical. If TRUE, then only functions from the \code{boot} package are used #' to compute the confidence interval. #' @param calcStat function. Function of a single variable to calculate for each sample. #' @param origData numeric vector. Original sample. Required if \code{origStat}, \code{bootStat} or #' \code{bcaA} (if \code{type} == "bc" ) not given. #' @param bootStat numeric vector. Bootstrap samples. Optional if \code{bookPkgCI} is TRUE. Will have no effect if #' \code{bootPkgCI} is \code{TRUE} and \code{bootObj} is not \code{NULL}. #' @param seed numeric vector. If specified, then \code{seed(seed)} is called before #' generating a bootstrap sample. #' @param type 'bca' or 'bc'. Whether to return BCa or bias-corrected intervals. If type == "bc", #' it sets \code{bcaA}, overriding \code{bcaA} as specified in the \code{calcBCa} arguments. #' @param origStat numeric. Original sample estimate, i.e. value of \code{calcStat} #' applied to \code{origData}. #' @param bcaA numeric. Acceleration constant. #' @param alpha numeric. Dependent on \code{ci}, either 1-\code{alpha} is the coverage of the #' confidence interval or \code{alpha} specifies the quantile. #' @param ci logical. If \code{TRUE}, then \code{alpha} specifies the width of the confidence interval, #' and an upper and lower bound are returned. If \code{FALSE}, then \code{alpha} specifies the quantile, #' and a single quantile is returned. #' @param B numeric. Number of bootstrap samples to generate, if required. #' @param ... arguments. Passed on to \code{boot::boot}, if run. #' @return If \code{ci} is \code{TRUE}, then a numeric vector of length two is returned with the #' upper and lower bound of the 1-\code{alpha} confidence interval. If \code{ci} is \code{FALSE}, then #' a single numeric is returned of the corresponding quantile. #' @examples calcBCa( origData = c( 0.096888, 0.115579, 0.13671, 0.086497, 0.5248, 1.676752, 0.46717, 0.360975, 0.118718 ), #' calcStat = mean, bootPkgCI = TRUE ) calcBCa = function( bootObj = NULL, bootStat = NULL, origStat = NULL, origData = NULL, bcaA = NULL, alpha = 0.05, ci = TRUE, type = 'bca', calcStat = NULL, B = 2e3, bootPkgCI = FALSE, seed = NULL, ...){ # FLOW # Input checks # - if bootPkgCI is TRUE and bootObj not given # -- origData and calcStat must be given # - if bootPkgCI is FALSE # -- If at least one of the following are not given: # --- bootStat, bcaA ( if type != "bc" ), origStat # --- then origData and calcStat must be given # Use boot package for CIs # - Only if bootPkgCI == TRUE # - if seed given # -- set seed. # -- If is.null( bootObj ) & is.null( bootStat ) # --- Calculate bootObj # -- If !is.null( bootObj ) # --- Calculate ci using boot.ci # --- Return ci # -- At this point, the function would have quit unless bootStat was supplied and # -- bootObj was not (bootObj therefore takes preference). # --- Calculate L # ---- This is the difference between the jackknife estimates and the jackknife mean # ---- for each jackknife estimate. # --- If origStat not provided # ---- Calculate it. # --- Calculate bca confidence interval # ---- Use boot:::bca.ci function, and # ---- L and origStat as calculated before. # --- Return bca confidence interval. # Use boot package for CIs only # - if bootPkgCI = TRUE and bootStat not NULL, then boot:::bca.ci is applied to bootStat to # calculate BCa confidence intervals. # origStat is first calculated if not initially supplied. # Remaing missing objects # - If bootStat is NULL, it is calculated. # - If type == "bca" and bcaA is NULL, then bcaA is calculated here. # - If type == "bc", then bcaA is set to 0. # Remaining objects # - Calculate z0 # - Calculate za # -- ci # --- If TRUE, then # ---- the original alpha is taken to mean that a 1-alpha # ---- confidence interval is required. # --- If FALSE, then # ---- the original alpha is taken to mean that the alpha-th quantile # ---- is required. # Calculated adjusted alpha # - Calculate the adjusted alpha # Return bootstrap quantile(s) # - Return the quantile(s) in the bootstrap distribution # - corresponding to the (adjusted) alpha(s). if( bootPkgCI & is.null( bootObj ) & or( is.null( origData ), is.null( calcStat ) ) ){ stop( "If bootPkgCI is TRUE and bootObj not given, then origData and calcStat are required." ) } if( !bootPkgCI & ( is.null( origStat ) %>% or( is.null( bootStat ) ) %>% or( and( is.null( bcaA ), type != "bc" ) ) ) & or( is.null( calcStat ), is.null( origData ) ) ){ stop( "If bootPkgCI is FALSE, then if bcaA (if type is not 'bc' ), origStat or bootStat are not given, origData and calcStat are required." ) } # Use boot package for confidence intervals if( bootPkgCI ){ if( !is.null( seed ) ) set.seed( seed ) if( is.null( bootObj ) & is.null( bootStat ) ) bootObj = boot::boot( origData, function(x,w) calcStat(x[w]), R = B,... ) if( !is.null( bootObj ) ) return( boot::boot.ci( bootObj, type = "bca" )$bca[4:5] ) L = boot::empinf( data = origData, statistic = function(x,w) calcStat(x[w]), type = "jack", stype = "i" ) if( is.null( origStat ) ) origStat = calcStat( origData ) return( boot:::bca.ci( boot.out = NULL, conf = 1-alpha, t0 = origStat, t = bootStat, L = L )[4:5] ) } # Intermediate objects if( is.null( origStat ) ) origStat = calcStat( origData ) if( !is.null( seed ) ) set.seed( seed ) if( is.null( bootStat ) ) bootStat = boot::boot( origData, function(x,w) calcStat(x[w]), R = B, ...)$t if( is.null( bcaA ) & type == "bca" ) bcaA = calcBCaA( origData, calcStat) if( type == "bc" ) bcaA = 0 if( !is.finite( bcaA ) ){ message( "Estimated variance adjustment, a, is infinite. Setting a to 0.") bcaA = 0 } z0 = calcBCaZ0( bootStat, origStat ) if( !is.finite( z0 ) ){ message( "Estimated bias adjustment, z0, is infinite. Setting z0 and a to 0." ) bcaA = 0 z0 = 0 } if( ci ) za = qnorm( c( alpha/2, 1-alpha/2 ) ) if( !ci ) za = qnorm( alpha ) # Adjusted alphas num = z0 + za den = 1 - bcaA * num term2 = num/den adjAlpha = pnorm ( z0 + term2 ) setNames( boot:::norm.inter( bootStat, adjAlpha )[,2], NULL) # Return bootstrap quantile(s) #setNames( matrixStats::colQuantiles( matrix( bootStat, ncol = 1 ), # probs = adjAlpha ), NULL ) } #' Calculate BCa acceleration factor #' #' Returns the estimated acceleration factor for the BCa confidence interval #' in the one-sample non-parametric case, using the standard jack-knife. #' #' @param origData numeric vector. Original sample. #' @param calcStat function. A numeric function that takes a single numeric vector as #' an argument and returns a numeric vector of length 1 as output. #' @return A numeric vector of length one that is the estimate of the acceleration factor. #' @examples calcBCaA( c( 0.096888, 0.115579, 0.13671, 0.086497, 0.5248, #' 1.676752, 0.46717, 0.360975, 0.118718 ), calcStat = mean) #' @export calcBCaA = function( origData, calcStat ){ L = boot::empinf( data = origData, statistic = function(x,w) calcStat(x[w]), type = "jack", stype = "i" ) setNames( sum(L^3)/(6 * sum(L^2)^1.5), NULL ) } #' Calculate BCa bias quantile #' #' Returns the estimated bias quantile for the BCa confidence interval. #' #' @param bootStat numeric vector. Bootstrap sample statistics. #' @param origStat numeric. Original sample statistic. #' @return A numeric vector of length one that is the estimate of the bias quantile. #' @export #' @examples #' respVec = c( 0.096888, 0.115579, 0.13671, 0.086497, 0.5248, #' 1.676752, 0.46717, 0.360975, 0.118718 ) #' origStat = mean(respVec) #' bootVec = boot::boot( respVec, function(x,w) mean(x[w]), R = 2e3 )$t #' calcBCaZ0( bootVec, origStat ) calcBCaZ0 = function( bootStat, origStat ){ qnorm( sum( bootStat < origStat ) / length( bootStat ), lower.tail = TRUE ) } #' calculate confidence intervals for multiple groups #' #' Calculates confidence intervals using one of three methods (BCa, BC or percentile), #' as well as the bias factor ($z_0$) and the acceleration factor ($a$). #' #' @param bootData dataframe. Must have character column split, defining #' groups, and bootStat, giving \code{B} bootstrap sample estimates for each #' group in \code{split} of statistic for which confidence interval is required. If #' \code{method=='percT'}, then #' @param alpha numeric \eqn{\;\in(0,1)}. (1-alpha) is the desired coverage #' for the confidence interval. #' @param method 'bca', 'bc' or 'perc'. The confidence interval method. #' @param diff logical. If \code{TRUE}, then the acceleration factor, $a$, is #' forced to zero, even when \code{method=='bca'}. This is because the acceleration factor #' calculated is invalid in the unpaired two-sample case. The reported acceleration factor #' is set to \code{NA}, for the same reason. If \code{diff==TRUE}, then the acceleration factor #' is only zero if \code{method=="bc"}, and the acceleration factor is reported as is. #' @param bcaAVec numeric vector. Numeric vector of . Required only if bcaAVec #' @param createCluster logical. If \code{TRUE}, then the code to start a cluster is run. #' @return A tibble with columns named split, lb and ub. #' @examples #' # data prep #' respVec = c( 0.060426, 0.066152, 0.07093, 0.056687, 0.18716, 0.790952, 0.20803, 0.245396, 0.087918, #' 0.02499226, 0.2234444308, 0.0148025445, 0.2425358694, 0.025742255, 0.011875387, 0.0148772707, #' 0.0086363158, 0.014349707, 0.0087206469, 0.055159961, 0.0366530097, 0.000260970000000001, 0.0111716045, 0.011851586, #' 0.0109080046, 0.002077461, 0.011693718, 0.0182342151, 0.0031248769, 0.0067057876, 0.0172261736, #' 0.0491776258, 0.026822441, 0.0062511869, 0.0135163775, 0.003760361, 0.0196274421, 0.004280863, 0.0143105389, #' 0.0150681214, 0.0063319547, 0.0087206469, 0.000260970000000001, 0.0111716045, 0.002077461, 0.011693718, 0.0148772707, #' 0.055159961, 0.0366530097, 0.011851586, 0.0109080046, 0.0182342151, 0.0172261736, 0.026822441, 0.0135163775 ) #' splitVec = c( rep( "1", 9), rep( "2", 46 ) ) #' calcStat = function(x) mean( x, trim = 0.2 ) #'calcStatVec = calcStat #' calcBootStatVec = function(x,w) calcStatVec(x[w]) #' # table of statistics on original sample #' origStatTbl = plyr::ldply( split( respVec, splitVec ), #' calcStatVec ) %>% #' rename( split = .id, origStat = V1 ) #' #' origStatVec = setNames( origStatTbl$origStat, origStatTbl$split ) #' # acceleration factor #' bcaATbl = plyr::ldply( split( respVec, splitVec ), function(x) calcBCaA( x, calcStat ) ) %>% #' rename( split = .id, bcaA = V1 ) #' #' bcaAVec = setNames( bcaATbl$bcaA, bcaATbl$split ) #' # bootstrap sample statistics #' set.seed(1) #' bootTbl = plyr::ldply( split( respVec, splitVec ), #' function(x) boot::boot( x, calcBootStatVec, 1e2 )$t ) %>% #' rename( split = .id, bootStat = `1` ) %>% #' mutate( origStat = origStatVec[ split ] ) %>% #' as_tibble() #' #' # actual function #' calcCITbl( bootData = bootTbl, alpha = 0.05, method = "bca", #' diff = FALSE, bcaAVec = bcaAVec ) calcCITbl = function( bootData, alpha, method, diff, bcaAVec, createCluster = FALSE ){ # FLOW # # Input checks # - Purpose: # -- Ensures that bcaVec is supplied if BCa calculation is requested. # -- Sets bcaAvec to named NA vec if bcaVec was NULL and BC # -- or perc calculation requested. # # Parallel I # - Purpose: # -- This is useful, as sometimes you have already initiated a cluster, # -- and so don't want another initialised to save time/avoid errors # - Code: # -- If createCluster is TRUE # --- initates a cluster. # # BCa vec # - Purpose: # -- Creates two vectors, reportingBCaVec and calculationBCaVec, which # -- are reported in the final outputted tibble or used in the # -- BCa or BC calculation, respectively. # -- This is done because if diff is TRUE, then the acceleration factor # -- should be NA, but if diff is FALSE, then the acceleration factor # -- is correct and can be reported. # -- It is also useful because if diff is TRUE or the calculation method # -- is BC, then the acceleration factor used in the BCa calculation should # -- be zero. # - Code: # -- if diff # --- set reportingBCaVec and calculationBCaVec to NA and 0, respectively, # --- with element names set to the unique names in the split. # -- if not diff # --- reportingBCaAvec is as given # --- calculationBCaVec is as given if method is BCa, and 0 if BC. Not needed # --- for perc method. # # # BC(a) calculation # - Purpose: # -- Performs a BCa calculation for each split, using the relevant provided # -- bootstrap samples (bootStat), acceleleration factors (calculationBCaAVec) # -- alpha and original sample statistics (origStat). # - Code: # -- ciVec # --- Uses calcBCa to calculate confidence interval. # -- Calculates z0CI using calcBCaZ0 # -- Sets aCI to reportingBCaAVec. # # Perc calculation # - Purpose: # -- For each level in split vector, calculates percentile confidence interval # -- and bias factor, and returns confidence interval, bias factor and # -- reportingBCaAVec accleration factor. # - Code: # -- Uses matrixStats::colQuantiles function for quantiles, and # -- calcBCaZ0 for bias factor. # # Parallel II # - Purpose # -- If a cluster was initiated by this function, it is stopped now. # # Return # - Purpose # -- Returns outTbl # Input checks if( is.null( bcaAVec ) & diff!= FALSE ){ if( method == "bca" ) stop( "Method == 'bca' required non-null bcaVec.") if( method %in% c( "perc", "bc" ) ) bcaAVec = setNames( rep( NA, calcLU( bootData$split ) ), unique( bootData$split ) ) } # Parallel if( createCluster ){ cl1 = parallel::makeCluster(parallel::detectCores()-1) doParallel::registerDoParallel(cl1) } # BCa vec if( diff ){ reportingBCaAVec = setNames( rep( NA, calcLU( bootData$split ) ), unique( bootData$split ) ) calculationBCaAVec = setNames( rep( 0, calcLU( bootData$split ) ), unique( bootData$split ) ) } else{ reportingBCaAVec = bcaAVec if( method == "bc" ) calculationBCaAVec = setNames( rep( 0, calcLU( bootData$split ) ), unique( bootData$split ) ) if( method == "bca" ) calculationBCaAVec = bcaAVec } # BC(a) calculation if( str_detect( method, "bc" ) ){ outTbl = ldply( split( bootData, bootData$split ), function(x){ ciVec = calcBCa( bootStat = x$bootStat, origStat = x$origStat[1], bcaA = calculationBCaAVec[x$split[1]], alpha = alpha ) tibble( lb = ciVec[1], ub = ciVec[2], z0CI = calcBCaZ0( x$bootStat, x$origStat[1]), aCI = reportingBCaAVec[x$split[1]]) }) %>% rename( split = .id ) %>% as_tibble() } # Perc calculation if( method == "perc" ){ outTbl = ldply( split( bootData, bootData$split ), function(x){ tibble( lb = matrixStats::colQuantiles( matrix( x$bootStat, ncol = 1), probs = alpha/2 ), ub = matrixStats::colQuantiles( matrix( x$bootStat, ncol = 1), probs = 1-alpha/2 ), z0CI = calcBCaZ0( x$bootStat, x$origStat[1]), aCI = reportingBCaAVec[x$split[1]]) }) %>% rename( split = .id ) %>% as_tibble() } # Parallel II if( createCluster ) parallel::stopCluster( cl1 ) # Return outTbl } #' Calculate p-value #' #' Calculate the p-value for a specific subgroup. #' #' @param bootData dataframe. Must have column named bootStat with bootstrap sample statistics. #' If \code{method=='percT'}, it must also have the column bootSE, with the bootstrap estimate #' standard deviation. #' @param origStat numeric. Original sample estimate. Required. #' @param origSE numeric. Original sample estimate standard error. Required if \code{method=='percT'}. #' @param nullValue numeric. Borderline value under the null hypothesis. #' @param altSide both', 'high' or 'low'. The side of the null hypothesis the alternate hypothesis #' is on. #' @return The p-value as a numeric vector. calcP = function( bootData, origStat, origSE = NULL, nullValue, altSide = NULL, method = 'perc'){ # Input checks if( !method %in% c( 'perc', 'percT' ) ){ stop( "method must be one of 'perc' or 'percT") } if( method == "percT" & ( suppressWarnings( is.null( bootData$bootSE ) %>% or( is.null( origSE ) ) ) ) ){ stop( "percT requires bootSE and origSE." ) } if( !exists( "bootData", inherits = FALSE ) ) stop( "bootData required." ) if( !exists( "origStat", inherits = FALSE ) ) stop( "origStat required." ) if( !exists( "nullValue", inherits = FALSE ) ) stop( "nullValue required." ) if( is.null( altSide ) ){ altSide = 'both' message( "Setting altSide to 'both'.") } # perc nullBootStat = bootData$bootStat - origStat + nullValue # centred at null nullOrigStat = origStat - nullValue # difference from null prop = sum( nullBootStat < nullOrigStat ) / nrow( bootData ) if( method == "perc" ) return( calcPSub( prop, altSide ) ) # percT nullBootTStat = (bootData$bootStat - origStat + nullValue )/bootData$bootSE nullOrigTStat = ( origStat - nullValue ) / origSE propT = sum( nullBootTStat < nullOrigTStat ) / nrow( bootData ) c( calcPSub( prop, altSide ), calcPSub( propT, altSide ) ) } #' Calculate p-value #' #' #' Calculate p-value based on a proportion #' #' @param prop numeric. Proportion of the null distribution less than the sample statistic. #' @param altSide 'both', 'high' or 'low'. The side of the null hypothesis the alternate hypothesis #' is on. #' @return A single numeric, the p-value. calcPSub = function( prop, altSide ){ if( altSide == "high" ) return( c( 1 - prop ) ) if( altSide == "low" ) return( prop ) if( altSide == "both" ) return( 2 * min( prop, 1 - prop ) ) } #' Calculate p value for a table #' #' Calculate p value for each subgroup in a table #' #' @param bootData dataframe. Must have character column split, defining #' groups, and bootStat/bootTStat, giving \code{B} bootstrap sample estimates for each #' group in \code{split} of statistic for which confidence interval is required. #' @param origData dataframe. Must have character column split, defining #' groups, and origStat/origTStat, giving original sample estimate of #' statistic for which p-value is required. #' @param calcStat function. Function that calculates the statistic for #' which a confidence interval is required. #' @param method character. The method specified by the argument \code{pMethod} #' in the \code{ggbootUV} function. #' @param altSide "both", "low" or "high". Specifies side(s) of null hypothesis alternative #' hypothesis lies. #' #' @return A dataframe with columns split and p. # added trueBootData now - check this out. calcPTbl = function( bootData, origData, method, altSide, nullValue ){ outTbl = ldply( split( bootData, bootData$split ), function(x){ origRow = which( origData$split == x$split[1] ) origStat = origData$origStat[origRow] origSE = origData$origSE[origRow] pVec = calcP( bootData = x, origStat = origStat, origSE = ifelse( method == "percT", origSE, 0 ), nullValue = nullValue, altSide = altSide, method = method ) z0P = calcBCaZ0( x$bootStat, origStat ) %>% signif(3) if( method == "perc" ) return( c( pVec, z0P ) ) z0PT = calcBCaZ0( ( x$bootStat - nullValue )/ x$bootSE, ( origStat - nullValue )/ origSE ) %>% signif(3) c( pVec, z0P, z0PT ) } ) %>% rename( split = .id, percP = V1 ) %>% as_tibble if( method == "perc" ) outTbl %<>% rename( z0P = V2 ) if( method == 'percT' ) outTbl %<>% rename( percTP = V2, z0P = V3, z0PT = V4 ) outTbl } <file_sep>context( "Testing centreAndScale" ) testDFReg = data.frame( x = 1:10 ) testDFZeroSD = data.frame( x = rep(1,10)) corrDFRegCentre = tibble( x = 1:10 - 5.5) corrDFRegScale = tibble( x = 1:10 / sd( 1:10 ) ) corrDFRegCentreScale = tibble( x = (1:10 - 5.5) / sd( 1:10 ) ) corrDFZeroSDCentre = tibble( x = rep(0,10) ) corrDFZeroSDScale = tibble( x = rep(1,10) ) testMatReg = matrix( 1:10 ) corrMatRegCentre = matrix( 1:10 - 5.5) corrMatRegScale = matrix( 1:10 / sd( 1:10 ) ) corrMatRegCentreScale = matrix( (1:10 - 5.5) / sd( 1:10 ) ) test_that( "Testing correct output", { expect_identical( centreAndScale( testDFReg, TRUE, FALSE ), corrDFRegCentre ) expect_equal( centreAndScale( testDFReg, FALSE, TRUE ), corrDFRegScale ) expect_equal( centreAndScale( testDFReg, TRUE, TRUE ), corrDFRegCentreScale, tolerance = 1 ) } ) test_that( "Testing correct output with a zero-sd column", { expect_identical( centreAndScale( testDFZeroSD, TRUE, FALSE ), corrDFZeroSDCentre ) expect_identical( suppressMessages( centreAndScale( testDFZeroSD, FALSE, TRUE ) ), corrDFZeroSDScale ) expect_identical( suppressMessages( centreAndScale( testDFZeroSD, TRUE, TRUE ) ), corrDFZeroSDCentre ) expect_message( centreAndScale( testDFZeroSD, TRUE, TRUE ), "A column had an sd of zero. Its mean-subtracted value was: 0." ) expect_silent( centreAndScale( testDFZeroSD, TRUE, TRUE, FALSE ) ) } ) test_that( "Testing correct output", { expect_equal( centreAndScale( testMatReg, TRUE, FALSE ), corrMatRegCentre ) expect_equal( centreAndScale( testMatReg, FALSE, TRUE ), corrMatRegScale ) expect_equal( centreAndScale( testMatReg, TRUE, TRUE ), corrMatRegCentreScale ) } ) <file_sep>data(mtcars) library(ggplot2) library(magrittr) library(tibble) library(testthat) p = ggplot( mtcars , aes( cyl, mpg ) ) + geom_point() test_that( "ggplotUV works" , { expect_equal_to_reference(c("a"), file = "basicTest.rds" ) }) <file_sep># uv boot grid plot func ggbootGrid = function( numVec, xVec, yVec, B, fdr, nullValue, locType = "mean", xLabVec, xLab, yLab, minEff = 0 ){ if( locType == "mean" ){ bootFunc = function(x,w) mean(x[w]) locFunc = mean } if( locType == "med" ){ bootFunc = function(x,w) median(x[w]) locFunc = median } # make a splitVec of above splitVec = str_c( xVec, ".", yVec ) # mean tbl meanTbl = ldply( split( numVec, splitVec ), function(x) locFunc(x) ) %>% mutate( mean = V1, V1 = str_sub( .id, 1, 1 ), V2 = str_sub( .id, 3) ) %>% as_tibble() # rawbootTbl rawBootTbl = ldply( split( numVec, splitVec ), function(x) boot( x, bootFunc, B )$t ) %>% rename( stat = `1` ) %>% separate( .id, into = c( "V1", "V2" ) ) ggplot( lPropTbl0, aes( x = vaccine, y = resp, fill = vaccine ) ) + geom_boxplot() + facet_wrap( ~ cytCombo, ncol = 2 ) resTbl = rawBootTbl %>% group_by( V1, V2 ) %>% summarise( pVal = sum( (stat <= nullValue )*1 )/B ) %>% ungroup() %>% mutate( V1.V2 = str_c( V1, ".", V2 ) ) # bh correction pVec = resTbl$pVal names( pVec ) = resTbl$`V1.V2` pVec = pVec[!is.nan(pVec)] sortPVec = sort( pVec ) ind = 0; i = 0; m = length(sortPVec); k = 0 while( i <= m -1 ){ i = i + 1 if( sortPVec[i] <= (i/m * fdr) ) k = i } if( k > 0 ){ sigNameVec = names(sortPVec)[1:k] } else{ sigNameVec = NULL } # plotTbl plotTbl = resTbl %>% full_join( meanTbl ) %>% mutate( sig = ( ( V1.V2 %in% sigNameVec ) * 1 ) %>% as.character(), sig = Vectorize(ifelse)( mean > minEff, sig, 0 ) ) ggplot( plotTbl, aes( V1, V2, fill = sig)) + geom_tile(colour = "black") + scale_x_discrete( labels = xLabVec, name = xLab ) + scale_y_discrete( name = yLab ) + scale_fill_manual( values = c( "lightblue2", "firebrick1" ), name = "Significance\nLevel", labels = c( "0" = str_c( "q>", fdr ), "1" = str_c( "q<", fdr ) )) + theme( axis.title = element_blank() ) } <file_sep>#' Plot cumulative axis predctivity #' #' Plot of the cumulative axis predictivity. #' @param data dataframe. Named numeric columns in wide format required. #' @inheritParams centreAndScale #' @param legendTitle character. Title of legend. Default is "Variable". #' @param legendLab named character vector. If NULL, then the labels used are #' the names of the columns and "mean". If not NULL, then the names of the #' labels must be the names of the columns in data, plus "mean". #' @param legendCol character vector. Colours to be used. May be named using #' the names of the columns in data, as well as "mean". #' #' @return Plot. #' @export plotCumQual = function( data, centre = TRUE, scale = FALSE, legendTitle = "Variable", legendLab = NULL, legendCol = NULL ){ if( is.null( legendLab ) ) legendLab = setNames( tbl_vars( data ), tbl_vars( data ) ) %>% c( "mean" = "Mean" ) if( is.null( legendCol ) ){ legendCol = c( "darkorchid", "springgreen", "maroon1", "dodgerblue", "red", "cyan2", "yellow3", "orange2" ) legendCol = setNames( legendCol, tbl_vars( data ) ) %>% c( "mean" = "black") } # svd numMat = centreAndScale( data, centre, scale ) %>% as.matrix() nVar = ncol( numMat ) svdList = svd( numMat ) # cumQMat cumQMat = matrix( 0, nrow = nVar, ncol = nVar ) # compQMat compQMat = matrix( 0, nrow = nVar, ncol = nVar ) for( r in 1:nVar ){ # Jr Jr = matrix(0, ncol = nVar, nrow = nVar) for(i in 1:r) Jr[i,i] = 1 # approx XHat = numMat %*% svdList$v %*% Jr %*% t( svdList$v ) # predictivity cumQMat[r,] = ( diag(diag( t(XHat) %*% XHat )) %*% solve( diag( diag( t(numMat) %*% numMat ) ) ) ) %>% diag() if( r == 1 ) compQMat[1,] = cumQMat[1,] if( r > 1 ) compQMat[r,] = cumQMat[r,] - cumQMat[r-1,] } cumQTbl = as_tibble( cumQMat ) compQTbl = as_tibble( compQMat ) dimnames( cumQTbl )[[2]] = tbl_vars( data ) dimnames( compQTbl )[[2]] = tbl_vars( data ) # adequacy # gather cumQTbl %<>% gather( key = varName, value = cumQual ) %>% mutate( comp = rep( 1:nVar, nVar ) ) # cumulative quality plot meanQualTbl = cumQTbl %>% group_by( comp ) %>% summarise( cumQual = mean( cumQual ) ) %>% mutate( varName = "mean" ) cumQualPlotTbl = bind_rows( cumQTbl, meanQualTbl ) ggplot( ) + geom_line( data = cumQualPlotTbl, aes( x = comp, y = cumQual, col = varName ), size = 1.5 ) + scale_x_continuous( breaks = 1:7 ) + labs( x = "Component number", y = "Cumulative Quality" ) + scale_colour_manual( name = legendTitle, label = legendLab, values = legendCol ) } #' Component-wise axis predictivity plot. #' #' Outputs a plot of the component-wise axis predictivity. #' @export plotCompQual = function( data, pc1, pc2, colVarName = "Cytokine\nCombination", colVec = cytComboColVec, scale ){ # svd numMat = centreAndScale( data, TRUE, scale ) %>% as.matrix() nVar = ncol( numMat ) svdList = svd( numMat ) # cumQMat cumQMat = matrix( 0, nrow = nVar, ncol = nVar ) # compQMat compQMat = matrix( 0, nrow = nVar, ncol = nVar ) for( r in 1:nVar ){ # Jr Jr = matrix(0, ncol = nVar, nrow = nVar) for(i in 1:r) Jr[i,i] = 1 # approx XHat = numMat %*% svdList$v %*% Jr %*% t( svdList$v ) # predictivity cumQMat[r,] = ( diag(diag( t(XHat) %*% XHat )) %*% solve( diag( diag( t(numMat) %*% numMat ) ) ) ) %>% diag() if( r == 1 ) compQMat[1,] = cumQMat[1,] if( r > 1 ) compQMat[r,] = cumQMat[r,] - cumQMat[r-1,] } cumQTbl = as_tibble( cumQMat ) compQTbl = as_tibble( compQMat ) dimnames( cumQTbl )[[2]] = tbl_vars( data ) dimnames( compQTbl )[[2]] = tbl_vars( data ) # adequacy # gather cumQTbl %<>% gather( key = varName, value = cumQual ) %>% mutate( comp = rep( 1:nVar, nVar ) ) compQTbl %<>% gather( key = varName, value = compQual ) %>% mutate( comp = rep( 1:nVar, nVar ) ) # join qualTbl = full_join( cumQTbl, compQTbl, by = c( "varName", "comp" )) # component-wise quality compQPlotTbl = compQTbl %>% spread( key = comp, value = compQual ) # component-wise quality tbl ggplot( compQPlotTbl, aes( x = compQPlotTbl[[1+pc1]], y = compQPlotTbl[[1+pc2]] ) ) + geom_text_repel( aes( label = varName, col = varName ), size = 5 ) + labs( x = paste0( "PC", pc1 ), y = paste0( "PC", pc2 )) + lims( x = c(0,1), y = c(0,1) ) + annotate( geom = "line", x = c( 0, 1 ), y = c( 0, 1 ), size = 1.2 ) + scale_colour_manual( values = cytComboColVec ) + theme( legend.position = "none" ) } #' Calculate axis predictivity #' #' Calculates the axis predictivity for a dataset. #' #' @param data dataframe. May #' @export calcAxisPred = function( data, centre = TRUE, scale = FALSE ){ # svd numMat = centreAndScale( data, centre, scale ) %>% as.matrix() nVar = ncol( numMat ) svdList = svd( numMat ) # cumQMat cumQMat = matrix( 0, nrow = nVar, ncol = nVar ) # compQMat compQMat = matrix( 0, nrow = nVar, ncol = nVar ) for( r in 1:nVar ){ # Jr Jr = matrix(0, ncol = nVar, nrow = nVar) for(i in 1:r) Jr[i,i] = 1 # approx XHat = numMat %*% svdList$v %*% Jr %*% t( svdList$v ) # predictivity cumQMat[r,] = ( diag(diag( t(XHat) %*% XHat )) %*% solve( diag( diag( t(numMat) %*% numMat ) ) ) ) %>% diag() if( r == 1 ) compQMat[1,] = cumQMat[1,] if( r > 1 ) compQMat[r,] = cumQMat[r,] - cumQMat[r-1,] } cumQTbl = as_tibble( cumQMat ) compQTbl = as_tibble( compQMat ) dimnames( cumQTbl )[[2]] = tbl_vars( data ) dimnames( compQTbl )[[2]] = tbl_vars( data ) # adequacy # gather cumQTbl %<>% gather( key = varName, value = cumQual ) %>% mutate( comp = rep( 1:nVar, nVar ) ) compQTbl %<>% gather( key = varName, value = compQual ) %>% mutate( comp = rep( 1:nVar, nVar ) ) # join qualTbl = full_join( cumQTbl, compQTbl, by = c( "varName", "comp" )) qualTbl } <file_sep>#' Bootstrap PCA biplot statistics #' #' Returns necessary statistics for PCA biplot. #' calcBiplot = function( dataTibble, scale, centre = TRUE, pcCompNum1 = 1, pcCompNum2 = 2, ellipseGroupVec = NULL, ellipseProb = 0.69, textAdjVal = 0.2 ){ # set-up pcCompNumVec = sort( c( pcCompNum1, pcCompNum2 )) nCol = ncol( dataTibble ) subSegmentPosVec = c( 'min', 'median', 'max' ) # pca pcaOutput = calcPCA( dataTibble, centre, scale ) # output saving Y = pcaOutput[[ 2 ]][ , pcCompNumVec ] # pc scores H = pcaOutput[[ 1 ]][ , pcCompNumVec ] # pc loadings eigenValVec = pcaOutput[[ 3 ]] # eigenvalues cumPropVarVec = pcaOutput[[ 4 ]] # cumulative proportion of variance compPropVarVec = pcaOutput[[ 5 ]] ######### PC SCORES pcaScoreTbl = as_tibble( Y ) ######### CALIBRATED AXEs # a one unit increase in the variable varLengthVec = rep( 0, nCol ) for ( row in 1:nCol ){ varLengthVec[ row ] = H[ row, 1 ] ^ 2 + H[ row, 2] ^ 2 } ### FIND VALUES TO MARK AT ####column means meanTbl = as_tibble( apply( dataTibble, 2, mean) ) #column standard deviations #sdTbl = as_tibble( apply( dataTibble, 2, sd ) ) ### CALIBRATION VALUES calValList = calcCalVal( dataTibble, "m3" ) ### CALIBRATION FACTORS AND HYPOTENUSE LENGTHS calFactList = list() hypLenList = list() nCalVal = length( calValList[[ 1 ]] ) for( i in 1:nCol ){ currCalValVec = calValList[[ i ]] currMean = as.numeric( meanTbl[ i, 1 ] ) currSd = 1 #as.numeric( sdTbl[ i, 1 ] ) currVarLength = varLengthVec[ i ] calFactList[[ i ]] = ( currCalValVec - currMean ) / currSd / currVarLength hypLenList[[ i ]] = calFactList[[ i ]] * currVarLength } ### FIND LINE MARKERS # preliminaries gradVec = H[ , 2 ] / H[ , 1 ] # gradient baseAngleVec = atan( abs( gradVec ) ) # angle in radians xPosNegIndVec = ifelse( H[, 1 ] > 0, 1, -1 ) # max x positivity yPosNegIndVec = ifelse( H[ , 2 ] > 0, 1, -1 ) # max y positivity axesCoordTbl = tibble( x = rep( 0, nCalVal * nCol ), y = 0, varName = 'a', segmentPos = rep( subSegmentPosVec, nCol ) ) for( i in 1:nCol ){ # from the hypotenuse lengtha and the variable angle, get the # x and y displacement. # adjust these from the signvec to get the correct placement of min and max. currBaseAngle = baseAngleVec[ i ] currHypLen = hypLenList[[ i ]] currFirstRow = ( i - 1 ) * length( subSegmentPosVec ) + 1 currLastRow = i * length( subSegmentPosVec ) axesCoordTbl$x[ currFirstRow:currLastRow ] = cos( currBaseAngle ) * currHypLen * xPosNegIndVec[ i ] axesCoordTbl$y[ currFirstRow:currLastRow ] = sin( currBaseAngle ) * currHypLen * yPosNegIndVec[ i ] axesCoordTbl$varName[ currFirstRow:currLastRow ] = tbl_vars( dataTibble )[ i ] } ######### TEXT ### Goal: Get the positions and the angles of the text to add to the ends ### of the lines. textXVec = rep( 0, nCol ) textYVec = rep( 0, nCol ) for( i in 1:nCol ){ # from the hypotenuse lengtha and the variable angle, get the # x and y displacement. # adjust these from the signvec to get the correct placement of min and max. currBaseAngle = baseAngleVec[ i ] CurrAdjHypLen = hypLenList[[ i ]][ 'max' ] + textAdjVal textXVec[ i ] = cos( currBaseAngle ) * CurrAdjHypLen * xPosNegIndVec[ i ] textYVec[ i ] = sin( currBaseAngle ) * CurrAdjHypLen * yPosNegIndVec[ i ] } ######### PATIENT INFO if( ! is.null( ellipseGroupVec ) ){ pcaScoreAndInfoTbl = as_tibble( pcaScoreTbl ) %>% mutate( group = ellipseGroupVec ) } else { pcaScoreAndInfoTbl = pcaScoreTbl } ######### ELLIPSE # Overlay a concentration ellipse if there are groups #if( !is.null( ellipseGroupVec ) ){ ### PRELIMINARIES #ellipseRawDataTbl = tibble( V1 = pcaScoreTbl$V1, # V2 = pcaScoreTbl$V2, # group = ellipseGroupVec ) ### ELLIPSE #ellipseTbl = ellipseRawDataTbl %>% # group_by( group ) %>% # do( calcEllipse( . ) ) # } ### OUTPUT if ( !is.null( ellipseGroupVec ) ){ outputList= list( 'fullPCAScoreTbl' = pcaOutput[[2]], 'pcaScoreAndInfoTbl' = pcaScoreAndInfoTbl, 'axesCoordTbl' = axesCoordTbl, 'textXVec' = textXVec, 'textYVec' = textYVec, 'pcCompNumVec' = pcCompNumVec, 'cumPropVarVec' = cumPropVarVec, # 'ellipseTbl' = ellipseTbl, 'compPropVarVec' = compPropVarVec, 'VJMat' = H ) } else { outputList= list( 'fullPCAScoreTbl' = pcaOutput[[2]], 'pcaScoreAndInfoTbl' = pcaScoreAndInfoTbl, 'axesCoordTbl' = axesCoordTbl, 'textXVec' = textXVec, 'textYVec' = textYVec, 'pcCompNumVec' = pcCompNumVec, 'cumPropVarVec' = cumPropVarVec, 'compPropVarVec' = compPropVarVec, 'VJMat' = H ) } return( outputList ) } <file_sep>context( "Testing calcCITbl" ) # Data -------------------------------------------------------------------- respVec = c( 0.060426, 0.066152, 0.07093, 0.056687, 0.18716, 0.790952, 0.20803, 0.245396, 0.087918, 0.02499226, 0.2234444308, 0.0148025445, 0.2425358694, 0.025742255, 0.011875387, 0.0148772707, 0.0086363158, 0.014349707, 0.0087206469, 0.055159961, 0.0366530097, 0.000260970000000001, 0.0111716045, 0.011851586, 0.0109080046, 0.002077461, 0.011693718, 0.0182342151, 0.0031248769, 0.0067057876, 0.0172261736, 0.0491776258, 0.026822441, 0.0062511869, 0.0135163775, 0.003760361, 0.0196274421, 0.004280863, 0.0143105389, 0.0150681214, 0.0063319547, 0.0087206469, 0.000260970000000001, 0.0111716045, 0.002077461, 0.011693718, 0.0148772707, 0.055159961, 0.0366530097, 0.011851586, 0.0109080046, 0.0182342151, 0.0172261736, 0.026822441, 0.0135163775 ) splitVec = c( rep( "1", 9), rep( "2", 46 ) ) calcStat = function(x) mean( x, trim = 0.2 ) calcStatVec = calcStat calcBootStatVec = function(x,w) calcStatVec(x[w]) # table of statistics on original sample origStatTbl = plyr::ldply( split( respVec, splitVec ), calcStatVec ) %>% rename( split = .id, origStat = V1 ) origStatVec = setNames( origStatTbl$origStat, origStatTbl$split ) # acceleration factor bcaATbl = plyr::ldply( split( respVec, splitVec ), function(x) calcBCaA( x, calcStat ) ) %>% rename( split = .id, bcaA = V1 ) bcaAVec = setNames( bcaATbl$bcaA, bcaATbl$split ) # bootstrap sample statistics set.seed(1) bootTbl = plyr::ldply( split( respVec, splitVec ), function(x) boot::boot( x, calcBootStatVec, 1e2 )$t ) %>% rename( split = .id, bootStat = `1` ) %>% mutate( origStat = origStatVec[ split ] ) %>% as_tibble() # Test: bca, no diff ------------------------------------------------------ # Data currBootTbl = bootTbl %>% filter( split == "1" ) ci1 = calcBCa( bootStat = currBootTbl$bootStat, origStat = currBootTbl$origStat[1], bcaA = bcaAVec[1] ) z01 = calcBCaZ0( currBootTbl$bootStat, currBootTbl$origStat[1]) a1 = calcBCaA( respVec[splitVec==1], calcStat ) currBootTbl = bootTbl %>% filter( split == "2" ) ci2 = calcBCa( bootStat = currBootTbl$bootStat, origStat = currBootTbl$origStat[1], bcaA = bcaAVec[2] ) z02 = calcBCaZ0( currBootTbl$bootStat, currBootTbl$origStat[1]) a2 = calcBCaA( respVec[splitVec==2], calcStat ) expTbl = tibble( split = c("1","2"), lb = c( ci1[1], ci2[1] ), ub = c( ci1[2], ci2[2] ), z0CI = c( z01, z02 ), aCI = c( a1, a2 ) ) # Test test_that( "calcCITbl works for method == bca & no diff", { # bca, no diff expect_identical( calcCITbl( bootData = bootTbl, alpha = 0.05, method = "bca", diff = FALSE, bcaAVec = bcaAVec ), expTbl ) }) # Test: bca, no diff & bc, no diff & bc, diff ----------------------------- # Data currBootTbl = bootTbl %>% filter( split == "1" ) ci1 = calcBCa( bootStat = currBootTbl$bootStat, origStat = currBootTbl$origStat[1], bcaA = 0 ) z01 = calcBCaZ0( currBootTbl$bootStat, currBootTbl$origStat[1]) a1 = calcBCaA( respVec[splitVec==1], calcStat ) currBootTbl = bootTbl %>% filter( split == "2" ) ci2 = calcBCa( bootStat = currBootTbl$bootStat, origStat = currBootTbl$origStat[1], bcaA = 0 ) z02 = calcBCaZ0( currBootTbl$bootStat, currBootTbl$origStat[1]) a2 = calcBCaA( respVec[splitVec==2], calcStat ) expTbl = tibble( split = c("1","2"), lb = c( ci1[1], ci2[1] ), ub = c( ci1[2], ci2[2] ), z0CI = c( z01, z02 ), aCI = c( a1, a2 ) ) expNATbl = expTbl %>% mutate( aCI = NA ) # Tests test_that( "calcCITbl works for method == bca & no diff", { # bca, diff expect_identical( calcCITbl( bootData = bootTbl, alpha = 0.05, method = "bca", diff = TRUE, bcaAVec = bcaAVec ), expNATbl ) # bc, no diff expect_identical( calcCITbl( bootData = bootTbl, alpha = 0.05, method = "bc", diff = FALSE, bcaAVec = bcaAVec ), expTbl ) # bc, ndiff expect_identical( calcCITbl( bootData = bootTbl, alpha = 0.05, method = "bc", diff = TRUE, bcaAVec = bcaAVec ), expNATbl ) }) # Test: perc, diff & perc, no diff ---------------------------------------------- # Data currBootTbl = bootTbl %>% filter( split == "1" ) lb1 = matrixStats::colQuantiles( matrix( currBootTbl$bootStat, ncol = 1), probs = 0.025 ) %>% setNames( NULL ) ub1 = matrixStats::colQuantiles( matrix( currBootTbl$bootStat, ncol = 1), probs = 0.975 ) %>% setNames( NULL ) z01 = calcBCaZ0( currBootTbl$bootStat, currBootTbl$origStat[1]) a1 = calcBCaA( respVec[splitVec==1], calcStat ) currBootTbl = bootTbl %>% filter( split == "2" ) lb2 = matrixStats::colQuantiles( matrix( currBootTbl$bootStat, ncol = 1), probs = 0.025 ) %>% setNames( NULL ) ub2 = matrixStats::colQuantiles( matrix( currBootTbl$bootStat, ncol = 1), probs = 0.975 ) %>% setNames( NULL ) z02 = calcBCaZ0( currBootTbl$bootStat, currBootTbl$origStat[1]) a2 = calcBCaA( respVec[splitVec==2], calcStat ) expTbl = tibble( split = c("1","2"), lb = c( lb1, lb2 ), ub = c( ub1, ub2 ), z0CI = c( z01, z02 ), aCI = c( a1, a2 ) ) expNATbl = expTbl %>% mutate( aCI = NA ) # Tests test_that( "calcCITbl works for method == bca & no diff", { # perc, diff expect_identical( calcCITbl( bootData = bootTbl, alpha = 0.05, method = "perc", diff = TRUE, bcaAVec = bcaAVec ), expNATbl ) # perc, no diff expect_identical( calcCITbl( bootData = bootTbl, alpha = 0.05, method = "perc", diff = FALSE, bcaAVec = bcaAVec ), expTbl ) }) <file_sep>context( "Testing calcPTbl" ) # Data -------------------------------------------------------------------- # Functions calcStat = function( x ) mean( x, 0.1 ) calcSE = function(x) { boot::boot( x, R = 20, function(x,w) calcStat( x[w] ) )$t %>% sd() } calcBootStatVec = function( x, w ) c( calcStat( x[w] ), calcSE( x[w] ) ) # Data respVec = c( 0.060426, 0.066152, 0.07093, 0.056687, 0.18716, 0.790952, 0.20803, 0.245396, 0.087918, 0.02499226, 0.2234444308, 0.0148025445, 0.2425358694, 0.025742255, 0.011875387, 0.0148772707, 0.0086363158, 0.014349707, 0.0087206469, 0.055159961, 0.0366530097, 0.000260970000000001, 0.0111716045, 0.011851586, 0.0109080046, 0.002077461, 0.011693718, 0.0182342151, 0.0031248769, 0.0067057876, 0.0172261736, 0.0491776258, 0.026822441, 0.0062511869, 0.0135163775, 0.003760361, 0.0196274421, 0.004280863, 0.0143105389, 0.0150681214, 0.0063319547, 0.0087206469, 0.000260970000000001, 0.0111716045, 0.002077461, 0.011693718, 0.0148772707, 0.055159961, 0.0366530097, 0.011851586, 0.0109080046, 0.0182342151, 0.0172261736, 0.026822441, 0.0135163775 ) splitVec = c( rep( "1", 9), rep( "2", 46 ) ) nullValue = 0.02 # Intermediate calculations origTbl = tibble( resp = respVec, split = splitVec ) origStatTbl = ldply( split( origTbl, origTbl$split ), function(x){ c( origStat = calcStat( x$resp ), origSE = calcSE( x$resp ) ) }) %>% rename( split = .id ) sd( respVec[splitVec==1]) sd( respVec[splitVec==2]) set.seed(1) bootStatTbl = ldply( split( respVec, splitVec ), function(x){ boot::boot( x, R = 2e2, calcBootStatVec )$t } ) %>% as_tibble() %>% rename( split = .id, bootStat = `1`, bootSE = `2` ) # Prop values currTbl = bootStatTbl %>% filter( split == 1 ) nullBootStat1 = currTbl$bootStat - origStatTbl$origStat[1] + nullValue # centred at null nullOrigStat1 = origStatTbl$origStat[1] - nullValue # difference from null nullBootTStat1 = (currTbl$bootStat - origStatTbl$origStat[1] + nullValue )/currTbl$bootSE nullOrigTStat1 = ( origStatTbl$origStat[1] - nullValue ) / origStatTbl$origSE[1] prop1 = sum( nullBootStat1 < nullOrigStat1 ) / nrow( currTbl ) # prop less than propT1 = sum( nullBootTStat1 < nullOrigTStat1 ) / nrow( currTbl ) propTVecLow1 = c( prop1, propT1 ) propTVecHigh1 = 1 - propTVecLow1 z0P1 = calcBCaZ0( currTbl$bootStat, origStatTbl$origStat[1]) z0PT1 = calcBCaZ0( ( currTbl$bootStat - nullValue ) / currTbl$bootSE, ( origStatTbl$origStat[1] - nullValue ) / origStatTbl$origSE[1] ) hist( ( currTbl$bootStat - nullValue ) / currTbl$bootSE ) hist( currTbl$bootSE ) origStatTbl$origSE currTbl = bootStatTbl %>% filter( split == 2 ) nullBootStat2 = currTbl$bootStat - origStatTbl$origStat[2] + nullValue # centred at null nullOrigStat2 = origStatTbl$origStat[2] - nullValue # difference from null nullBootTStat2 = (currTbl$bootStat - origStatTbl$origStat[2] + nullValue )/currTbl$bootSE nullOrigTStat2 = ( origStatTbl$origStat[2] - nullValue ) / origStatTbl$origSE[2] prop2 = sum( nullBootStat2 < nullOrigStat2 ) / nrow( currTbl ) # prop less than propT2 = sum( nullBootTStat2 < nullOrigTStat2 ) / nrow( currTbl ) propTVecLow2 = c( prop2, propT2 ) propTVecHigh2= 1 - propTVecLow2 z0P2 = calcBCaZ0( currTbl$bootStat, origStatTbl$origStat[2]) z0PT2 = calcBCaZ0( ( currTbl$bootStat - nullValue ) / currTbl$bootSE, ( origStatTbl$origStat[2] - nullValue ) / origStatTbl$origSE[2] ) outTblPercLow = tibble( split = c("1","2"), percP = c( prop1, prop2 ), z0P = c( z0P1, z0P2 ) %>% signif(3) ) outTblPercTHigh = tibble( split = c("1","2"), percP = 1 - c( prop1, prop2 ), percTP = 1 - c( propT1, propT2 ), z0P = c( z0P1, z0P2 ) %>% signif(3), z0PT = c( z0PT1, z0PT2 ) %>% signif(3) ) # Testing ----------------------------------------------------------------- test_that( 'calcPTbl works',{ expect_identical( calcPTbl( bootData = bootStatTbl, origData = origStatTbl, method = 'perc', altSide = 'low', nullValue = 0.02 ), outTblPercLow ) expect_identical( calcPTbl( bootData = bootStatTbl, origData = origStatTbl, method = 'percT', altSide = 'high', nullValue = 0.02 ), outTblPercTHigh ) } ) <file_sep><!-- README.md is generated from README.Rmd. Please edit that file --> ggboot ====== The package ggboot provides the functions used to compile the figures in the package VaccComp for the paper 'A comparison of antigen-specific T cell responses induced by six novel tuberculosis vaccine candidates'. You can install ggboot from Github using the following code: ``` r devtools::install_github("MiguelRodo/ggboot") ``` <file_sep>library(testthat) library(ggboot) test_check("ggboot") <file_sep># scree plot plot_scree = function( numTbl, centre = TRUE, scale = FALSE, nVar = NULL ){ ### PRELIM if( is.null( nVar ) ) nVar = ncol( numTbl ) # get desired number of variables to plot ### CALC pcaOutput = calcPCA( dataTibble = as.matrix( numTbl ), scale = scale, centre = centre ) # calc pca ### PLOT PREP plotTbl = tibble( x = rep( 1:nVar, 2 ), y = c( pcaOutput[[ 5 ]][1:nVar], pcaOutput[[ 4 ]][1:nVar] ), type = rep( c( "comp", "cum" ), each = nVar ) ) # prep plot ### PLOT ggplot( plotTbl, aes( x, y ) ) + geom_line( size = 1) + geom_point( size = 2 ) + labs( x = "Component number", y = "Proportion of variation" ) + facet_wrap( ~ type, ncol = 2, scale = "free_y", labeller = labeller( type = c( "comp" = "Component-wise", "cum" = "Cumulative" ) ) ) + scale_x_continuous( breaks = 1:nVar ) + background_grid( major = 'y', minor = 'none', colour.major = 'grey75' ) } <file_sep>context( "Testing sub functions for calcBCa" ) # Data respVec = c( 0.096888, 0.115579, 0.13671, 0.086497, 0.5248, 1.676752, 0.46717, 0.360975, 0.118718 ) calcStat = mean set.seed(3) bootObj = boot::boot( respVec, function(x,w) calcStat(x[w]), R = 1e4 ) # Tests test_that( "Testing that calcBCaA works properly",{ expect_equal( calcBCaA( respVec, calcStat ), 0.1102757 ) } ) test_that( "Testing that calcBCaZ0 works properly",{ expect_equal( calcBCaZ0( bootObj$t, calcStat( respVec ) ), 0.09791473 ) }) <file_sep># qq plot qqPlotFunc = function( dataTbl, selVar, nCol, pointSize = 1, lineSize = 1, lineAlpha = 0.7){ # centre and standardise stdTbl = dataTbl %>% group_by( group ) %>% mutate(V1 = (V1-mean(V1))/sd(V1), V2 = (V2-mean(V2))/sd(V2) ) %>% ungroup() B = dataTbl %>% group_by( group ) %>% summarise( count = n() ) %>% `[[`( "count" ) %>% unique() if( selVar == "V1" ){ # quantiles quantTbl = stdTbl %>% group_by( group ) %>% arrange( V1 ) %>% mutate( stdQuant = qnorm( seq(1/B,1-1/B,length.out=B)) ) %>% ungroup() # plot p = ggplot( quantTbl, aes( x = stdQuant, y = V1, col = group ) ) } else if( selVar == "V2" ){ # quantiles quantTbl = stdTbl %>% group_by( group ) %>% arrange( V2 ) %>% mutate( stdQuant = qnorm( seq(1/2000,1-1/2000,length.out=2000)) ) %>% ungroup() # plot p = ggplot( quantTbl, aes( x = stdQuant, y = V2, col = group ) ) } p + geom_point( size = pointSize ) + facet_wrap( ~ group, ncol = nCol, labeller = labeller( group = vaccLabelVec ) ) + labs( x = "Standard Normal Quantile", y = "Standardised Sample Quantile" ) + annotate( geom = "line", x = c(-3,3), y = c(-3, 3), size = lineSize, alpha = lineAlpha ) + scale_colour_manual( values = vaccColVec ) + theme( legend.position = "none" ) } # normal histogram plot histNormFunc = function( dataTbl, selVar, xlab, nCol ){ # centre and standardise stdTbl = dataTbl %>% group_by( group ) %>% mutate(V1 = (V1-mean(V1))/sd(V1), V2 = (V2-mean(V2))/sd(V2) ) %>% ungroup() # normal density xVec = seq(-3,3, length.out=1e4) normVec = dnorm( xVec ) # plot if( selVar == "V1" ){ ggplot( stdTbl, aes( x = V1, fill = group, col = group ) ) + facet_wrap( ~ group, labeller = labeller( group = vaccLabelVec ), scales = 'free_x', ncol = nCol ) + geom_density() + theme( legend.position = "none" ) + scale_fill_manual( values = vaccColVec ) + scale_colour_manual( values = vaccColVec ) + labs( x = xlab, y = "Density" ) + annotate( geom = "line", x = xVec, y = normVec, size = 1.5, linetype = 1 ) } else if( selVar == "V2" ){ ggplot( stdTbl, aes( x = V2, fill = group, col = group ) ) + facet_wrap( ~ group, labeller = labeller( group = vaccLabelVec ), scales = 'free_x', ncol = nCol ) + geom_density() + theme( legend.position = "none" ) + scale_fill_manual( values = vaccColVec ) + scale_colour_manual( values = vaccColVec ) + labs( x = xlab, y = "Density" ) + annotate( geom = "line", x = xVec, y = normVec, size = 1.5, linetype = 1 ) } } <file_sep>#' Centre and scale a dataframe. #' #' \code{centreAndScale} allows column-wise mean centring and #' standard-deviation scaling for a dataframe or matrix. The extra #' features of this function are the following: #' #' \itemize{ #' \item If a column has zero standard deviation, then scaling #' has no effect. A message is outputted to inform the user. #' \item A dataframe may be provided with character columns. These #' are simply ignored for the purposes of centring and scaling. #' \item A dataframe or a matrix may be provided. If the #' input was a matrix, then the output is also a matrix. If the #' input inherits from the dataframe class, then the output is a #' tibble. #' } #' #' #' @param grid dataframe or matrix. #' @param centre logical. If TRUE, then each column has its own #' mean subtracted #' @param scale logical. If TRUE, then each column is divided by #' its own standard deviation. If a column has zero standard #' deviation, then it is returned as is. #' @param message logical. If TRUE, then #' @return A tibble or a matrix, depending on whether \code{grid} #' inherited from the dataframe class or was a matrix. #' @export centreAndScale = function( grid, centre, scale, message = TRUE ){ # check if a matrix or a tibble if( is.matrix( grid ) ){ mat = TRUE grid = as_tibble( grid ) } if( !is_tibble( grid ) ) grid = as_tibble( grid ); mat = FALSE # if centring and scaling if( scale & centre ){ # centre grid %<>% mutate_if( is.numeric, function(x) x - mean(x) ) # scale grid %<>% mutate_if( is.numeric, function(x){ if( sd(x) == 0 ){ if( message ) message( "A column had an sd of zero. Its mean-subtracted value was: ", unique( x ), "." ) return(x) } x/sd(x) } ) if( mat ) grid %<>% as.matrix() return( grid ) } if( centre ){ grid %<>% mutate_if( is.numeric, function(x) x - mean(x) ) if( mat ) grid %<>% as.matrix() return(grid) } if( scale ){ # scale grid %<>% mutate_if( is.numeric, function(x){ if( sd(x) == 0 ){ if( message ) message( "A column had an sd of zero. Its mean-subtracted value was: ", unique( x ) ) return(x) } x/sd(x) } ) if( mat ) grid %<>% as.matrix() return( grid ) } } #' Calculate PCA and associated statistics. #' #' Calculate PCA #' #' @param grid matrix or dataframe. If a dataframe, then the numeric columns #' are selected and converted to a matrix. #' @param centre,scale logical. If TRUE, then the matrix has its mean subtracted #' (centre) and/or has each column divided by its sd (scale). If scale = TRUE and the sd #' of a column is 0, then that column is not divided by its sd and a message #' is printed. #' @param r integer. The number of principal compononents to show information for. #' Defaults to \code{ncol(grid)}. #' @return A list containing elements: #' #' \tabular{ll}{ #' VJMat \tab matrix of eigenvectors \cr #' YMat \tab matrix of principal component scores \cr #' singValVec \tab vector of singular values \cr #' cumPropVarVec \tab vector of cumulative proportion of variation \cr #' compPropVarVec \tab vector of component-wise proportion of variation #' } #' @export calcPCA = function ( grid, centre = TRUE, scale, r = ncol( grid ) ){ ### CENTRING AND SCALING if( !is.matrix( grid ) ) grid = grid %>% as_tibble() %>% select_if( is.numeric ) %>% as.matrix() mat = centreAndScale( grid, centre, scale ) %>% as.matrix() ### SVD svdOutput = svd( mat ) ### CALCULATIONS VJMat = svdOutput$v[ , 1:r ] # first r XtX eigenvectors YMat = mat %*% VJMat # PCA scores singValVec = svdOutput$d #eigenvalues cumPropVarVec = cumsum( svdOutput$d ^ 2 ) / sum( svdOutput$d ^ 2 ) compPropVarVec = ( svdOutput$d ^ 2 ) / sum( svdOutput$d ^ 2 ) ### OUTPUT outputList = list ( VJMat = VJMat, YMat = YMat, singValVec = singValVec, cumPropVarVec = cumPropVarVec, compPropVarVec = compPropVarVec ) return( outputList ) } #' Calculate calibration values. #' #' Calculate calibration values. #' @export calcCalVal = function( dataTibble, calOption ){ ### PURPOSE: Give the min, median and max of the columns of a data tibble ### in a list. ### PRELIMINARIES nCol = ncol( dataTibble ) calValList = list( ) ### OPTIONS if( calOption == "m3" ){ # min, median and max for ( i in 1:nCol ){ currCol = dataTibble[ , i ] medianString = summary( currCol )[3] colonLoc = str_locate( medianString, ":")[, 'start' ] medianVal = as.numeric( str_sub( medianString, start = colonLoc + 1 ) ) minVal = min( currCol ) maxVal = max( currCol ) calValList[[ i ]] = c( 'min' = minVal, 'median' = medianVal, 'max' = maxVal) } } if( calOption == "prop" ){ for ( i in 1:nCol ){ # data prep currCol = dataTibble[[i]] minVal = min( currCol ) maxVal = max( currCol ) # calculation potValVec = seq( -1, 1, by = 0.2) # vector of possible calibration points calMinVal = potValVec[ potValVec <= minVal ] %>% max() calMaxVal = potValVec[ potValVec >= maxVal ] %>% min() calValList[[ i ]] = potValVec[ which( potValVec >= calMinVal & potValVec <= calMaxVal ) ] } } ### OUTPUT return( calValList ) } #' Calculate ellipses #' #' Calculates ellipses #' @export calcEllipse = function( currTbl, type = "pcaBiplot", group = NULL, p = 0.69, medVec = NULL ){ ### PURPOSE - Calculate the contour of the 69th quantile of ### a 2D distribution based, assuming a ### bivariate normal distribution with parameters from the data. ### CIRCLE thetaVec = c( seq( -pi, pi, length = 50 ), seq( pi, -pi, length = 50 ) ) circleMat = cbind( cos( thetaVec ), sin( thetaVec ) ) ### INPUT CALCULATIONS if( is.null( medVec ) ){ currMeanVec = c( mean( currTbl$V1 ), mean( currTbl$V2 ) ) } else if ( !is.null( medVec ) ){ currMeanVec = medVec } sigmaMat = var( cbind( currTbl[[ 'V1' ]], currTbl[[ 'V2' ]] ) ) baseRadius <- sqrt( qchisq( p, df = 2 ) ) ### ELLIPSE CALCULATION ellipseCalcMat = sweep( circleMat %*% chol( sigmaMat ) * baseRadius, 2, currMeanVec, FUN = '+' ) ### OUTPUT if( type == "pcaBiplot" ) { outputTbl = tibble( x = ellipseCalcMat[ , 1 ], y = ellipseCalcMat[ , 2 ], group = currTbl$group[1] ) %>% mutate( group = as.character( group ) ) } else if( type == "mvMed" ) { outputTbl = tibble( x = ellipseCalcMat[ , 1 ], y = ellipseCalcMat[ , 2 ], group = group ) %>% mutate( group = as.character( group ) ) } return( outputTbl ) } <file_sep>context( "Testing calcBCa and related functions" ) # FLOW # Objects used throughout # - respVec # - bootObj # - percCI # -- bootstrap percentile CI # - bcaCI # -- BCA ci # Objects used throughout respVec = c( 0.096888, 0.115579, 0.13671, 0.086497, 0.5248, 1.676752, 0.46717, 0.360975, 0.118718 ) set.seed(3) bootObj = boot::boot( respVec, function(x,w) mean(x[w]), R = 1e4 ) bcaCI = boot::boot.ci( bootObj, type = "bca" )$bca[4:5] jackBCaCI = boot:::bca.ci( bootObj, type = "jack" )[4:5] origStat = mean( respVec ) test_that( "calcBCa works when bootPkgCI is TRUE", { # neither bootObj nor bootVec given, and so need to use boot::boot expect_equal( calcBCa( origData = respVec, calcStat = mean, bootPkgCI = TRUE, B = 1e4, seed = 3 ), bcaCI ) # bootObj given, and so just apply boot.ci( ..., type = "bca" ) expect_equal( calcBCa( bootObj = bootObj, bootPkgCI = TRUE, seed = 3, B = 1e4 ), bcaCI ) # bootVec only given, and so calculate L and origStat expect_equal( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, bootPkgCI = TRUE, B = 1e4, seed = 3 ), jackBCaCI ) # bootVec and origStat given, and so calculate L expect_equal( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, origStat = origStat, bootPkgCI = TRUE, B = 1e4, seed = 3 ), jackBCaCI ) # input errors expect_error( calcBCa( bootPkgCI = TRUE ) ) # missing calculation function and original data expect_error( calcBCa( bootPkgCI = TRUE, calcStat = mean ) ) # missing original data expect_error( calcBCa( bootPkgCI = TRUE, origData = respVec ) ) # missing calculation function } ) test_that( "calcBCa works when bootPkgCI is FALSE", { # bootStat and origStat not given expect_equal( calcBCa( origData = respVec, calcStat = mean, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ), jackBCaCI) # bootStat given but origStat not expect_equal( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ), jackBCaCI ) # origStat given but bootStat not expect_equal( calcBCa( origData = respVec, calcStat = mean, origStat = origStat, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ), jackBCaCI ) # bootStat and origStat given expect_equal( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, origStat = origStat, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ), jackBCaCI ) # bcaA given expect_equal( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, origStat = origStat, bcaA = 0.1102757, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ), jackBCaCI) # type == "bc" expect_equal( signif( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, origStat = origStat, bcaA = 0.1102757, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bc' ), 7 ), c( 0.1690968, 0.7993466 ) ) # ci = FALSE expect_equal( calcBCa( bootStat = bootObj$t, origData = respVec, calcStat = mean, ci = FALSE, alpha = 0.025, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ), bcaCI[1]) # input errors expect_error( calcBCa( bootStat = bootObj$t, calcStat = mean, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # origData not given expect_error( calcBCa( bootStat = bootObj$t, origData = respVec, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # calcStat not given expect_error( calcBCa( bootStat = bootObj$t, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # neither given expect_error( calcBCa( bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # none of bootStat, origStat and bcaA given expect_error( calcBCa( bootStat = bootObj$t, bcaA = 0.11, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # only origStat not given expect_error( calcBCa( bootStat = bootObj$t, origStat = origStat, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # only bcaA not given expect_error( calcBCa( origStat = origStat, bcaA = 0.11, bootPkgCI = FALSE, B = 1e4, seed = 3, type = 'bca' ) ) # only bootStat not given } ) <file_sep>#' Calculate bivariate normal contour for groups. #' #' @param data dataframe. Observations in numeric columns, with grouping variable #' a character column. #' @param p numeric. Contour percentile. #' @return A tibble with points representing coordinates composing the contour lines #' for each group, and a column denoting group for each coordinate. calcGroupEllipse = function( data, p = 0.95 ){ numTbl = data %>% select_if( is.numeric ) groupVec = data %>% select_if( is.character ) %>% `[[`(1) ldply( split( numTbl, groupVec ), function(x){ calcEllipse( x, p = p ) } ) %>% dplyr::rename( group = .id, x = V1, y = V2 ) %>% as_tibble() } #' Calculate bivariate normal contour. #' #' Calculate the \code{p}-th contour line for a distribution #' using observations in \code{data}, assuming that the #' distribution is bivariate normal. #' @param data numeric dataframe #' @inheritParams calcGroupEllipse #' @return A matrix with points along the contour line. calcEllipse = function( data, p = 0.95 ){ # circle thetaVec = c( seq( -pi, pi, length = 50 ), seq( pi, -pi, length = 50 ) ) circleMat = cbind( cos( thetaVec ), sin( thetaVec ) ) # sample values meanVec = laply( data, mean ) sigmaMat = var( as.matrix( data ) ) baseRadius <- sqrt( qchisq( p, df = 2 ) ) # calculate ellipse sweep( circleMat %*% chol( sigmaMat ) * baseRadius, 2, meanVec, FUN = '+' ) } <file_sep>#' Univariate bootstrap plot #' #' Plots a sample statistic, such as the mean or median, and associated bootstrapped 95\% confidence intervals for specified subsets of observations. Facilitates hypothesis testing by allowing a) application of the Benjamini-Hochberg procedure to control the alse discovery rate and b) specification of a minimum effect size. #' #' @param data dataframe. Has one row per observation and the column names specified below. #' @param resp unquoted expression. Response variable name. #' @param xAxis unquoted expression. X-axis variable name. #' @param col unquoted expression. Colour variable name. #' @param facet unquoted expression. Facet variable name. #' @param diff unquoted expression. Difference variable name. Must be a binary variable, preferrably ('0','1') as then it is clear that the difference is the amount by which the observations labelled '1' are greater than the observations labelled '0'. #' @param calcStat function olr character. Bootstrap statistic function. Functions other than mean or median used at own risk. #' @param B integer. Number of bootstrap samples per subgroup. #' @param alpha numeric. 1-\code{alpha} is the coverage of the confidence intervals. #' @param nSide 1 or 2. Number of sides of the hypothesis tests. #' @param altSde 'high', 'low' or 'both'. Character specifying the alternative hypothesis relative to the null hypothesis. Note that you must still specify nSide, even if altSide is specified. #' @param fdr numeric. False discovery rate. #' @param minEff numeric. Minimum effect size. Default is 0. #' @param hLineVec numeric vector. Heights of dashed horizontal lines to plot. Useful for indicating minimum effect size. #' @param nullValue numeric. Null hypothesis value for statistic. #' @param xLab,yLab characeter. X- and y-axis titles. Optional. #' @param xAxisLabVec named character vector. Labels for x-axis variable. Optional. #' @param rotXText logical. If TRUE, then the x-axis text is rotated 90 degrees clockwise. #' @param remXAxisMarks logical. If TRUE, then the x-axis ticks and text are removed. #' @param pointSize numeric. Size of plot points #' @param errBarSize numeric. Size of error bar #' @param errBarSizeRatio numeric. How many times larger the size is of the statistically significant error bars than the #' non-statistically significant bars are. #' @param colLabName character. Name for colour legend. Optional. #' @param colourVec character vector. Colours for colour scale. Optional. Label with factor levels to match levels to colours manually. #' @param colLabVec named character vector. Labels for colour variable. Optional. #' @param facetlabeVec named character vector. Labels for facet fariable. Optional. #' @param facetScale 'free', 'free_x' or 'free_y'. Facet scale. #' @param nCol numeric. Number of columns to use. #' @param plotTblName character. If not NULL, then the dataframe used to plot is saved to global environment with name \code{plotTblName}. #' @param eqErrBarWidth logical. If \code{TRUE}, then the error bars are made the same width in each facet. Otherwise the error bars automatically #' span the entire facet, however many x-axis entries there are. #' @param errBarAlpha numeric. Error bar alpha #' @param errBarAlphaRatio numeric. How many times greater the alpha is of the statistically significant error bars than the #' non-statistically significant bars are. #' @param sigIndType character vector. Must contain at least one of \code{"lineType"}, \code{"alpha"} and \code{"size"}. The #' statistically significant and non-statistically significant error bars will then differ by this aesthetic. #' @param fontScaleFactor numeric. Factor by which to scale the text size from the default. #' @param lineScaleFactor numeric. Factor by which to scale the line size from the default. #' @param hLineFactor numeric. Factor by which to scale the horizontal line size from the default. #' @param pMethod "perc" or "percT". Method to use for calculating p-values. Both uses the bootstrap percentile method, but "perc" does this on the mean or median, whilst "percT" does this on the t-statistic based on the mean or median. #' @param ciMethod "perc" or "bca". method to use to calculate confidence intervals. Both use bootstrap samples, but "perc" uses the percentile method and "bca" the bias-corrected and adjusted method. #' @return a ggplot2 object #' @export ggbootUV = function( data, resp, xAxis, col = NULL, facet = NULL, nullBFactor = 10, diff = NULL, calcStat = "mean", B = 10, seB = 200, pMethod = "percT", fdr = 0.01, altSide, nSide = 1, ciMethod = "bca", alpha = 0.05, minEff = 0, hLineVec = NULL, nullValue = 0, xLab = NULL, yLab = 'Response', xAxisLabVec = NULL, rotXText = FALSE, remXAxisMarks = FALSE, pointSize = 2, errBarSize = 1, errBarSizeRatio = 2, errBarAlpha = 0.7, errBarAlphaRatio = 2, eqErrBarWidth = TRUE, errBarLineType = "dotted", colLabName = NULL, colourVec = c( 'darkorchid1', 'springgreen2', 'maroon1', 'dodgerblue', 'red', 'yellow3', 'cyan2', "orange2" ), colLabVec = NULL, facetLabVec = NULL, facetScale = 'free', nCol = 2, plotTblName = NULL, fontScaleFactor = 1, lineScaleFactor = 1, hLineFactor = 1, bootT = TRUE, trim = 0.2, bootSECorr = FALSE ){ ### PRELIMINARIES ### on.exit( if( exists( "cl1" ) ) parallel::stopCluster( cl1 ) ) # variables ## variable names xAxisVar = substitute( xAxis ) colVar = substitute( col ) facet = substitute( facet ) diff = substitute( diff ) resp = substitute( resp ) ## vectors of grouping variables xAxisVec = data[[ deparse( xAxisVar ) ]] colVec = data[[ deparse( colVar ) ]] facetVec = data[[ deparse( facet ) ]] diffVec = data[[ deparse( diff ) ]] respVec = data[[ deparse( resp ) ]] ## grouping variables name vector vNameVec = c( "V1" ) if( !is.null( colVar ) ) vNameVec = c( vNameVec, "V2" ) if( !is.null( facet ) ) vNameVec = c( vNameVec, "V3" ) ## vector to split into groups based on splitVec = str_c( xAxisVec, colVec, facetVec, diffVec, sep = "." ) noDiffSplitVec = str_c( xAxisVec, colVec, facetVec, sep = "." ) # x axis label if( is.null( xLab ) ) xLab = deparse( xAxisVar ) sdFunc = sd if( identical( calcStat, "median" ) ){ calcStat = function(x) matrixStats::colMedians( as.matrix( x, ncol = 1 ) ) calcSE = function(x) { boot::boot( x, R = seB, function(x,w) matrix( x[w], ncol = 1 ) %>% matrixStats::colMedians() )$t %>% sdFunc() } } else if( identical( calcStat, "mean" ) ){ calcStat = function( x, .trim = trim ) mean( x, .trim ) calcSE = function(x) { boot::boot( x, R = seB, function(x,w) mean( x[w], trim ) )$t %>% sdFunc() } } else{ stop( "calcStat must be either 'mean' or 'median'") } if( pMethod == "perc" ) { calcStatVec = calcStat calcBootStatVec = function( x, w ) calcStat( x[w] ) } if( pMethod == "percT" ){ calcStatVec = function( x ) c( calcStat( x ), calcSE( x ) ) calcBootStatVec = function( x, w ) c( calcStat( x[w] ), calcSE( x[w] ) ) } # only calculate calcStat to save time when not using t-stat for hyp testing ### BOOTSTRAP STATISTICS ### cl1 = parallel::makeCluster(parallel::detectCores()-1) doParallel::registerDoParallel(cl1) if( is.null( diff ) ){ # if no difference taken ## table of statistics on original sample origStatTbl = plyr::ldply( split( respVec, splitVec ), calcStatVec, .parallel = TRUE ) %>% rename( split = .id, origStat = V1 ) origStatVec = setNames( origStatTbl$origStat, origStatTbl$split ) bcaATbl = plyr::ldply( split( respVec, splitVec ), function(x) calcBCaA( x, calcStat ) ) %>% rename( split = .id, bcaA = V1 ) bcaAVec = setNames( bcaATbl$bcaA, bcaATbl$split ) if( pMethod == "percT" ){ origStatTbl %<>% rename( origSE = V2 ) %>% mutate( origTStat = ( origStat - nullValue ) / origSE ) origSEVec = setNames( origStatTbl$origSE, origStatTbl$split ) } # table of bootstrapped sample estimates bootTbl = plyr::ldply( split( respVec, splitVec ), function(x) boot::boot( x, calcBootStatVec, B )$t, .parallel = TRUE ) %>% rename( split = .id, bootStat = `1` ) %>% mutate( origStat = origStatVec[ split ] ) if( pMethod == "percT" ){ bootTbl %<>% rename( bootSE = `2` ) %>% mutate( origSE = origSEVec[ split ], bootTStat = ( bootStat - origStat + nullValue ) / bootSE ) } } else{ # difference taken bcaAVec = NULL if( ciMethod == "bca" ) ciMethod = "bc" ## table of statistics on original sample if( pMethod == "perc" ){ origStatTbl = plyr::ldply( split( respVec, splitVec ), calcStat ) mutate( diff = str_sub( .id, -1 ), split = str_sub( .id, end = -3 ) ) %>% arrange( split, diff ) %>% group_by( split ) %>% summarise( origStat = V1[2] - V1[1] ) origStatVec = setNames( origStatTbl$origStat, origStatTbl$split ) # table of bootstrapped sample estimates bootTbl = plyr::ldply( split( respVec, splitVec ), # a group for each unique value in splitVec function(x) boot::boot( x, calcBootStatVec, B )$t, .parallel = TRUE ) %>% # sample from each group B times, calculating calcBootStatVec rename( split = .id, bootStat = `1` ) %>% mutate( diff = str_sub( split, -1 ), split = str_sub( split, end = -3 ) ) bootTbl = plyr::ldply( split( bootTbl, bootTbl$split ), # a group for each unique value in splitVec function(x) x %>% mutate( tempID = c( 1:(nrow(x)/2),1:(nrow(x)/2) ) ) %>% spread( key = diff, value = bootStat ), .parallel = TRUE ) %>% # sample from each group B times, calculating calcBootStatVec mutate( bootStat = `1` - `0` ) %>% select( -c( .id, tempID, `0`, `1` ) ) %>% mutate( origStat = origStatVec[ split ] ) } else if( pMethod == "percT" ){ origDataTbl = tibble( split = splitVec, resp = respVec ) %>% mutate( origSplit = split, diff = str_sub( split, -1 ), split = str_sub( split, end = -3 ) ) origStatTbl = ldply( split( origDataTbl, origDataTbl$split ), function(x){ resp0Vec = x %>% filter( diff == 0 ) %>% extract2( "resp" ) resp1Vec = x %>% filter( diff == 1 ) %>% extract2( "resp" ) se0 = calcSE( resp0Vec ) se1 = calcSE( resp1Vec ) diffSE = sqrt( se0^2 + se1^2 ) statDiff = calcStat( resp1Vec ) - calcStat( resp0Vec ) tibble( origStat = statDiff, origSE = diffSE, origTStat = ( statDiff - nullValue )/diffSE ) } ) %>% rename( split = .id ) # get bootstrap sample estimates of mean and estimates of sd of mean bootTbl = ldply( split( origDataTbl, origDataTbl$origSplit ), function(x){ boot::boot( x$resp, R = B, function( y, w ) c( bootStat = calcStat( y[w] ), bootSE = calcSE( y[w] ) ) )$t %>% as_tibble() %>% rename( bootStat = V1, bootSE = V2 ) }, .parallel = TRUE ) %>% rename( origSplit = .id ) %>% mutate( split = str_sub( origSplit, end = -3 ), diff = str_sub( origSplit, - 1 ) ) # calculate bootStat and bootTStat bootTbl = plyr::ldply( split( bootTbl %>% select( -origSplit ), bootTbl$split ), # a group for each unique value in splitVec function(x){ currSplit = x$split[1] currOrigStat = origStatTbl$origStat[which(origStatTbl$split==currSplit)] currOrigSE = origStatTbl$origSE[which(origStatTbl$split==currSplit)] x %<>% mutate(tempID = c( 1:(nrow(x)/2),1:(nrow(x)/2) ) ) %>% select( -split ) statTbl = x %>% select( - bootSE ) %>% spread( key = diff, value = bootStat ) %>% rename( stat0 = `0`, stat1 = `1` ) sdTbl = x %>% select( - bootStat ) %>% spread( key = diff, value = bootSE ) %>% rename( se0 = `0`, se1 = `1` ) fullTbl = merge( statTbl, sdTbl, by = "tempID" ) fullTbl %>% mutate( bootStat = stat1 - stat0, bootSE = sqrt( se1^2 + se0^2 ), bootTStat = ( bootStat - currOrigStat + nullValue ) / bootSE, origStat = currOrigStat, origSE = currOrigSE) %>% as_tibble() } , .parallel = TRUE ) %>% # sample from each group B times, calculating calcBootStatVec rename( split = .id ) # %>% # select( split, bootStat, bootTStat, trueBootTStat, nullBootTStat ) } else { stop( "pMethod must be one of perc or percT" ) } } if( pMethod == "percT" & bootSECorr ) bootTbl = ldply( as.list( unique( bootTbl$split ) ), function(i){ currOrigStat = origStatTbl %>% filter( split == i ) %>% extract2( "origStat" ) currOrigSE = origStatTbl %>% filter( split == i ) %>% extract2( "origSE" ) currBootTbl = bootTbl %>% filter( split == i ) gamMod = gam::gam( formula = bootSE ~ gam::s(bootStat, df = 4), data = currBootTbl ) bootFit = gamMod$fitted.values origSEFit = gam::predict.Gam( gamMod, tibble( bootStat = currOrigStat ) ) adjFactor = currOrigSE / origSEFit bootFit = bootFit * adjFactor # adjust by a multiplicative factor origMinBootSE = min( currBootTbl$bootSE ) # min raw boot SE bootFit = Vectorize(ifelse)( bootFit <origMinBootSE, origMinBootSE, bootFit ) # ensure positive currBootTbl %>% mutate( bootSE = bootSE * adjFactor, adj = adjFactor ) }, .parallel = TRUE ) bootTbl %<>% as_tibble() ### BOOTSTRAP CONFIDENCE INTERVALS AND P-VALUES ### ciTbl = calcCITbl( bootData = bootTbl, alpha = alpha, method = ciMethod, diff = !is.null( diff ), bcaAVec = bcaAVec, createCluster = FALSE ) pTbl = calcPTbl( bootData = bootTbl, origData = origStatTbl, method = pMethod, altSide = altSide, nullValue = nullValue ) bootStatTbl = merge( ciTbl, pTbl, by = "split" ) ### CORRECTIONS FOR MULTIPLE TESTING ### # identify names of split levels for which the p-value was statistically significant # after controlling fdr if( pMethod == "perc" ) pVec = bootStatTbl$percP if( pMethod == "percT" ) pVec = bootStatTbl$percTP fdrSigNameVec = correctBH( setNames(pVec, bootStatTbl$split ), fdr = fdr, nSide = 1 ) plotTbl = bootStatTbl %>% full_join( origStatTbl, by = 'split' ) %>% mutate( fdrSig = ( split %in% fdrSigNameVec ) * 1 ) # add in p-value sig levels # check which meet min effect size if( altSide == "high" ) plotTbl %<>% mutate( mesSig = ( ( origStat >= abs( minEff ) ) * 1 ) ) if( altSide == "low" ) plotTbl %<>% mutate( mesSig = ( ( origStat <= -abs( minEff ) ) * 1 ) ) if( altSide == "both" ) plotTbl %<>% mutate( mesSig = pmax( ( origStat <= -abs( minEff ) ) * 1, ( origStat >= abs( minEff ) ) * 1 ) ) # get which are both fdr and min eff size significant plotTbl %<>% mutate( sig = pmin( fdrSig, mesSig ) %>% as.character() ) # assign plotTbl to plotTblName in global environment if( !is.null( plotTblName ) ) assign( plotTblName, as_tibble( plotTbl ), envir = globalenv() ) ### PLOT ### plotTbl %<>% separate( split, into = vNameVec ) # width if( eqErrBarWidth & !is.null( facet ) ){ widthPerTbl = plotTbl %>% group_by( V3 ) %>% summarise( count = n() ) %>% mutate( maxCount = max( count ), widthRatio = count/maxCount * 0.95 ) widthLabVec = setNames( widthPerTbl$widthRatio, widthPerTbl$V3 ) plotTbl %<>% mutate( width = widthLabVec[ plotTbl$V3 ] ) } else{ plotTbl %<>% mutate( width = 1 ) } # give values for lb and ub equal to origStat if lb and ub are NAN plotTbl %<>% mutate( lb = Vectorize(ifelse)( is.nan( lb ), origStat, lb ), ub = Vectorize(ifelse)( is.nan( ub ), origStat, ub ) ) # base plot p = ggplot( plotTbl, aes( x = V1 ) ) + # base settings theme_cowplot( font_size = 14 * fontScaleFactor, line_size = 0.5 * lineScaleFactor ) + labs( x = xLab, y = yLab ) + # axes labels geom_hline( yintercept = nullValue, linetype = 2, size = 1 * hLineFactor ) # add a horizontal line at null value if( rotXText ) p = p + theme( axis.text.x = element_text( angle = 90 ) ) # rotate x-axis labels if( !is.null( xAxisLabVec ) ) p = p + scale_x_discrete( labels = xAxisLabVec ) # give x-axis better labels if( remXAxisMarks ) p = p + theme( axis.text.x = element_blank(), axis.ticks.x = element_blank() ) # remove x axis text # add in extra horizontal lines k = ifelse( is.null( hLineVec ), 0, length( hLineVec ) ) while ( k > 0 ){ p = p + geom_hline( yintercept = hLineVec[k], linetype = 2, alpha = 0.4, linetype = 'dotted' ) k = k - 1 } # colour variable if( is.null( colVar ) ){ # if there is no colour variables if( !fdr == 1 ){ p = p + geom_errorbar( aes( ymin = lb, ymax = ub, width = width, linetype = sig ), size = errBarSize, alpha = errBarAlpha ) p = p + scale_linetype_manual( labels = c( "0" = "Not significant", "1" = "Significant" ), name = "", values = c( "0" = errBarLineType, '1' = 'solid' ), drop = FALSE, limits = c( "0", "1" ) ) } if( fdr == 1 ) p = p + geom_errorbar( aes( ymin = lb, ymax = ub, width = width ), size = errBarSize, alpha = errBarAlpha ) p = p + geom_point( aes( y = origStat ), size = pointSize ) # add in points } else if( !is.null( colVar ) ){ # if there are colour variables if( !fdr == 1 ){ p = p + geom_errorbar( aes( ymin = lb, ymax = ub, width = width, col = V2, linetype = sig ), size = errBarSize, alpha = errBarAlpha ) p = p + scale_linetype_manual( labels = c( "0" = "Not significant", "1" = "Significant" ), name = "", values = c( "0" = errBarLineType, '1' = 'solid' ), drop = FALSE, limits = c( "0", "1" ) ) } if( fdr == 1 ) p = p + geom_errorbar( aes( ymin = lb, ymax = ub, col = V2, width = width ), size = errBarSize, position = position_dodge( 1 ), linetype = errBarLineType, alpha = errBarAlpha ) p = p + geom_point( aes( y = origStat, col = V2 ), size = pointSize, position = position_dodge( 1 ) ) + # add in points scale_colour_manual( values = colourVec, labels = colLabVec, name = colLabName) # modify points } # facet variable if( !is.null( facet ) ){ if( is.null( facetLabVec ) ){ p = p + facet_wrap( ~ V3, ncol = nCol, scales = facetScale ) } else{ p = p + facet_wrap( ~ V3, ncol = nCol, scales = facetScale, labeller = labeller( V3 = facetLabVec ) ) } } p } <file_sep>#' Assign selected column indices to #' #' \code{assignSelAxisIndVec} assigns the selected columns in #' \code{.data} from \code{.selAxisLab} to a specified environment. #' #' @param selAxisLab integer vector. Column indices of axes #' to plot on biplot. #' @param data numeric dataframe. Dataframe from which to take #' the labels, if required. #' @param env environment. Environment to which to save the results. #' #' @return Nothing. Assigns values to names in \code{env} directly. assignSelAxisIndVec = function( selAxisLab, data, env ){ # If no axes were pre-specified to be selected, # then return the integer vector from # to the number of columns in .data. if( is.null( selAxisLab ) ){ assign( "selAxisIndVec", 1:ncol( data ), env ) } else{ assign( "selAxisIndVec", which( tbl_vars( data ) %in% selAxisLab ), env ) } } #' Get selected column indices. #' #' \code{getSelAxisInd} returns the indices of the columns #' in \code{data} whose names are in \code{selAxisLab}. #' @param selAxisLab character vector. Names of columns #' whose axes must be shown on biplot. If NULL, then #' all axes must be plotted, and an integer vector #' from 1 to \code{ncol(data)} is returned. #' @param data numeric dataframe. Dataframe from which to draw #' the labels. #' @return Integer vector of columns in \code{data} to plot. getSelAxisInd = function( selAxisLab, data ){ if( is.null( selAxisLab ) ) return( 1:ncol( data ) ) which( tbl_vars( data ) %in% selAxisLab ) } #' Assign values to graphical parameters. #' #' \code{assignGraphPar} assigns values to the names #' used for variables that determine what is plotted. #' #' @param displot,checkPlot logical. If \code{TRUE}, then #' the values for certain graphical parameters given by default #' or in the function call are overridden. See code of #' \code{assignGraphPar} for details. #' @param env environment. Environment to assign values to names in. #' #' @return Nothing. Assigns values to names in \code{env} directly. assignGraphPar = function( dispPlot, checkPlot, env ){ if( dispPlot ){ assign( "axes", TRUE, env ) assign( "points", TRUE, env ) assign( "pointAlpha", 1, env ) assign( "ellipse", TRUE, env ) assign( "ellAlpha", 1, env ) assign( "ellSize", 2, env ) assign( "quant", FALSE, env ) assign( "density", TRUE, env ) assign( "densAlpha", 0.3, env ) assign( "densSize", 1, env ) assign( "addOrigPos", FALSE, env) return( NULL ) } if( checkPlot ){ assign( "axes", FALSE, env ) assign( "points", TRUE, env ) assign( "pointAlpha", 1, env ) assign( "ellipse", TRUE, env ) assign( "ellAlpha", 0.8, env ) assign( "ellSize", 1, env ) assign( "quant", TRUE, env ) assign( "quantAlpha", 0.8, env ) assign( "quantSize", 1, env ) assign( "density", TRUE, env ) assign( "densAlpha", 0.2, env ) assign( "densSize", 1, env ) assign( "addOrigPos", FALSE, env) } NULL } #' Get the measure of location function. #' #' Based on \code{locType}, returns the measure of location desired. #' #' @param locType character. Selects the location type to choose. Options #' are: mean (column-wise median), gmed (geometric median), wei (fast approximate geometric median), oja and cwmed (column-wise median). Default is mean. getLocFunc = function( locType = "mean", .trim = trim ){ if( locType == "mean" ) return( function(x) c( mean( x[[1]] ), mean( x[[2]] ) ) ) if( locType == "cwmed" ) return( function(x) c( median( x[[1]] ), median( x[[2]] ) ) ) if( locType == "oja" ) return( ojaMedian ) if( locType == "gmed" ) return( Gmedian ) if( locType == "wei" ) return( weiszFunc ) stop( "Unrecognised locType selected." ) } #' Return proportion of variation explained. #' #' Convenience function to return the proportion of variation explained #' for the desired principal components, rounded to two decimal places. #' #' @param vec numeric vector. Contains component-wise proportion of #' variation. #' @param comp integer vector. Specifies the principal components #' whose proportion of variation must be returned. Defaults to 1:2. #' #' @return Numeric vector. calcRoundPropVar = function( vec, comp = 1:2 ){ laply( comp, function(x) round( vec[ x ], 2 ) * 100 ) } <file_sep>context ( "testing calcP and calcPSub" ) # Data -------------------------------------------------------------------- # Functions calcStat = function( x ) mean( x, trim = 0.02 ) calcSE = function(x) { boot::boot( x, R = 20, function(x,w) calcStat( x[w] ) )$t %>% sd() } calcBootStat = function( x ) mean( x, trim = 0.02 ) calcBootSE = function(x) { boot::boot( x, R = 20, function(x,w) calcStat( x[w] ) )$t %>% sd() } calcBootStatVec = function( x, w ) c( calcBootStat( x[w] ), calcBootSE( x[w] ) ) # Data respVec = c( 0.498767, 0.154696, 0.317299, 0.25632, 0.428, 1.48165, 1.601475, 0.385599, 0.217408 ) nullValue = 0.02 # Intermediate calculations origStat = calcStat( respVec ) origSE = calcSE( respVec ) set.seed(1) bootStatTbl = boot::boot( respVec, R = 2e2, calcBootStatVec )$t %>% as_tibble() %>% rename( bootStat = V1, bootSE = V2 ) # Percentile nullBootStat = bootStatTbl$bootStat - origStat + nullValue # centred at null nullOrigStat = origStat - nullValue # difference from null nullBootTStat = (bootStatTbl$bootStat - origStat + nullValue )/bootStatTbl$bootSE nullOrigTStat = ( origStat - nullValue ) / origSE prop = sum( nullBootStat < nullOrigStat ) / nrow( bootStatTbl ) # prop less than propT = sum( nullBootTStat < nullOrigTStat ) / nrow( bootStatTbl ) propHigh = 1 - prop propBoth = 2 * min( prop, propHigh ) propTVecLow = c( prop, propT ) propTVecHigh = 1 - propTVecLow diffNullProp = sum( ( bootStatTbl$bootStat - origStat + 0.3 ) < (origStat - 0.3 ) ) / nrow( bootStatTbl ) if( FALSE ){ par(mfrow=c(2,2)) hist(respVec) hist(bootStatTbl$bootStat) hist( nullBootStat ) par(mfrow=c(2,2)) hist( ( bootStatTbl$bootStat - nullValue ) / bootStatTbl$bootSE ) hist( nullBootTStat ) plot( bootStatTbl$bootStat, ( bootStatTbl$bootStat - nullValue ) / bootStatTbl$bootSE ) plot( bootStatTbl$bootStat, ( bootStatTbl$bootStat ) / bootStatTbl$bootSE ) plot( bootStatTbl$bootStat, bootStatTbl$bootSE ) } # Tests ------------------------------------------------------------------- test_that( "calcP works", { # perc expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.02, altSide = 'high', method = 'perc' ), propHigh ) #altSide high expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.02, altSide = 'low', method = 'perc' ), prop ) # altSide low expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.02, altSide = 'both', method = 'perc' ), propBoth ) # altSide both expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.02, altSide = NULL, method = 'perc' ), propBoth ) # altSide NULL # percT expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.02, altSide = 'low', method = 'percT', origSE = origSE ), propTVecLow ) #altSide high expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.02, altSide = 'high', method = 'percT', origSE = origSE ), propTVecHigh ) #altSide high # null value 0 expect_equal( calcP( bootData = bootStatTbl, origStat = origStat, nullValue = 0.3, altSide = "low", method = 'perc' ), diffNullProp ) }) test_that( "calcPSub works", { expect_equal( calcPSub( 0.01, "high" ), 0.99 ) expect_equal( calcPSub( 0.01, "low" ), 0.01 ) expect_equal( calcPSub( 0.01, "both" ), 0.02 ) }) <file_sep>#' @import ggplot2 #' @importFrom cowplot theme_cowplot #' @importFrom plyr llply laply ldply #' @import stringr #' @import pryr #' @import dplyr #' @import doParallel #' @import foreach #' @import parallel #' @import iterators #' @importFrom tidyr spread gather separate #' @importFrom magrittr %>% %<>% extract extract2 or and #' @importFrom tibble tibble as_tibble is_tibble NULL <file_sep>--- output: md_document: variant: markdown_github --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, echo = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-", tidy = TRUE ) ``` # ggboot The package ggboot provides the functions used to compile the figures in the package VaccComp for the paper 'A comparison of antigen-specific T cell responses induced by six novel tuberculosis vaccine candidates'. You can install ggboot from Github using the following code: ```{r echo = TRUE, eval = FALSE} devtools::install_github( "MiguelRodo/ggboot" ) ``` <file_sep>#' Bootstrap location measures for multiple groups. #' #' @param data dataframe. Numeric dataframe in wide format. #' @param group character vector. Vector indicating group membership #' for each observation in \code{data}. #' @param calcLoc function. Returns multivariate measure of location. #' @inheritParams ggbootUV calcMVBoot = function( data, group, B, calcLoc ){ # table of estimated mv locs across groups ldply( split( data, group ), function( x ){ calcGroupMVBoot( x, B, calcLoc ) } ) %>% dplyr::rename( group = .id ) %>% as_tibble() } #' Bootstrap location measures for a single group. #' #' @inheritParams calcMVBoot #' @inheritParams ggbootUV calcGroupMVBoot = function( data, B, calcLoc ){ ldply( 1:B, function(i) calcBootSampleGroupMVBoot( data, calcLoc ) ) } #' Bootstrap location measure. #' #' @inheritParams calcMVBoot calcBootSampleGroupMVBoot = function( data, calcLoc ){ data %>% sample_frac( replace = TRUE ) %>% calcLoc() } <file_sep> pcaBiplotPlotFunc = function( numTbl, infoTbl, pcCompNum1 = 1, pcCompNum2 = 2, ellipseVec = NULL, legendTitle, labelVec, colVec, scale = FALSE, centre = TRUE, ellipse = TRUE, medPos = TRUE, textAdjVal = 0.2, pointSize = 3, xMult = 1 ){ # pca Obj pcaObj = calcBiplot( dataTibble = numTbl, infoTbl = infoTbl, scale = scale, centre = centre, pcCompNum1 = pcCompNum1, pcCompNum2 = pcCompNum2, ellipseGroupVec = ellipseVec, textAdjVal = textAdjVal ) # median positions # cumulative proportion of variation varProp1 = round( pcaObj$compPropVarVec[ pcCompNum1 ], 2 ) * 100 varProp2 = round( pcaObj$compPropVarVec[ pcCompNum2 ], 2 ) * 100 # plot p = ggplot( pcaObj$pcaScoreAndInfoTbl ) + geom_line( data = pcaObj$axesCoordTbl %>% filter( segmentPos != 'max' ), aes( x = x * xMult, y = y, group = varName ), col = 'gray10' ) + geom_line( data = pcaObj$axesCoordTbl %>% filter( segmentPos != 'min' ), aes( x = x * xMult, y = y, group = varName ), col = 'gray10' ) + labs( x = str_c( 'PC', pcaObj$pcCompNumVec[1], " - ", varProp1, "%" ), y = str_c( 'PC', pcaObj$pcCompNumVec[2], " - ", varProp2, "%" ) ) + coord_fixed() # ellipses and point colours if( is.null( ellipseVec ) ){ p = p + geom_point( aes( x = V1 * xMult, y = V2 ), size = pointSize ) # + # geom_text( data = medPosTbl, aes( x = medV1, y = medV2, label = labelVec ), # size = 4, fontface = 'bold' ) + } else { p = p + geom_point( aes( x = V1 * xMult, y = V2, col = ellipseVec ), size = pointSize ) + scale_colour_manual( name = legendTitle, label = labelVec, values = colVec ) # ellipse if( ellipse ){ p = p + geom_path( data = pcaObj$ellipseTbl, aes( x = x * xMult, y = y, colour = group, group = group ), size = 1 ) } #if medPos == TRUE if( medPos == TRUE ){ medPosTbl = pcaObj$pcaScoreAndInfoTbl %>% # select( -ellipseGroupVec ) %>% # mutate( vaccine = wInfoTbl$vaccine, vaccInfGroup = wInfoTbl$vaccInfGroup ) %>% group_by( ellipseGroupVec ) %>% summarise( medV1 = median(V1), medV2 = median(V2) ) p = p + geom_text( data = medPosTbl, aes( x = medV1 * xMult, y = medV2, label = labelVec ), size = 4, fontface = 'bold' ) } } # add labels p = p + annotate( 'text', x = pcaObj$textXVec * xMult, y = pcaObj$textYVec, label = tbl_vars( numTbl ), size = 4, col = 'brown4' ) # return p } <file_sep>#' Find and correct row of a specific categorical variable combination. #' #' Used for the \code{ggbootPW} function, where it may be desired #' that the variables are put in a specific order along the x and y-axis. #' Finds the row in a dataframe corresponding to a specific 'x' and 'y' combination, #' but where the elements that should be in 'x' may be in 'y', and vice versa. It #' returns that row, with the elements swopped around if need be. If the elements are swopped, #' the column labelled 'origStat' is multiplied by -1. #' #' @param xVar,yVar numeric/character. Elements to set as 'x' and 'y' variables, respectively. #' @param plotTbl dataframe. Dataframe with columns x, y and origStat. May have other columns. #' The combination \code{xVar} and \code{yVar} must only occur once in \code{plotTbl}, regardless of order. #' @return Row of dataframe as a dataframe. #' @examples findXYRow( 1, 2, data.frame(x = c( 3, 1, 1 ), #' y = c( 2, 2, 1 ), #' origStat = c( 0.5, 0.3, -0.2 ) ) ) findXYRow = function( yVar, xVar, plotTbl ){ origRow = plotTbl %>% filter( x == xVar | y == xVar ) %>% filter( x == yVar | y == yVar ) if( origRow$x != xVar ) origRow[["origStat"]] = -origRow[["origStat"]] origRow %>% mutate( x = xVar, y = yVar ) } #' Set a categorical variable as x-variable, with all remaining y-variables. #' #' Returns the rows of plotTbl with the selected group as the x-variable, and #' all the y-variables that are "smaller" than this variable, as defined by \code{sortVec}. #' #' @param i numeric. \code{sortVec[1:(length(sortVec)-i)]} are searched for as y-variables, and #' \code{rev( sortVec )[i]} is set as the x-variable. #' @inheritParams findXYRow #' @param sortVec character vector. Order in which groups are to display along x- and y-axes. The #' first group along the x-axis is the last element of \code{sortVec}. #' @return Dataframe with the columns along x and y-axes changed appropriately, for the specific variables #' as set by \code{i} and \code{sortVec}. #' @examples findXTbl( 1, 1:2, data.frame(x = c( 3, 1, 1 ), #' y = c( 2, 2, 1 ), #' origStat = c( 0.5, 0.3, -0.2 ) ) ) findXTbl = function( i, sortVec, plotTbl ){ xVar = rev( sortVec )[i] yVarList = sortVec[1:(length(sortVec)-i)] %>% as.list() ldply( yVarList, findXYRow, xVar = xVar, plotTbl = plotTbl ) } #' Sort x- and y-columns by size of response for an individual facet. #' #' This assumed that all the data is from an individual facet. #' #' @param data dataframe. Has columns group, resp and facet. The column 'group' specifies individual group, #' 'resp' response and 'facet' overall facet. #' @param plotTbl dataframe. Has columns .id, x, y and origStat. May have other columns. The column '.id' specifies overall facet, #' 'x' and 'y' the specific groups compared in a row, and 'origStat' how much larger the variable level in 'y' is than the variable #' level in 'x' (at least for \code{ggbootPW}; for other functions it could be the other way around the code would run fine). #' @return Dataframe with columns along x- and y-axes changed appropriately. #' @export findSortedIndTbl = function( data, plotTbl, calcStat ){ # table of groups sorted by average response size sortTbl = data %>% filter( facet == plotTbl$.id[1] ) %>% group_by( group ) %>% summarise( mean = calcStat( resp ) ) %>% arrange( mean ) # vector of group names sorted by average response size sortVec = sortTbl$group sortLabVec = setNames( length( sortVec ):1, sortTbl$group ) outTbl = ldply( seq_along( sortVec[-1]), findXTbl, sortVec = sortVec, plotTbl = plotTbl ) %>% mutate( x = as.character( sortLabVec[x] ), y = as.character( sortLabVec[y] ) ) outTbl %>% mutate( x = str_c( .id, ".", x ), y = str_c( .id, ".", y ) ) %>% arrange( .id, x, y ) } #' Sort x- and y-columns by size of response across facets. #' #' This sorts within facet. #' #' @param data dataframe. Has columns group, resp and facet. The column 'group' specifies individual group, #' 'resp' response and 'facet' overall facet. #' @param plotTbl dataframe. Has columns .id, x, y and origStat. May have other columns. The column '.id' specifies overall facet, #' 'x' and 'y' the specific groups compared in a row, and 'origStat' how much larger the variable level in 'y' is than the variable #' level in 'x' (at least for \code{ggbootPW}; for other functions it could be the other way around the code would run fine). #' @return Dataframe with columns along x- and y-axes changed appropriately. #' data = data.frame( facet = c( rep( 0, 6 ), rep( 1, 8 ) ), #' group = c( 1, 1, 2, 2, 3, 3, 1, 1, 3, 3, 2, 2, 4, 4 ), #' resp = c( 0.1, 0.3, 5, 2, -2, 1, 5, 2, 3, 4, 5, 6, 7, 3 ) ) #' plotTbl = data.frame( .id = c( rep( 0, 3 ), rep( 1, 6 ) ), #' x = c( '1', '1', '2', '1', '1', '1', '2', '2', '3' ), #' y = c( '2', '3', '3', '2', '3', '4', '3', '4', '4' ), #' origStat = c( 0, 5, 3, 2, 5, 4, 2, 10, 10 ) ) #' findSortedTbl( data, plotTbl) #' @export findSortedTbl = function( data, plotTbl, calcStat ){ plotTbl %<>% mutate( .id = as.character( .id ), x = as.character( x ), y = as.character( y ) ) data %<>% mutate( facet = as.character( facet ), group = as.character( group ) ) ldply( split( plotTbl, plotTbl$.id ), findSortedIndTbl, data = data, calcStat = calcStat ) } #' Change group labels according to sorted response size, within a facet. #' @param data dataframe. Dataframe with columns 'group' and 'resp', where the elements in 'resp' are the responses of #' individual subjects, and elements in 'group' specify the subject group. #' @param groupLabVec named character vector. Specifies labels for each of the unique elements in the 'group' column of #' \code{data}. #' @return A named vector, where the groups are sorted according to response size. #' @examples #' data = data.frame( group = c( 1, 1, 1, 2, 2, 2, 3, 3, 3 ), #' resp = c( 5, 4, 6, 10, 12, 7, 6, 1, 4 ) ) #' groupLabVec = c( "1" = "A", "2" = "B", "3" = "C" ) #' sortIndGroupLabVec( data, groupLabVec ) sortIndGroupLabVec = function( data, groupLabVec, calcStat ){ sortTbl = data %>% group_by( group ) %>% summarise( mean = calcStat( resp ) ) %>% arrange( mean ) setNames( groupLabVec[ sortTbl$group ], as.character( nrow( sortTbl ):1 ) ) } #' Change group labels according to sorted response size. #' #' @inheritParams sortIndGroupLabVec #' @param data dataframe. Dataframe with columns 'facet', 'group', 'resp'. The elements in 'resp' are the responses of #' individual subjects, elements in 'group' specify the subject group, and elements in 'facet' specify the overall #' grouping variable. #' @return A named vector, where the groups are sorted according to response size. #' data = data.frame( group = c( 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 3 ), #' resp = c( 5, 4, 6, 10, 12, 7, 6, 1, 4, 4, 8, 7 ), #' facet = c( rep( "0", 9 ), rep( "1", 3 ) ) ) #' groupLabVec = c( "1" = "A", "2" = "B", "3" = "C" ) #' sortGroupLabVec( data, groupLabVec ) #' @export sortGroupLabVec = function( data, groupLabVec, calcStat ){ llply( split( data, data$facet ), sortIndGroupLabVec, groupLabVec = groupLabVec, calcStat = calcStat ) %>% unlist() } <file_sep>#' Compute pair-wise comparisons estimates and bootstrap statistics #' #' Calculates the mean or median sample estimates of all #' pair-wise differences within a factor. Can be set #' compute the maximum Bayes factors (MBFs) and indicate #' which of the comparisons are statistically #' significant after controlling the false discovery rate, if the number of bootstrap repetition (\code{B}) is set to greater than 0. #' #' @param data dataframe. Contains numeric variable named 'resp' for responses and character variable named 'group' containing factor levels. #' @param B integer. Number of bootstrap samples per subgroup. If equal to zero, then the MBF is not calculated. #' @inheritParams ggbootUV #' @return A tibble of the comparison groups and estimates of differences in \code{calcStat}, as well as the confidence intervals and MBFs if bootstrapping was performed. #' @export calcPW = function( data, calcStat, trim = 0.2, B, seB, method = "percT", fdr = FALSE ){ # FLOW # # Parallel I # - Purpose: # -- Closes cl1 if it exists when the function closes. # # Functions # - Purpose: # -- Creates functions to calculate sample statistic and sample statistic standard # -- deviation, both for the original sample and for use in boot::boot. # - Code: # -- calcStat # --- calculates mean or median # -- calcSE # --- Calculates standard deviation of calcStat # -- calcBootStatVec # --- If method is "perc", then only calculates calcStat # --- for each bootstrap sample to save time. # --- If method is "percT", then it calculates both # --- calcStat and calcSE for each bootstrap sample. # # Combinations # - Purpose: # -- Calculates all unique pair-wise combinations. # # Raw original statistics # - Purpose # -- Calculates calcStat and, if method == "percT", # -- calcSE, for each group. This is needed for calculating # -- the original statistics for # -- ( stat1 - stat0 ) (for method == "perc" ) and # -- ( stat1 - stat0 ) / sqrt( se1^2 + se2^2) # # Original statistics # - Purpose # -- Calculates original statistics, as described above, # -- for each pair-wise combination, as found in # -- the 'Combinations' section. # - Code: # -- Calculates only origStat if method == "perc", # -- and both origStat and origSE if method == "percT". # # Sample differences only # - Purpose: # -- Returns the original statistics as calculated above, # -- if no statistical significance testing is to be performed. # - Code: # -- This is set to happen if fdr is NULL. # # Parallel II # - Purpose # -- Once it's confirmed that bootstrapping is required to # -- calculate p-values, since not only sample differences # -- are being returned, a cluster is initiated. # # Raw bootstrap statistics # - Purpose # -- Similary to 'Raw original statistics', # -- calcStat and, if method == "percT", calcSE, # -- are calculated for each bootstrap sample # -- from each individual group. # # Statistics # on.exit( if( exists( "cl1" ) ) parallel::stopCluster( cl1 ) ) # Functions if( identical( calcStat, "median" ) ){ calcStat = function(x) matrixStats::colMedians( as.matrix( x, ncol = 1 ) ) calcSE = function(x) { boot::boot( x, R = seB, function(x,w) matrix( x[w], ncol = 1 ) %>% matrixStats::colMedians() )$t %>% sd() } } else if( identical( calcStat, "mean" ) ){ calcStat = function( x ) mean( x, trim ) calcSE = function(x) { boot::boot( x, R = seB, function(x,w) mean( x[w], trim ) )$t %>% sd() } } else{ stop( "calcStat must be either 'mean' or 'median'") } if( method == "percT" ) calcBootStatVec = function( x, w ) c( calcStat( x[w] ), calcSE( x[w] ) ) if( method == "perc" ) calcBootStatVec = function( x, w ) calcStat( x[w] ) # Combinations combnVec = calcUniqueCombn( data$group ) # Raw original statistics if( method == "perc" ) rawOrigStatTbl = data %>% group_by( group ) %>% summarise( rawOrigStat = calcStat( resp ) ) if( method == "percT" ) rawOrigStatTbl = data %>% group_by( group ) %>% summarise( rawOrigStat = calcStat( resp ), rawOrigSE = calcSE( resp ) ) # Original statistics if( method == "perc" ) origStatTbl = tibble( split = combnVec ) %>% mutate( split1 = split ) %>% separate( split1, into = c( "y", "x" ) ) %>% group_by( x, y, split ) %>% summarise( origStat = rawOrigStatTbl$rawOrigStat[ rawOrigStatTbl$group == x ] - rawOrigStatTbl$rawOrigStat[ rawOrigStatTbl$group == y ] ) %>% ungroup() if( method == "percT" ) origStatTbl = tibble( split = combnVec ) %>% mutate( split1 = split ) %>% separate( split1, into = c( "y", "x" ) ) %>% group_by( x, y, split ) %>% summarise( origStat = rawOrigStatTbl$rawOrigStat[ rawOrigStatTbl$group == x ] - rawOrigStatTbl$rawOrigStat[ rawOrigStatTbl$group == y ], origSE = ( rawOrigStatTbl$rawOrigSE[ rawOrigStatTbl$group == x ]^2 + rawOrigStatTbl$rawOrigSE[ rawOrigStatTbl$group == y ]^2 )^0.5 ) %>% mutate( origTStat = origStat / origSE ) %>% ### should be ( origStat - nullValue ) / origSE ungroup() # Sample differences only if( is.null( fdr ) ) return( origStatTbl ) # Parallel II cl1 = parallel::makeCluster(parallel::detectCores()-1) doParallel::registerDoParallel(cl1) # Raw bootstrap statistics rawBootStatTbl = ldply( split( data, data$group ), function(x) boot::boot( x$resp, calcBootStatVec, B )$t, .parallel = TRUE ) %>% rename( group = .id, rawBootStat = `1` ) if( method == "percT" ) rawBootStatTbl %<>% rename( rawBootSE = `2` ) # Statistics statTbl = ldply( split( origStatTbl, origStatTbl$split ), function( tbl ){ xRawBootStatVec = rawBootStatTbl %>% filter( group == tbl$x ) %>% `[[`( "rawBootStat" ) yRawBootStatVec = rawBootStatTbl %>% filter( group == tbl$y ) %>% `[[`( "rawBootStat" ) bootStatVec = xRawBootStatVec - yRawBootStatVec origStat = origStatTbl %>% filter( x == tbl$x & y == tbl$y ) %>% `[[`( "origStat" ) z0 = calcBCaZ0( bootStatVec, origStat ) if( method == "perc" ){ alphaHigh = sum( ( bootStatVec - origStat ) >= origStat ) / length( bootStatVec ) alphaLow = sum( ( bootStatVec - origStat ) <= origStat ) / length( bootStatVec ) } if( method == "percT" ){ xRawBootSEVec = rawBootStatTbl %>% filter( group == tbl$x ) %>% `[[`( "rawBootSE" ) yRawBootSEVec = rawBootStatTbl %>% filter( group == tbl$y ) %>% `[[`( "rawBootSE" ) bootStatSE = sqrt( xRawBootSEVec^2 + yRawBootSEVec^2 ) origSE = origStatTbl %>% filter( x == tbl$x & y == tbl$y ) %>% `[[`( "origSE" ) origTStat = origStatTbl %>% filter( x == tbl$x & y == tbl$y ) %>% `[[`( "origTStat" ) bootTStatVec = ( bootStatVec - origStat ) / bootStatSE z0T = calcBCaZ0( bootStatVec / bootStatSE, origStat / origSE ) alphaHigh = sum( bootTStatVec >= origTStat ) / length( bootTStatVec ) alphaLow = sum( bootTStatVec <= origTStat ) / length( bootTStatVec ) } pVal = 2 * min( alphaHigh, alphaLow ) splitStatTbl = tibble( x = tbl$x, y = tbl$y, split = tbl$split, p = pVal, origStat = origStat, z0 = z0 ) if( method == "percT" ) splitStatTbl %<>% mutate( z0T = z0T ) if( "facet" %in% colnames(data) ) splitStatTbl %<>% mutate( facet = data$facet[1] ) splitStatTbl }, .parallel = TRUE ) statTbl %>% mutate( .id = facet ) %>% select( -facet ) } <file_sep>#' Subtract second half of a vector from the first. #' #' x sub_second_half = function( numVec ){ n2 = length( numVec )/2; numVec[(n2+1):(2*n2)]-numVec[1:n2] } #' Sort a table in some way. #' #' x sortTblFunc = function( dataTbl, level ){ dataRowList = split( dataTbl, 1:nrow( dataTbl ) ) ldply( dataRowList, function( splitTbl, currLevel = level ){ if( splitTbl$x == currLevel ) return( splitTbl ) if( splitTbl$x != currLevel ){ splitTbl$y = splitTbl$x splitTbl$x = currLevel splitTbl } } ) %>% select( -.id) } #' Split by vaccine within a specified splitting vector. #' #' x fullSplitFunc = function( currTbl, splitVec1){ llply( llply( split( currTbl, splitVec1 ), function(x) split( x, x$vaccine ) ) ) } #' Calculate the 2.5% quantile. #' #' x llbFunc = function(x){ quantile( x, p = 0.025, na.rm = TRUE ) } #' Calculate the 97.5% quantile. #' #' x uubFunc = function(x){ quantile( x, p = 0.975, na.rm = TRUE ) } #' correct using bh procedure #' #' x #' @export correctBH = function( pVec, fdr, nSide ){ sortPVec = sort( pVec ) ind = 0; i = 0; m = length(sortPVec); k = 0; q = fdr/nSide while( i <= m - 1 ){ i = i + 1 if( sortPVec[i] <= (i/m * q) ) k = i } if( k > 0 ){ if( is.null( names( sortPVec ) ) ) return( which( pVec %in% sortPVec[1:k] ) ) return( names(sortPVec)[1:k] ) } NULL } #' Calculate unique combinations #' #' x calcUniqueCombn = function( charVec, diff = TRUE ){ allPwCombnVec = combn( unique( charVec ), 2 ) uniquePwCombnVec = NULL for( i in 1:ncol( allPwCombnVec ) ){ if( and( diff, allPwCombnVec[1,i] == allPwCombnVec[2,i]) ) next currCombn = str_c( allPwCombnVec[,i], collapse = "_" ) currCond = !or( currCombn %in% uniquePwCombnVec, rev( currCombn ) %in% uniquePwCombnVec ) if( currCond ) uniquePwCombnVec = append( uniquePwCombnVec, currCombn ) } uniquePwCombnVec } #' Calculate maximum Bayes factor. #' #' upper bound bayes factor #' @export calcBF = function(p) -1/(exp(1) * p * log(p)) calcMinMax = function(x) c( "min" = min(x), "max" = max(x) ) #' Calculate min and max #' #' Wrapper function around min and max that returns as a vector the minimum and maximum of a vector. #' #' @param x A numeric vector. #' @return A named numeric vector of the minimum and maximum value. #' @examples #' calcMinMax(rnorm(20)) #' calcMinMax(1:10) #' @export calcMinMax = function(x) c( "min" = min(x), "max" = max(x) ) #' Calculate number of unique vector elements. #' #' Convenience function around \code{length()} and \code{unique()} #' that calculates the number of unique elements in a vector. #' #' @param x vector. #' @export calcLU = function(x) length( unique( x ) ) <file_sep>#' Pair-wise comparisons plot #' #' Plot the estimates or maximum Bayes factors (MBFs) pair-wise comparisons in terms of a summary statistic between all levels of a factor. BCa bootstrapping is used to obtain the maximum Bayes factor. #' #' @inheritParams ggbootUV #' @param groupLabVec named character vector. Labels for grouping vector. Optional. #' @param B integer. Number of bootstrap repetitions. If greater than 0, the plot displays the MBF rather than the estimate of the difference. If 0, then no bootstrapping is performed and the sample values for \code{calcStat} are displayed. #' @param group unquoted expression. Group variable name. #' @param axisLab character. X- and y-axis titles. #' @param rotX logical. If TRUE, x-axis titles are rotated 90 degrees. #' @param ncol integer. Number of facet variable columns. #' @param text logical. If TRUE, the difference estimates or MBFs are written over each grid point. #' @param textSize numeric. Size of text. #' @param plot logical. If TRUE, then a plot is outputted. #' @param facetScale 'fixed' or 'free'. Input for scale argument of \code{ggboot::facet_wrap}. Forced to \code{'free'} if \code{sort=TRUE}. #' @param scale logical. Whether to sort x- and y-axes text by size of response. Default is \code{TRUE}. #' @export ggbootPW = function( data, resp, group, facet = NULL, B = 1e2, seB = 1e1, calcStat = "mean", trim = 0.2, fdr = NULL, minEff = 0, groupLabVec = NULL, facetLabVec = NULL, axisLab = NULL, ncol = 2, facetOrderVec = NULL, rotX = FALSE, method = "percT", facetScale = 'fixed', text = TRUE, textSize = 3, plotTblName = NULL, plot = TRUE, fillLabVec = NULL, fillColVec = NULL, sort = TRUE ){ # data tempTbl = data.frame( group = data[[ deparse( substitute( group ) ) ]], resp = data[[ deparse( substitute( resp ) ) ]] ) if( !is.null( substitute( facet ) ) ) tempTbl[[ "facet" ]] = data[[ deparse( substitute( facet ) ) ]] data = tempTbl %>% as_tibble() %>% mutate_if( is.factor, as.character ) # if( is.null( fillLabVec ) ){ if( !sort ){ fillLabVec = c( "0" = "Not significant", "0.1" = "Left vaccine significantly larger", "1.1" = "Bottom vaccine significantly larger" ) } else{ fillLabVec = c( "0" = " Not significant ", "1.1" = " Significant " ) } } if( is.null( fillColVec ) ){ if( !sort ){ fillColVec = c( "0" = "gray94", "0.1" = "orange", "1.1" = "royalblue1" ) } else{ fillColVec = c( "0" = "gray94", "1.1" = "orange" ) } } if( !sort ){ fdrLegTitle = "Statistical\nSignificance" } else{ fdrLegTitle = "" } ### BOOTSTRAP STATISTICS if( is.null( substitute( facet ) ) ) plotTbl = calcPW( data = data, calcStat = calcStat, trim = trim, B = B, seB = seB, method = method, fdr = fdr ) if( !is.null( substitute( facet ) ) ) plotTbl = ldply( split( data, data$facet ), function(x) calcPW( data = x, calcStat = calcStat, trim = trim, B = B, seB = seB, method = method, fdr = fdr ) ) if( is.null( groupLabVec ) ) groupLabVec = setNames( unique( data$group ), unique( data$group )) if( is.null( axisLab ) ) axisLab = "Group" if( sort ){ if( identical( calcStat, "mean" ) & trim != 0 ){ selTrim = trim calcStat = pryr::partial( mean, trim = selTrim ) } else{ calcStat = get( calcStat ) } origGroupLabVec = groupLabVec groupLabVec = sortGroupLabVec( data, groupLabVec, calcStat = calcStat ) facetScale = 'free' plotTbl = findSortedTbl( data, plotTbl, calcStat = calcStat ) } ### CORRECTIONS FOR MULTIPLE TESTING if( !is.null( fdr ) ){ if( !is.null( substitute( facet ) ) ) plotTbl %<>% mutate( split = str_c( .id, split ) ) sigNameVec = correctBH( setNames( plotTbl$p, plotTbl$split ), fdr, 2 ) plotTbl %<>% mutate( fdrSig = ( split %in% sigNameVec ) * 1, mesSig = pmax( ( origStat <= -abs( minEff ) ) * 1, ( origStat >= abs( minEff ) ) * 1 ), sig = pmin( fdrSig, mesSig ) %>% as.character(), xLarger = Vectorize(ifelse)( origStat >= 0, "1", "0" ), xLarger.Sig = Vectorize( ifelse )( sig == 0, "0", str_c( xLarger, ".", sig ) ) ) ### MBF CALC if( text ) plotTbl %<>% mutate( mbf = Vectorize(calcBF)( p ), isNanMbf = is.nan( mbf ), mbf = Vectorize(ifelse)( isNanMbf, calcBF(1/B), mbf ) ) %>% select( -isNanMbf ) } ### OUTPUT TBL if( !is.null( plotTblName ) ){ if( sort ){ invOrigGroupLabVec = setNames( names( origGroupLabVec ), origGroupLabVec ) retPlotTbl = plotTbl %>% mutate( x = invOrigGroupLabVec[ groupLabVec[x]], y = invOrigGroupLabVec[ groupLabVec[y]] ) # convert x and y to original } else{ retPlotTbl = plotTbl } assign( plotTblName, as_tibble( retPlotTbl ), envir = globalenv() ) } if( !plot ) return() # if you just want the plotTbl ### PLOT p = ggplot( plotTbl, aes( x, y ) ) + labs( x = axisLab, y = axisLab ) + scale_x_discrete( labels = groupLabVec ) + scale_y_discrete( labels = groupLabVec ) if( rotX ) p = p + theme( axis.text.x = element_text( angle = 90 ) ) # just estimates if( is.null( fdr ) ){ p = p + geom_tile( aes( fill = origStat ), col = "black" ) + scale_fill_gradient2( low = "royalblue1", high = "orange", name = "Decrease\nin Row" ) if( text ) p = p + geom_text( aes( label = as.character( round( origStat, 2 ) ) ), size = textSize ) # if to be faceted if( is.null( substitute( facet ) ) ) return( p ) if( is.null( facetLabVec ) ) facetLabVec = setNames( data$facet, data$facet ) p = p + facet_wrap( ~ .id, labeller = labeller( .id = facetLabVec ), ncol = ncol, scale = facetScale ) return( p ) } p = p + geom_tile( aes( fill = xLarger.Sig ), col = "black" ) + scale_fill_manual( values = fillColVec, name = fdrLegTitle, labels = fillLabVec ) if( text ) p = p + geom_text( aes( label = as.character( round( mbf, 0 ) ) ), size = textSize ) # facet wrap if( is.null( facetLabVec ) ) facetLabVec = setNames( unique( data$facet ), unique( data$facet ) ) if( !is.null( substitute( facet ) ) ) p = p + facet_wrap( ~ .id, labeller = labeller( .id = facetLabVec ), ncol = ncol, scale = facetScale ) p } <file_sep> #' mv med plot info func #' #' x #' PCA biplot with bootstrap confidence areas. #' #' Plot a PCA biplot with bootstrap confidence ares. #' #' @inheritParams ggbootUV #' @inheritParams getSelAxisInd #' @inheritParams getLocFunc #' @inheritParams calcRoundPropVar #' @param data dataframe. In wide format. Only numeric columns will be used. #' @param group vector. Vector indicating group membership for each observation in \code{data}. #' Will be coerced to a character vector. #' @param boot logical. If TRUE, then bootstrap is re-performed. If FALSE, then #' bootstrap values are taken from object with name \code{name} in environment \code{bootList}. #' @param name character. Name of object in \code{bootList} to add to or take to. Must not be #' NULL if \code{save=TRUE}. #' @param save logical. If \code{TRUE} and \code{boot=TRUE}, then bootList is #' @param env environment. Environment to save bootstrapped values to. #' @param path character. Path of to save bootstrapped values to, or load bootstrapped values from. #' @param quant logical. If \code{TRUE}, then univariate 95 percent percentile bootstrap confidence #' intervals are plotted. #' @param textAdjVal numeric. Value that controls the degree to which the axis labels are shifted from #' the endpoints of the axes. Higher values move the axis further right and up. #' @param axesLenRatio numeric. If not NULL, then the ratio of the length of the y-axis divided by the #' x-axis is made equal to \code{axesLenRatio}, where length is defined as the difference between the maximum and the #' minimum value plotted along that axis. This is done by stretching the shorter axis around its mean. Useful #' for making the axes of equal length. #' @param qualCutoff numberic. The minimum sum of the axis predictivity across the principal components selected (by \code{comp}) required for the axis of a variable to be plotted. Only works if \code{arrow=FALSE} (this will change in future). #' @param arrow logical. If TRUE, then arrows instead of lines are plotted for the axes. The arrows point from #' the origin to the largest observed value for its variable on the biplot axis. #' @param arrowSize numeric. Size of the arrows for \code{ggplot2} to use. #' @param fontScaleFactor numeric. Ratio by which to multiply the default font size. #' @export ggbootMV = function( data, group, B, seed = NULL, comp = 1:2, locType = "mean", scale = FALSE, checkPlot = FALSE, dispPlot = FALSE, labelVec = NULL, legendTitle = "Group", colVec = c( 'darkorchid1', 'springgreen2', 'maroon1', 'dodgerblue', 'red', 'yellow3', 'cyan2', "orange2" ), addOrigPos = TRUE, pcaAxesLabSize = 2.5, origPosLabSize = 2, axes = TRUE, points = TRUE, pointAlpha = 1, pointSize = 1, ellipse = TRUE, ellAlpha = 1, ellSize = 1, quant = FALSE, quantAlpha = 1, quantSize = 1, density = FALSE, densAlpha = 1, densSize = 1, boot = TRUE, save = FALSE, name = NULL, env = NULL, path = NULL, textAdjVal = 0.2, axesLenRatio = NULL, qualCutoff = 0, selAxisLab = NULL, arrow = FALSE, arrowSize = 2, fontScaleFactor = 1, trim = 0.2 ){ # force(trim) # data edit group = as.character( group ) data %<>% select_if( is.numeric ) comp = sort( comp ) if( is.null( labelVec ) ) labelVec = setNames( unique( group ), unique( group ) ) # get indices of columns selected by selAxixLab selAxisIndVec = getSelAxisInd( selAxisLab, data ) # assign graphical parameters assignGraphPar( dispPlot, checkPlot, environment() ) # location function calcLoc = getLocFunc( locType ) # pca biplotList = calcBiplot( dataTibble = data, scale = scale, ellipseGroupVec = group, pcCompNum1 = comp[1], pcCompNum2 = comp[2], textAdjVal = textAdjVal ) attach( biplotList ) # proportion of variation propVarVec = calcRoundPropVar( compPropVarVec, comp ) # ellipses mvObj = calcMV( data = data, group = group, B = B, seed = seed, comp = comp, scale = scale, calcLoc = calcLoc, boot = boot, save = save, name = name, env = env, path = path, quant = quant, trim = trim ) attach( mvObj ) xlimVec = calcMinMax( c( textXVec, pcaScoreAndInfoTbl$V1 ) ) ylimVec = calcMinMax( c( textYVec, pcaScoreAndInfoTbl$V2 ) ) if( !is.null( axesLenRatio ) ) { ratio = diff(range(ylimVec)) / diff(range(xlimVec)) if( ratio < axesLenRatio ) ylimVec = (ylimVec - mean(ylimVec) ) * (axesLenRatio/ratio) + mean(ylimVec) if( ratio > axesLenRatio ) xlimVec = (xlimVec - mean(xlimVec) ) * (ratio/axesLenRatio) + mean(xlimVec) } ### PLOT # scaffolding p = ggplot( pcaScoreAndInfoTbl ) + theme_cowplot( font_size = 14 * fontScaleFactor ) + labs( x = str_c( 'PC', comp[1], " - ", propVarVec[1], "%" ), y = str_c( 'PC', comp[2], " - ", propVarVec[2], "%" ) ) if( axes ){ axisLocTbl = tibble( varName = tbl_vars( data ), x = textXVec, y = textYVec ) if( qualCutoff > 0 ){ qualTbl = calcAxisPred( data, centre, scale ) axisSelTbl = qualTbl %>% filter( comp %in% comp ) %>% group_by( varName ) %>% summarise( compQual = sum( compQual ) ) qualIndVec = Vectorize(ifelse)( axisSelTbl[["compQual"]] > qualCutoff, "0", "1" ) %>% rep( rep(2, length(axisSelTbl[["compQual"]]))) qualLabVec = c( "0" = paste( ">", qualCutoff), "1" = paste( "<", qualCutoff) ) p = p + geom_line(data = axesCoordTbl %>% filter( segmentPos != 'max', varName %in% tbl_vars( data )[selAxisIndVec]) %>% mutate( qualInd = qualIndVec ), aes( x = x, y = y, group = varName, linetype = qualInd ), col = 'gray10' ) + geom_line( data = axesCoordTbl %>% filter( segmentPos != 'min', varName %in% tbl_vars( data )[selAxisIndVec]) %>% mutate( qualInd = qualIndVec ), aes( x = x, y = y, group = varName, linetype = qualInd ), col = 'gray10' ) + scale_linetype_discrete( name = "Axis Predictivity", labels = qualLabVec ) } else{ if( !arrow ){ p = p + geom_line( data = axesCoordTbl %>% filter( segmentPos != 'max', varName %in% tbl_vars( data )[selAxisIndVec]), aes( x = x, y = y, group = varName ), col = 'gray10' ) + geom_line( data = axesCoordTbl %>% filter( segmentPos != 'min', varName %in% tbl_vars( data )[selAxisIndVec] ), aes( x = x, y = y, group = varName ), col = 'gray10' ) } else{ arrowDataTbl = axesCoordTbl %>% filter( segmentPos != 'min', varName %in% tbl_vars( data )[selAxisIndVec] ) botTbl = arrowDataTbl %>% filter( segmentPos == "median" ) %>% mutate( x = 0, y = 0) topTbl = arrowDataTbl %>% filter( segmentPos == "max" ) %>% rename( xend = x, yend = y ) arrowPlotTbl = full_join( botTbl, topTbl, by= "varName" ) p = p + geom_segment( data = arrowPlotTbl, col = 'black', alpha = 0.8, aes( x = x, y = y, xend = xend, yend = yend, group = varName ), arrow = arrow( length = unit( 0.03, "npc") ), size = arrowSize ) } } } # add points if( points ){ p = p + geom_point( aes( x = V1, y = V2, col = group ), size = pointSize, alpha = pointAlpha ) + scale_colour_manual( name = legendTitle, values = colVec, labels = labelVec ) } # add density curves if( density ) { # base densities p = p + geom_density2d( data = bootTbl, aes( x = V1, y = V2, col = group ), alpha = densAlpha, size = densSize ) } # add ellipses if( ellipse ){ # base ellipses p = p + geom_path( data = ellipseTbl, aes( x = x, y = y, colour = group ), size = ellSize, alpha = ellAlpha ) } # add quantile lines if( quant ) { p = p + geom_line( aes( x = varV1, y = V2, colour = lineGroup ), quantPlotTbl, linetype = 1, size = quantSize, alpha = quantAlpha ) + geom_line( aes( x = V1, y = varV2, colour = lineGroup ), qquantPlotTbl, linetype = 1, size = quantSize, alpha = quantAlpha ) } # final editing if( addOrigPos ) { p = p + geom_text( data = origLocTbl, aes( x = V1, y = V2, label = labelVec[origLocTbl$group] ), size = origPosLabSize * fontScaleFactor ) } p = p + coord_fixed( xlim = xlimVec, ylim = ylimVec ) # add names of axes if( axes ){ p = p + annotate( 'text', x = textXVec[selAxisIndVec], y = textYVec[selAxisIndVec], label = tbl_vars( data )[selAxisIndVec], size = pcaAxesLabSize * fontScaleFactor, col = 'black', alpha = 0.8 ) } detach(biplotList) detach(mvObj) p } <file_sep>#' Calculate information required for plotting PCA biplot with confidence areas. #' #' @param data dataframe. Only the numeric columns will be used. #' @param group vector. Vector indicating group membership for each observation in \code{data}. #' Will be coerced to a character vector. #' @inheritParams ggbootMV #' @inheritParams ggbootUV calcMV = function( data, group, B, seed, comp = 1:2, scale, calcLoc, boot = TRUE, save = FALSE, name = NULL, env = NULL, path = NULL, quant, trim ){ # checks if( save & is.null( name ) ) stop( "If save=TRUE, then name argument cannot be null." ) if( !boot & is.null( name ) ) stop( "If boot=FALSE, then name argument cannot be null." ) if( !boot & is.null( env ) ) stop( "If boot=FALSE, then env argument cannot be null." ) # data edit group = as.character( group ) data %<>% select_if( is.numeric ) comp = sort( comp ) # pca pcaTbl = calcPCA( data, scale = scale )[[2]][,comp] %>% as_tibble() # obtain bootstrap values if( boot ){ # boot if( !is.null( seed ) ) set.seed( seed ) bootTbl = calcMVBoot( pcaTbl, group, B, calcLoc ) # hard cache if( !is.null( name ) ){ env$bootList[[ name ]] = bootTbl if( save ) save( bootList, envir = env, file = path ) } } else{ bootTbl = env$bootList[[ name ]] } # median/mean ## original data origLocTbl = ldply( split( data, group ), function( x ) calcLoc( x ) ) %>% dplyr::rename( group = .id ) %>% as_tibble() ## bootstrap data bootLocTbl = ldply( split( bootTbl, bootTbl$group ), function( x ) calcLoc( x[,2:3] ) ) %>% dplyr::rename( group = .id ) %>% as_tibble() # quantiles quantTbl = bootTbl %>% group_by( group ) %>% summarise( lbV1 = llbFunc(V1), ubV1 = uubFunc(V1), lbV2 = llbFunc(V2), ubV2 = uubFunc(V2) ) quantPlotTbl = tibble( varV1 = c( quantTbl$lbV1, quantTbl$ubV1 ), V2 = rep( origLocTbl$V2, 2 ), V1 = rep( origLocTbl$V1, 2 ), varV2 = c( quantTbl$lbV2, quantTbl$ubV2 ), lineGroup = as.character( rep( quantTbl$group, 2 ) ) ) # ellipses ellipseTbl = calcGroupEllipse( bootTbl, p = 0.95 ) # output list( "bootTbl" = bootTbl, "origLocTbl" = origLocTbl, "bootLocTbl" = bootLocTbl, "quantPlotTbl" = quantPlotTbl, "ellipseTbl" = ellipseTbl ) } <file_sep>#' Set ggbootMV graphical parameters. #' #' Set the graphical parameters for ggbootMV. #' #' @param dispPlot,checkPlot logical. If \code{TRUE}, then #' default values are over-ridden with appropriate values #' for a display or checking plot, respectively. If both are \code{TRUE}, #' then dispPlot is used. #' @param env environment. Environment to which to create the bindings. assignGraphPar = function( dispPlot, checkPlot, env ){ if( dispPlot){ assign( "axes", TRUE, env ) assign( "points", TRUE, env ) assign( "pointAlpha", 1, env ) assign( "ellipse", TRUE, env ) assign( "ellAlpha", 1, env ) assign( "ellSize", 2, env ) assign( "quant", FALSE, env ) assign( "density", TRUE, env ) assign( "densAlpha", 0.3, env ) assign( "densSize", 1, env ) assign( "addOrigPos", FALSE, env) return( NULL ) } if( checkPlot ){ assign( "axes", FALSE, env ) assign( "points", TRUE, env ) assign( "pointAlpha", 1, env ) assign( "ellipse", TRUE, env ) assign( "ellAlpha", 0.8, env ) assign( "ellSize", 1, env ) assign( "quant", TRUE, env ) assign( "quantAlpha", 0.8, env ) assign( "quantSize", 1, env ) assign( "density", TRUE, env ) assign( "densAlpha", 0.2, env ) assign( "densSize", 1, env ) assign( "addOrigPos", FALSE, env) } NULL } #' Return the selected location function. #' #' @param locType character. Specifies measure of location to use. Options are #' mean, cmwed (column-wise median), oja, weisz (geometric median) and #' gmed (a fast version for the geometric median). getLocFunc = function( locType ){ if( locType == "mean" ) return( function(x) c( mean( x[[1]] ), mean( x[[2]] ) ) ) if( locType == "cwmed" ) return( function(x) c( median( x[[1]] ), median( x[[2]] ) ) ) if( locType == "oja" ) return( OjaNP::ojaMedian ) if( locType == "gmed" ) return( Gmedian::Gmedian ) if( locType == "weisz" ) return( function(x) Gmedian::Weiszfeld(x)$median ) stop( "locType not recognised.") } #' Return the column indices with given variables names. #' #' @param selAxisLab character vector. Names of columns in \code{data} to print. #' @param data dataframe. getSelAxisInd = function( selAxisLab, data ){ if( is.null( selAxisLab ) ) return( 1:ncol( data ) ) which( tbl_vars( data ) %in% selAxisLab ) }
fe8830fa8d36b7484da141ed224160b843f5026f
[ "Markdown", "R", "RMarkdown" ]
31
R
MiguelRodo/ggboot
fa721e57e18e9da9c95219782fb9e96ca84e0d14
6d70ddf743337ac19ab890e0579b59011ccafc1b
refs/heads/main
<repo_name>NurulHidayati14/CRUDALUMNI<file_sep>/Alumni/app/src/main/java/com/phb/crud/ListAlumniActivity.kt package com.phb.crud import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.activity_list_alumni.* import org.jetbrains.anko.db.classParser import org.jetbrains.anko.db.select class ListAlumniActivity : AppCompatActivity() { private lateinit var adapter: RVAdapterAlumni private var alumni = ArrayList<Alumni>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list_alumni) adapter = RVAdapterAlumni(this, alumni) recylerView.adapter = adapter getData() recylerView.layoutManager = LinearLayoutManager(this) } private fun getData() { database.use { alumni.clear() var result = select(Alumni.TABLE_ALUMNI) var dataKayu = result.parseList(classParser<Alumni>()) alumni.addAll(dataKayu) adapter.notifyDataSetChanged() } } }<file_sep>/Alumni/app/src/main/java/com/phb/crud/DBHelper.kt package com.phb.crud import android.content.Context import android.database.sqlite.SQLiteDatabase import org.jetbrains.anko.db.* class DBHelper(ctx: Context): ManagedSQLiteOpenHelper(ctx, "Alumni.db", null, 1) { companion object{ private var instance: DBHelper? = null @Synchronized fun getInstance(ctx: Context) : DBHelper{ if(instance == null){ instance = DBHelper(ctx.applicationContext) } return instance as DBHelper } } override fun onCreate(db: SQLiteDatabase?) { db?.createTable(Alumni.TABLE_ALUMNI, true, Alumni.ID to INTEGER + PRIMARY_KEY + AUTOINCREMENT, Alumni.NAMA to TEXT, Alumni.ANGKATAN to TEXT, Alumni.JURUSAN to TEXT ) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { db?.dropTable(Alumni.TABLE_ALUMNI, true) } } val Context.database : DBHelper get() = DBHelper.getInstance(applicationContext)<file_sep>/README.md # CRUDALUMNI <file_sep>/Alumni/app/src/main/java/com/phb/crud/Alumni.kt package com.phb.crud data class Alumni(var id: Long?, var nama: String?, var angkatan: String?, var jurusan: String?){ companion object{ const val TABLE_ALUMNI: String = "TABLE_ALUMNI" const val ID: String = "ID_" const val NAMA: String = "NAMA" const val ANGKATAN: String = "ANGKATAN" const val JURUSAN: String = "JURUSAN" } }<file_sep>/Alumni/app/src/main/java/com/phb/crud/RVAdapterAlumni.kt package com.phb.crud import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_list.view.* import org.jetbrains.anko.db.delete import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class RVAdapterAlumni(val context: Context, val items: ArrayList<Alumni>) : RecyclerView.Adapter<RVAdapterAlumni.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view){ fun bindItem(items: Alumni){ itemView.namaAlumni.text = items.nama itemView.umur.text = items.angkatan itemView.penyakit.text = items.jurusan itemView.btnEdit.setOnClickListener { itemView.context.startActivity<MainActivity>( "oldNama" to items.nama, "oldUmur" to items.angkatan, "oldPenyakit" to items.jurusan ) } itemView.btnHapus.setOnClickListener { itemView.context.database.use { delete(Alumni.TABLE_ALUMNI, "(${Alumni.NAMA} = {nama})", "nama" to items.nama.toString()) } itemView.context.toast("Data Dihapus") } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_list, parent, false)) } override fun getItemCount(): Int = items.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindItem(items[position]) } }<file_sep>/Alumni/app/src/main/java/com/phb/crud/MainActivity.kt package com.phb.crud import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* import org.jetbrains.anko.db.insert import org.jetbrains.anko.db.update import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var oldNama = intent.getStringExtra("oldNama") var oldAngkatan = intent.getStringExtra("oldAngkatan") var oldJurusan = intent.getStringExtra("oldJurusan") if (oldAngkatan.isNullOrBlank()){ buttonUpdate.isEnabled = false }else{ buttonSimpan.isEnabled = false editTextNama.setText(oldNama) editTextUmur.setText(oldAngkatan) editTextPenyakit.setText(oldJurusan) } buttonSimpan.setOnClickListener { addDataAlumni() // clear data clearData() } buttonLihatData.setOnClickListener { startActivity<ListAlumniActivity>() } buttonUpdate.setOnClickListener { database.use { update(Alumni.TABLE_ALUMNI, Alumni.NAMA to editTextNama.text.toString(), Alumni.ANGKATAN to editTextUmur.text.toString(), Alumni.JURUSAN to editTextPenyakit.text.toString()) .whereArgs("${Alumni.NAMA} = {nama}", "nama" to oldNama ).exec() } // clear data clearData() toast("Data Diupdate") } } private fun addDataAlumni() { database.use { insert(Alumni.TABLE_ALUMNI, Alumni.NAMA to editTextNama.text.toString(), Alumni.ANGKATAN to editTextUmur.text.toString(), Alumni.JURUSAN to editTextPenyakit.text.toString() ) toast("Data berhasil disimpan!") } } fun clearData(){ editTextNama.text.clear() editTextUmur.text.clear() editTextPenyakit.text.clear() } }
8ead42eab988d2313c3e121227312b1885c6b308
[ "Markdown", "Kotlin" ]
6
Kotlin
NurulHidayati14/CRUDALUMNI
088d88dba99ace88621442934f4e9f1f26054efe
bdcd5a315112f055c1e658fd17aa3c43893d61aa
refs/heads/master
<repo_name>olithor91/bolti<file_sep>/README.md ticTacToeGame ============= Háskólinn í Reykjavík T-303-HUGB, Hugbúnaðarfræði, 2014-3 - Síðannarverkefni Nemendur: <NAME> <NAME> <NAME> <NAME> <NAME> Here is our tic tac toe game: https://tictactoelechamp.herokuapp.com/ [![Build Status](https://magnum.travis-ci.com/ragnarrun/ticTacToeGame.svg?token=<KEY>&branch=master)](https://magnum.travis-ci.com/ragnarrun/ticTacToeGame) <file_sep>/.gradle/2.1/taskArtifacts/cache.properties #Tue Oct 28 11:26:51 GMT+00:00 2014 <file_sep>/bin/build #!/bin/bash sudo killall -9 java ./gradlew build<file_sep>/src/main/java/is/ru/bolti/Main.java package is.ru.bolti; import static spark.Spark.*; import spark.*; import spark.servlet.SparkApplication; public class Main{ public static Game mainGame = new Game(); public static void main(String[] args) { System.out.println("Welcome to Bolti"); mainGame.playGame(); } }
f60e4aa889823682fa80ccb43636a52b3cc89eb7
[ "Markdown", "Shell", "Java", "INI" ]
4
Markdown
olithor91/bolti
b9a21ef1a61f1cd4cf895aee6a7326931696fc78
90a6bec667549c3bddcf907f82b834a0780d4972
refs/heads/master
<repo_name>tonyrlim/DocBrown<file_sep>/README.md # DocBrown CPP Homework: Works with creating text based menus. <file_sep>/docBrown.cpp #include <iostream> #include <iomanip> #include <cstdlib> using namespace std; void getInfo(int &choice, int &sHours, int &sMinutes, int &callTime); double calcCost(int &choice, int &sHours, int &sMinutes, int &callTime); void displayCost(int &choice, int &sHours, int &sMinutes, int &callTime); int main() { int choice, sHours, sMinutes, callTime; getInfo(choice, sHours, sMinutes, callTime); calcCost(choice, sHours, sMinutes, callTime); displayCost(choice, sHours, sMinutes, callTime); return 0; } void getInfo(int &choice, int &sHours, int &sMinutes, int &callTime) { cout << "PHONE BOOTH" << endl << endl << "1. Call destined to the United States" << endl << "2. Call destined to Mexico or Canada" << endl << "3. Call destined to another country" << endl << "4. Quit" << endl << endl << "Please make a selection: "; cin >> choice; if(choice != 4) { cout << endl << endl; cout << "========================================="; cout << endl << endl; cout << "When will your call start?" << endl; cout << "Please format entry as so HH:MM" ; cin >> sHours; cin.ignore(); cin >> sMinutes; cout << "How long will the call be in minutes? "; cin >> callTime; } else { exit(0); } } double calcCost(int &choice, int &sHours, int &sMinutes, int &callTime) { const int US = 1, mexCan = 2, other = 3, quit = 4; double cost1, cost2, cost3, earlyR = .12, midR = .55, lateR = .35; int hourMin = sHours*60 + sMinutes; int earlyMins = 420 - hourMin; int midMins = 1140 - hourMin; int lateMins = 1439 - hourMin; if(choice == US) { if(sHours<=6 && sMinutes<60) { cost1 = earlyMins * earlyR; if(callTime < earlyMins) { cost2 = callTime*earlyR; return cost2; } else if(callTime - earlyMins > 0 && callTime - earlyMins <= 720) { cost2 = cost1 + (callTime - earlyMins)* midR; return cost2; } else if(callTime - earlyMins > 0) { cost3 = cost1 + (midMins- (earlyMins+1))* midR; cost2 = (cost3 + (callTime - (midMins + 1)) * lateR); return cost2; } else return cost1; } else if(sHours>= 7 && sHours<= 19) { cost1 = midMins * midR; if(callTime< midMins) { cost2 = callTime* midR; return cost2; } else if(callTime - midMins > 0) { cost2 = cost1 + (callTime - midMins) * lateR; return cost2; } else return cost1; } else if(sHours>=19 && sMinutes<60) { cost2 = callTime * lateR; return cost2; } } else if(choice == mexCan) { if(sHours<=6 && sMinutes<60) { cost1 = earlyMins * (earlyR*1.50); if(callTime < earlyMins) { cost2 = callTime * (earlyR*1.50); return cost2; } else if(callTime - earlyMins > 0 && callTime - earlyMins <= 720) { cost2 = cost1 + (callTime - earlyMins)* (midR*1.50); return cost2; } else if(callTime - earlyMins > 0) { cost3 = (earlyMins*earlyR) + (midMins- (earlyMins+1))* midR; cost2 = (cost3 + (callTime - (midMins + 1)) * lateR); return cost2*1.5; } } else if(sHours>= 7 && sHours<= 19) { cost1 = midMins * (midR*1.50); if(callTime < midMins) { cost2 = callTime * (midR*1.50); return cost2; } else if(callTime - midMins > 0) { cost2 = cost1 + (callTime - midMins) * (lateR*1.50); return cost2; } } else if(sHours>=19 && sMinutes<60) { cost2 = callTime * (lateR*1.50); return cost2; } } else if(choice == other) { if(sHours<=6 && sMinutes<60) { cost1 = earlyMins * (earlyR*2.25); if(callTime < earlyMins) { cost2 = callTime * (earlyR*2.25); return cost2; } else if(callTime - earlyMins > 0 && callTime - earlyMins <= 720) { cost2 = cost1 + (callTime - earlyMins)* (midR*2.25); return cost2; } else if(callTime - earlyMins > 0) { cost3 = (earlyMins*earlyR) + (midMins- (earlyMins+1))* midR; cost2 = (cost3 + (callTime - (midMins + 1)) * lateR); return cost2*2.25; } } else if(sHours>= 7 && sHours<= 19) { cost1 = midMins * (midR*2.25); if(callTime < midMins) { cost2 = callTime * (midR*2.25); return cost2; } else if(callTime - midMins > 0) { cost2 = cost1 + (callTime - midMins) * (lateR*2.25); return cost2; } } else if(sHours>=19 && sMinutes<60) { cost2 = callTime * (lateR*2.25); return cost2; } } else if(choice == quit) { exit(0); } return 0; } void displayCost(int &choice, int &sHours, int &sMinutes, int &callTime) { double cost = calcCost(choice, sHours, sMinutes, callTime); cout << cost; }
6ec1480ff48f8d9730bbc886e0f837bdd8d05a37
[ "Markdown", "C++" ]
2
Markdown
tonyrlim/DocBrown
a8698c6d94a30b725e8bf6890377b7a390d70dd3
8b33141e1f87dfb56d863f8cc35f7d40a62777eb
refs/heads/master
<file_sep>#!/bin/bash SEQUENCR_TOKEN=$(aws logs describe-log-streams --log-group-name "LearningLogG" | jq -r '.logStreams[0].uploadSequenceToken') echo $SEQUENCR_TOKEN if [ $SEQUENCR_TOKEN = "null" ]; then aws logs put-log-events \ --log-group-name LearningLogG \ --log-stream-name LearningLogS \ --log-events file://output.json else aws logs put-log-events \ --log-group-name LearningLogG \ --log-stream-name LearningLogS \ --log-events file://output.json \ --sequence-token $SEQUENCR_TOKEN fi <file_sep>- Athena apiのドキュメント https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Athena.html - AWS LambdaでAthenaを呼び出す https://qiita.com/naoto_koyama/items/6bfc6e67260e761fd1b4 - code sample https://docs.aws.amazon.com/code-samples/latest/catalog/javascript-athena-index.js.html テーブルの作成 ``` CREATE EXTERNAL TABLE IF NOT EXISTS pokemon_go ( name string, cp int, hp int, favorite boolean, weight float, height float, attributes array< string >, skill1 struct < name:string, attribute:string >, skill2 struct < name:string, attribute:string > ) ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' LOCATION 's3://athena-test-7010/' ``` - Amazon Athenaを使ってJSONファイルを検索してみる https://dev.classmethod.jp/cloud/aws/athena-json/ - Workgroup https://blog.santashack.dev/entry/2019/03/01/164405 https://dev.classmethod.jp/cloud/aws/20190224-amazon-athena-workgroups/ ## 用語集 ### アドホック 特定の目的のための、その場限りの、取ってつけたような、などの意味を持つラテン語表現 ### インタラクティブ 「対話」または「双方向」といった意味で、ユーザーがパソコンの画面を見ながら、対話をするような形式で操作する形態 ### OLAP(OnLine Analytical Processing) データベースに蓄積された大量のデータに対し複雑な集計、分析を行い、素早く結果を提示することができるシステム ### ETL 【 Extract/Transform/Load 】 データベースなどに蓄積されたデータから必要なものを抽出(Extract)し、目的に応じて変換(Transform)し、データを必要とするシステムに格納(Load)すること。 ### スキーマ 物事や計画の概略や仕組み、構造、形式などを示したものを意味することが多い<file_sep>#!/bin/bash aws cloudformation delete-stack --stack-name "cloudwatch-learning-stack" aws cloudformation wait stack-delete-complete --stack-name "cloudwatch-learning-stack"<file_sep>#!/bin/bash aws cloudformation deploy \ --stack-name "cloudwatch-learning-stack" \ --template-file "cloudformation.yaml" \ --parameter-overrides \ LogGroupName="LearningLogG" \ LogStreamName="LearningLogS" \ RInDays=14<file_sep># Cognito ## Amazon Cognitoとは ウェブアプリケーションやモバイルアプリケーションの認証、許可、ユーザー管理をサポートするサービス ### ユーザープール(User pool) サインアップ、サインイン、サインアウト = 認証を担当 ### IDプール(Federated Identities) AWSリソースアクセス用のTemporary Credentialsを払い出す = 認可を担当 ## ハンズオン [Amazon Cognitoを使ったサインイン画面をつくってみる~サインアップ編~](https://www.tdi.co.jp/miso/amazon-cognito-sign-up) を参考にして作成していく ## 参考サイト - [Amazon Cognitoを使ったサインイン画面をつくってみる~サインアップ編~](https://www.tdi.co.jp/miso/amazon-cognito-sign-up) - [AWS Black Belt Online Seminar](https://d1.awsstatic.com/webinars/jp/pdf/services/20170517_AWS-BlackBelt_AmazonCognito.pdf) - [公式ドキュメント](https://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/what-is-amazon-cognito.html)<file_sep>const AWS = require('aws-sdk'); const athena = new AWS.Athena({apiVersion: '2017-05-18', region: 'ap-northeast-1'}); const params = { QueryExecutionId: 'c60cddbd-14a0-4b7f-a235-9ca994ad6f02' }; // クエリの実行状況が返ってくる // { // QueryExecution: { // QueryExecutionId: 'c60cddbd-14a0-4b7f-a235-9ca994ad6f02', // Query: 'select * from sampledb.pokemon_go where name is not null limit 2', // StatementType: 'DML', // ResultConfiguration: { // OutputLocation: 's3://query-results-bucket-test-suzuki/api/c60cddbd-14a0-4b7f-a235-9ca994ad6f02.csv' // }, // QueryExecutionContext: {}, // Status: { // State: 'SUCCEEDED', // SubmissionDateTime: 2019-12-11T02:21:28.701Z, // CompletionDateTime: 2019-12-11T02:21:40.651Z // }, // Statistics: { // EngineExecutionTimeInMillis: 1994, // DataScannedInBytes: 880, // TotalExecutionTimeInMillis: 11950, // QueryQueueTimeInMillis: 9930, // QueryPlanningTimeInMillis: 908, // ServiceProcessingTimeInMillis: 26 // }, // WorkGroup: 'primary' // } // } athena.getQueryExecution(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response });<file_sep>import * as fs from 'fs' interface ICloudWatchLog { timestamp: number, message: string } interface IlogFormat { method: httpMethod, id: id, device: device, browser: browser }; type httpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD'; type id = 100 | 101 | 102 | 103 | 104 | 105 | 106; type device = 'ios' | 'android' | 'windows' | 'macos' | 'linux'; type browser = 'chrome' | 'ie' | 'safari' | 'firefox'; function randomArrayIndex(length: number) { return Math.floor(Math.random() * length); } const httpMethod: httpMethod[] = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD']; const id: id[] = [100, 101, 102, 103, 104, 105, 106]; const device: device[] = ['ios', 'android', 'windows', 'macos', 'linux']; const browser: browser[] = ['chrome', 'ie', 'safari', 'firefox']; const finePath = './output.json'; const logCount = 1000; try { const dt = new Date(); dt.setHours(dt.getHours() - 240); const mthodLen = httpMethod.length; const idLen = id.length; const deviceLen = device.length; const browserLen = browser.length; fs.unlinkSync(finePath); fs.appendFileSync(finePath, '['); for(let i=0; i<logCount; i++){ const logs = { method: httpMethod[randomArrayIndex(mthodLen)], id: id[randomArrayIndex(idLen)], device: device[randomArrayIndex(deviceLen)], browser: browser[randomArrayIndex(browserLen)], }; // console.log(logs); dt.setMinutes(dt.getMinutes() + 1); const cwLog = { timestamp: dt.getTime(), message: JSON.stringify(logs) }; if(i === logCount-1) { fs.appendFileSync(finePath, `${JSON.stringify(cwLog)}\r\n`); } else { fs.appendFileSync(finePath, `${JSON.stringify(cwLog)},\r\n`); } } fs.appendFileSync(finePath, ']'); } catch (err) { console.log(err); }<file_sep># AWS Step Functions 視覚的なワークフローを使用して、分散アプリケーションとマイクロサービスのコンポーネントを調整できるウェブサービス 下記、記事を参考して動かしてみた - Step Functionsを使って初めてループや分岐をやってみた! https://dev.classmethod.jp/cloud/aws/first-aws-step-functions/ ## ステートマシンの定義 ### ステートマシン例1 ![ステートマシン例1](./img/img1.png) ``` { # ステートマシンの説明(コンソールには表示されない?) "Comment": "Sample AWS Step functions flow", # 一番最初に実行される状態 "StartAt": "TaskSampleCall", # 各状態をこの配下に記載していく "States": { # 状態名 "TaskSampleCall": { # 状態の説明(コンソールには表示されない) "Comment": "SampleCallの呼び出し", # 状態のタイプ(作業、分岐、遅延など) "Type": "Task", # 実行するARNを指定する "Resource": "arn:aws:lambda:ap-northeast-1:(AWSユーザーID):function:SampleCall", # Lambda関数へパラメータとして渡すデータを定義。これによって、Lambda内のeventにて値を取得可能 "InputPath": "$", # Lambda関数からのreturn値を定義 "ResultPath": "$.SampleCallResult", # Step Functionsで次のステートへ渡したいデータを定義 "OutputPath": "$", # trueが設定されていると実行が終了される "End": true } } } ``` ### ステートマシン例2 ![ステートマシン例1](./img/img2.png) ``` { "Comment": "Sample Calculation flow", "StartAt": "TaskInitialSetting", "States": { "TaskInitialSetting": { "Comment": "初期の値を設定します", "Type": "Task", "Resource": "arn:aws:lambda:ap-northeast-1:(AWSユーザーID):function:SampleSetting", "InputPath": "$", "ResultPath": "$.SettingResult", "OutputPath": "$", "Next": "TaskAddition" }, "TaskAddition": { "Comment": "足し算をおこないます", "Type": "Task", "Resource": "arn:aws:lambda:ap-northeast-1:(AWSユーザーID):function:SampleAddition", "InputPath": "$", "ResultPath": "$.AdditionResult", "OutputPath": "$", "Next": "TaskMultiply" }, "TaskMultiply": { "Comment": "掛け算をおこないます", "Type": "Task", "Resource": "arn:aws:lambda:ap-northeast-1:(AWSユーザーID):function:SampleMultiply", "InputPath": "$", "ResultPath": "$.MultiplyResult", "OutputPath": "$", "End": true } } } ``` アウトプット ResultPathに指定したオブジェクトに結果が入る。`$`は一番上位のオブジェクト ``` { "Comment": "Insert your JSON here", "SettingResult": { "foo": 1 }, "AdditionResult": { "var": 3 }, "MultiplyResult": { "baz": 9 } } ``` ### ステートマシン例3 ![ステートマシン例3](./img/img3.png) ``` { "Comment": "Sample loop flow", "StartAt": "ConfigureCount", "States": { "ConfigureCount": { "Type": "Pass", # 次の状態に渡される結果。Lambda内のreturnの中身のイメージ "Result": { "idx": 1, "step": 1, "maxcount": 3, "continue": true }, "ResultPath": "$.iterator", "Next": "wait_seconds" }, "wait_seconds": { "Type": "Wait", # 5秒待つ "Seconds": 5, "Next": "ChoiceLoopStopState" }, "ChoiceLoopStopState": { "Type": "Choice", "Choices": [{ "Comment": "ループ継続フラグcontinueをチェックする", "Variable": "$.iterator.continue", "BooleanEquals": true, "Next": "CheckStatus" }], "Default": "SuccessProcess" }, "CheckStatus": { "Type": "Task", "Resource": "arn:aws:lambda:ap-northeast-1:(AWSユーザーID):function:SampleCountUp", "InputPath": "$", "ResultPath": "$.iterator", "OutputPath": "$", "Next": "wait_seconds" }, "SuccessProcess": { "Type": "Succeed" } } } ``` ## 参考URL - AWS Step Functions とは https://docs.aws.amazon.com/ja_jp/step-functions/latest/dg/welcome.html <file_sep>const AWS = require('aws-sdk'); const athena = new AWS.Athena({apiVersion: '2017-05-18', region: 'ap-northeast-1'}); const params = { QueryExecutionId: 'c60cddbd-14a0-4b7f-a235-9ca994ad6f02', // MaxResults: 1, // NextToken: '<KEY> }; // クエリの実行結果が返ってくる athena.getQueryResults(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else { console.log(data); for (let i = 0; i < data.ResultSet.Rows.length; i++) { console.log(data.ResultSet.Rows[i]); } } });<file_sep># cloudwatchについていろいろ ## ロググループとログストリームの作成 下記サイトを参考にcloudformationでロググループとログストリームを構築 http://blog.serverworks.co.jp/tech/2019/11/29/post-76523/ ## ログストリームにログを送信 こちらのサイトを参考にした https://michimani.net/post/use-cloudwatch-via-aws-cli/#cloudwatch-logs-%e3%81%ae%e6%a7%8b%e6%88%90%e8%a6%81%e7%b4%a0 ログの送信はロググループとログストリームを指定する必要がある。 方法としてShorthand SyntaxとJSON Syntaxがある。 ### Shorthand Syntax ワンラインでタイムスタンプとメッセージを指定する方法 2回目以降はその一つ前に送信した際に返ってきたsequenceTokenを--sequence-token オプションで指定する必要がある ``` $ aws logs put-log-events \ --log-group-name LearningLogG \ --log-stream-name LearningLogS \ --log-events timestamp=1579096423000,message="Hello CloudWatch Logs" \ --sequence-token 49599905847494815968440472464551125366243568252283310978 ``` ### JSON Syntax JSON 形式で指定する方法です。この方法だと、複数のログイベントを一度に送信することができます。 ``` $ aws logs put-log-events \ --log-group-name LearningLogG \ --log-stream-name LearningLogS \ --log-events file://events.json \ --sequence-token 49599905847494815968440579934810523281120572972717888386 ``` ログイベントの形式をjsonにする場合はmessageをjson文字列する ``` $ aws logs put-log-events \ --log-group-name LearningLogG \ --log-stream-name LearningLogS \ --log-events file://events2.json \ --sequence-token 49599905847494815968440580082567854806059791989564560258 ``` ### nextSequenceTokenの取得 `aws logs describe-log-streams --log-group-name "LearningLogG"` ## cloudwatch Insights [公式ドキュメントのクエリ構文を参考](https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html) ログの形式は下記 ``` { method:"POST", id:101, device:"macos", browser:"chrome" } ``` ### クエリーの色々 - 昇順で上位20件のログを取得。表示する項目はfieldsに指定しているもの ``` fields @timestamp, id, device, browser, method | sort @timestamp asc | limit 20 ``` - displayコマンドの項目に指定したもののみを表示する ``` fields @timestamp, id, device, browser, method | sort @timestamp asc | limit 20 | display id ``` - filterコマンドには抽出条件を記載することができる ``` fields @timestamp, id, device, browser, method | filter id = 101 and method = "GET" | sort @timestamp asc | limit 20 ``` - statsは統計演算子を記載できる ``` stats count(*) as count | filter id = 101 and method = "GET" ``` - statusはbyの後にグルーピングできる ``` fields id, device, method # idが存在している場合にtrueを返す | filter ispresent(id) # asはエイリアス名を付ける | stats count(*) as count1 by id, device, method | sort id ``` - parseコマンドを使用すると、皇族化されていない値も取得できる `Hello CloudWatch Logs3` のような形式のログがある場合、parseコマンドを使うことで`Hello CloudWatch` 以降を抜き出すことが可能 ``` fields @message | parse @message "Hello CloudWatch *" as log | filter log = "Logs3" | limit 10 ```
d4e3672d0cfa9424f6e3326ab36f69385352a1ba
[ "Markdown", "TypeScript", "JavaScript", "Shell" ]
10
Shell
nsuzuki7713/aws-sdk-sample
4cc71af95b00e9bb5c03ed73bb51e7e81a6afee9
b11fadb57cab7e3c068b97e97a34cad50ec94d97
refs/heads/master
<file_sep>from django.db import models # Create your models here. from django.db import models class Question(models.Model): question_text=models.CharField(max_length=2000) pub_date=models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) choice_text=models.CharField(max_length=2000) votes=models.IntegerField(default=0) class Author(models.Model): name=models.CharField(max_length=50) age=models.IntegerField def __str__(self): return self.name<file_sep># -*- coding:utf-8 -*- from django.urls import path from .import views from django.conf.urls import url urlpatterns=[ path('',views.index,name='index'), path('add/<int:a>/<int:b>/',views.old_add_redirect), url(r'new_add/(\d+)/(\d+)/$',views.add,name='add_new') ]<file_sep>from django.db import models # Create your models here. from django.db import models import os,django # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django2.settings") # django.setup() class Author(models.Model): first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) qq=models.CharField(max_length=10) addr=models.TextField() email=models.EmailField() def __str__(self): return self.first_name def my_property(self): return self.first_name+' '+self.last_name my_property.short_description='Full name' full_name=property(my_property) class Article(models.Model): title=models.CharField(max_length=50) author=models.ForeignKey(Author,on_delete=models.CASCADE) content=models.TextField() score=models.IntegerField() tags=models.ManyToManyField('Tag') def __str__(self): return self.title class Tag(models.Model): name=models.CharField(max_length=50) def __str__(self): return self.name<file_sep># -*- coding:utf-8 -*- from blog.models import Author,Article,Tag import random import os,django # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django2.settings") # django.setup() author_list=['张三','李四','王五','赵六'] article_list=['python 教程','sql 教程','django 教程','java 教程'] def create_authors(): for author_name in author_list: author,created=Author.objects.get_or_create(name=author_name) author.qq=''.join(str(random.choice(range(10))) for _ in range(9)) author.addr='addr_%s'%(random.randrange(1,3)) author.email='%<EMAIL>'%(author.name) author.save() def create_article_tags(): for article_title in article_list: tag_name=article_title.split(' ',1)[0] tag,created=Tag.objects.get_or_create(name=tag_name) random_author=random.choice(Author.objects.all()) for i in range(1,21): title='%s_%s'%(article_title,i) article,created=Article.objects.get_or_create( title=title,defaults={ 'author':random_author, 'content':'%s 正文'%title, 'score':random.randrange(70,101) } ) article.tags.add(tag) def main(): create_authors() create_article_tags() if __name__ == '__main__': main() print('Done')<file_sep># -*- coding:utf-8 -*- from django.db import models import ast class ListField(models.TextField): # __metaclass__=models.SubfieldBase description='Stores a python list' def __init__(self,*arg,**kwargs): super(ListField, self).__init__(*arg,**kwargs) def to_python(self, value): if not value: value=[] if isinstance(value,list): return value return ast.literal_eval(value) def get_prep_value(self, value): if value is None: return value return str(value) def value_to_string(self, obj): value=self._get_val_from_obj(obj) return self.get_db_prep_value(value)<file_sep>from django.test import TestCase # Create your tests here. from polls.models import Question que=Question() que.question_text('什么水果最好吃') que.pub_date('2018-04-01') que.save() <file_sep>from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.urls import reverse def index(request): #return HttpResponse('Hello World.') string=u'这是从views发过来的信息' List=['html','css','java','python'] dict={'name':u'王武','age':'17'} return render(request, 'index.html',{'dict':dict}) def add(request,a,b): # a=request.GET.get('a',0) # b=request.GET.get('b',0) c=int(a)+int(b) return HttpResponse(str(c)) def old_add_redirect(request,a,b): return HttpResponseRedirect( reverse('add_new',args=(a,b)) )<file_sep>from django.contrib import admin from .models import * # Register your models here. class ArticleAdmin(admin.ModelAdmin): list_display = ('title','author','score') class AuthorAdmin(admin.ModelAdmin): list_display = ('first_name','last_name','full_name','addr','qq','email') admin.site.register(Article,ArticleAdmin) admin.site.register(Author,AuthorAdmin) admin.site.register(Tag)
47644f7e26abd8ac23382d38a47d02de7e00cc07
[ "Python" ]
8
Python
SurfingBoy/Django3
0cf1b880072ead953dc963718f3f27827952e6ca
6e83a6b3c427eb1467f799a8567e7acb642fa2bc
refs/heads/master
<repo_name>shahkaushal94/ResolutionAlgorithm<file_sep>/Resolution.java import java.util.*; import java.io.*; public class Resolution { public static HashMap<String, ArrayList<String>> kbFinal = new HashMap<String, ArrayList<String>>(); public static int countForInfinite = 0; public static void main(String args[]) throws Exception { FileWriter fw1 = new FileWriter("output.txt"); PrintWriter pw1 = new PrintWriter(fw1); ReadFile file = new ReadFile("input.txt"); String textFile[] = file.OpenFile(); ArrayList<String> q = new ArrayList<String>(); int nq = Integer.parseInt(textFile[0]); for(int i=0 ;i<nq; i++) { q.add(textFile[i+1]); } int ns = Integer.parseInt(textFile[nq+1]); ArrayList<String> s = new ArrayList<String>(); for(int i=nq+1 ; i<nq+1+ns ; i++) { s.add(textFile[i+1]); } /* System.out.println("------------------Q is "); for(String s2: q) { System.out.println(s2); } System.out.println(); System.out.println("-----------------S is "); for(String s1: s) { System.out.println(s1); } */ // Removing spaces from s // System.out.println("Removing spaces"); for(int i=0;i<s.size(); i++) { String sstring = s.get(i); sstring = sstring.replaceAll(" ", ""); //System.out.println(sstring); //cleanS.add(sstring); s.set(i,sstring); } /* System.out.println("-----------------s is "); for(String s1: s) { System.out.println(s1); } */ // System.out.println("Replacing => by >"); for(int i = 0; i<s.size(); i++) { String sstring = s.get(i); for(int j=0; j<sstring.length(); j++) { if(sstring.charAt(j) == '=') { sstring = sstring.replaceAll("=", ""); s.set(i, sstring); } } } /* System.out.println("-----------------s is ---------------------------"); for(String s1: s) { System.out.println(s1); } System.out.println(); */ // This function converts Predicates into P int predicateCounter= 0; HashMap<String, String> hm = new HashMap<String, String>(); HashMap<String, String> hm1 = new HashMap<String, String>(); ArrayList<String> newS = new ArrayList<String>(); for(int i=0; i<s.size(); i++) { String sstring = s.get(i); //System.out.println("The string to convert is "+sstring); //int startIndex = 0; //int endIndex = sstring.length(); String p = new String(); for(int j=0; j<sstring.length(); j++) { if(sstring.charAt(j) >= 'A' && sstring.charAt(j) <= 'Z') { int startIndex = j; while(sstring.charAt(j) != ')') { j++; } int endIndex = j; String predicate = sstring.substring(startIndex, endIndex+1); predicateCounter++; if(predicateCounter < 10) { if(!hm.containsKey(predicate)) { p = p + "P" + "00"+ predicateCounter ; hm.put(predicate, "P" + "00" + predicateCounter); hm1.put("P"+"00"+predicateCounter, predicate); } else { p = p+ hm.get(predicate) ; } } else if(predicateCounter < 100) { if(!hm.containsKey(predicate)) { p = p + "P" + "0"+ predicateCounter ; hm.put(predicate, "P" + "0" + predicateCounter); hm1.put("P"+"0"+predicateCounter, predicate); } else { p = p + hm.get(predicate) ; } } else if(predicateCounter < 800) { if(!hm.containsKey(predicate)) { p = p + "P" + predicateCounter ; hm.put(predicate, "P" + predicateCounter); hm1.put("P"+predicateCounter, predicate); } else { p = p + hm.get(predicate) ; } } } else { p = p + sstring.charAt(j); } } newS.add(p); } /* System.out.println("-----------------newS is-------------------- "); for(String s1: newS) { System.out.println(s1); } System.out.println(); */ ArrayList<String> prefixS = new ArrayList<String>(); prefixS = prefixFunction(newS); /* System.out.println("-----------------prefixS is-------------------------------- "); for(String s1: prefixS) { System.out.println(s1); } System.out.println(); */ ArrayList<String> removedImplication = new ArrayList<String>(); removedImplication = removeImplication(prefixS); /* System.out.println("-----------------removedImplication is-------------------------------- "); for(String s1: removedImplication) { System.out.println(s1); } System.out.println(); */ ArrayList<String> prefixRemovedImplication = new ArrayList<String>(); prefixRemovedImplication = prefixFunction(removedImplication); /* System.out.println("-----------------prefixRemovedImplication is-------------------------------- "); for(String s1: prefixRemovedImplication) { System.out.println(s1); } System.out.println(); */ ArrayList<String> negationInwards = new ArrayList<String>(); negationInwards = negateInside(prefixRemovedImplication); /* System.out.println("-----------------negationInwards is-------------------------------- "); for(String s1: negationInwards) { System.out.println(s1); } System.out.println(); */ ArrayList<String> prefixNegationInwards = new ArrayList<String>(); prefixNegationInwards = prefixFunction(negationInwards); /* System.out.println("-----------------prefixNegationInwards is-------------------------------- "); for(String s1: prefixNegationInwards) { System.out.println(s1); } System.out.println(); */ ArrayList<String> distributivityArray = new ArrayList<String>(); distributivityArray = distributivity(prefixNegationInwards); /* System.out.println("-----------------distributivityArray is "); for(String s1: distributivityArray) { System.out.println(s1); } */ //Adding into kn by splitting on & ArrayList<String> kb = new ArrayList<String>(); kb = splitAnd(distributivityArray); //System.out.println("The knowledge base is " + kb); //displayHashMap(hm); //displayHashMap(hm1); ArrayList<String> standardizeVar = new ArrayList<String>(); standardizeVar = standardizingVar(kb, hm1); /* System.out.println("The standardizeVar is ====================="); for(String s1: standardizeVar) { System.out.println(s1); } */ kbFinal = makeHashMap(standardizeVar); //displayHashMap(kbfinal); /* System.out.println("Display KB before query "); displayKbHashMap(kbFinal); */ //Now solving queries for(int i=0; i<q.size(); i++) { Stack<String> currentQueryStack = new Stack<String>(); String qString = q.get(i); qString = qString.replaceAll(" ", ""); if(qString.contains("~")) { qString = qString.substring(1); } else { qString = '~' + qString; } currentQueryStack.push(qString); countForInfinite = 0; boolean dfsResult = dfs_function(currentQueryStack, countForInfinite); if(dfsResult == true) { pw1.println("TRUE"); System.out.println("TRUE"); } else { pw1.println("FALSE"); System.out.println("FALSE"); } } fw1.close(); pw1.close(); //System.out.println("Display KB before query "); //displayKbHashMap(kbFinal); // System.out.println("The knowledge base is " + kb); // displayHashMap(hm); // displayHashMap(hm1); // System.out.println("DONE"); } public static String negate(String query) { if(query.contains("~")) { return query.substring(1); } else { return "~"+query; } } public static boolean dfs_function(Stack<String> qstack,int countForInfinite) throws IOException { // System.out.println("The first stack is "+qstack); while(!qstack.isEmpty()) { String popped=qstack.pop(); // System.out.println("the popped element is "+popped); String currentQuery=negate(popped); // System.out.println("The current Query is "+ currentQuery); String pred=""; int index = -1; for(int i=0; i<currentQuery.length(); i++) { while(currentQuery.charAt(i)!='(') { pred+=currentQuery.charAt(i); i++; } index=i; break; } String arguments1[]=currentQuery.substring(index+1,currentQuery.length()-1).split(","); //System.out.print("Argument 1 is "); /* for(String x:arguments1) System.out.print(x+" "); System.out.println(); */ // System.out.println("The KB FINAL is " ); // displayKbHashMap(kbFinal); if(kbFinal.containsKey(pred)) { ArrayList<String> valuesOfKey=kbFinal.get(pred); for(int i=0;i<valuesOfKey.size();i++) { if(countForInfinite > 1000) { //System.out.println("The counter is "+countForInfinite); return false; } String currentValue=valuesOfKey.get(i); //System.out.println("currentValue "+currentValue); ArrayList<String> orList=new ArrayList<String>(); String splitter[]=currentValue.split("\\|"); String matchFound=""; for(String x:splitter) { orList.add(x); if(x.contains(pred)) { matchFound=x; } //System.out.print(x+" "); } String arg2String=""; for(int j=0;j<matchFound.length();j++) { if(matchFound.charAt(j)=='(') { j++; while(matchFound.charAt(j)!=')') { arg2String+=matchFound.charAt(j); j++; } break; } } //System.out.println("arg2 "+arg2String); //Kb args String arguments2[]=arg2String.split(","); boolean result=unification(arguments1,arguments2); //System.out.println("result of unification is "+result); if(result==true) { HashMap<String,String> hmapUnification=new HashMap<String,String>(); for(int h=0;h<arguments1.length;h++) { String stackArg=arguments1[h]; String kbArgs=arguments2[h]; if(!hmapUnification.containsKey(kbArgs)) { hmapUnification.put(kbArgs,stackArg); } } // System.out.println("Hmap Unification "+hmapUnification); //Cloning qstack Stack<String> copyStack=new Stack<String>(); String stackArray[]= qstack.toArray(new String[qstack.size()]); ArrayList<String> stackarraylist=new ArrayList<String>(); for(String x:stackArray) { stackarraylist.add(x); } for(int si=0;si<qstack.size();si++) { copyStack.push(stackArray[si]); } for(int m=0;m<orList.size();m++) { String currentKbElement=orList.get(m); // System.out.println("current "+currentKbElement); Iterator it = hmapUnification.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); if(currentKbElement.contains((String)pair.getKey())) { currentKbElement=currentKbElement.replace((String)pair.getKey(),(String)pair.getValue()); } } // System.out.println("after substitution: "+currentKbElement); String chck=""; for(int f=0;f<currentKbElement.length();f++) { while(currentKbElement.charAt(f) != '(') { chck += currentKbElement.charAt(f) + ""; f++; } break; } if(!chck.equals(pred)) { String original = currentKbElement; String temp = ""; if(original.contains("~")) { temp = original.substring(1); } else { temp = "~" + original; } int count = 0; for (Iterator<String> iterator = stackarraylist.iterator(); iterator.hasNext();) { String string = iterator.next(); if (string.equals(temp)) { iterator.remove(); count=1; } } if(count!=1) stackarraylist.add(original); } } Stack<String> finalstack=new Stack<String>(); for(String z:stackarraylist) { finalstack.push(z); } boolean dfsResult=dfs_function(finalstack,++countForInfinite); // System.out.println("DFS result is "+dfsResult); if(dfsResult==true) { return true; } } } return false; } else { return false; } } // System.out.println("After exiting while loop"); return true; } public static HashMap<String, ArrayList<String>> makeHashMap(ArrayList<String> a) { HashMap <String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>(); for(int i=0; i<a.size(); i++) { String s1 = a.get(i); //System.out.println("The string is " + s1); for(int j=0; j<s1.length(); j++) { if(s1.charAt(j) >= 'A' && s1.charAt(j) <= 'Z') { String predicate = ""; if(j>0 && s1.charAt(j-1)=='~') { //predicate = s1.substring(j-1, j+4); predicate += '~'; } else { //predicate = s1.substring(j,j+4); } int startIndex = j; while(s1.charAt(j) != '(') { j++; } int endIndex = j; predicate += s1.substring(startIndex, endIndex); //System.out.println("The predicate is " + predicate); if(!hm.containsKey(predicate)) { ArrayList<String> tmp = new ArrayList<String>(); tmp.add(s1); hm.put(predicate, tmp); } else { ArrayList<String> tmp = hm.get(predicate); tmp.add(s1); hm.put(predicate, tmp); } while(s1.charAt(j) != ')') { j++; } } } } return hm; } public static boolean unification(String a[],String b[]) { int count=0; for(int i=0;i<a.length;i++) { String x=a[i]; //string from stack String y=b[i]; //string from kbstring // System.out.println("The arg 1 is " + x); // System.out.println("The arg 2 is " + y); if(x.charAt(0)>='a'&& x.charAt(0)<='z' && y.charAt(0)>='a' && y.charAt(0)<='z') { count++; } else if(x.charAt(0)>='a'&& x.charAt(0)<='z' && y.charAt(0)>='A' && y.charAt(0)<='Z') { count++; } else if(x.charAt(0)>='A'&& x.charAt(0)<='Z' && y.charAt(0)>='a' && y.charAt(0)<='z') { count++; } else if(x.equals(y)) { count++; } } //System.out.println("The count is " + count); if(count==a.length) return true; else return false; } public static ArrayList<String> distributivity(ArrayList<String> a) { ArrayList<String> answer = new ArrayList<String>(); for(int j = 0; j<a.size(); j++) { String as = a.get(j); // System.out.println("The string in distributivity is " + as); Stack<String> stack = new Stack<String>(); for(int i = as.length()-1; i>=0; i--) { // System.out.println(stack); if(as.charAt(i) == 'P') { String pred = as.substring(i,i+4); stack.push(pred); } if(as.charAt(i) == '&') { String first = stack.pop(); String second = stack.pop(); String adding = first + as.charAt(i) + second; // System.out.println(third); stack.push(adding); } if(as.charAt(i)=='~') { String firstNow=""; String first = stack.pop(); firstNow = "~" + first; stack.push(firstNow); } if(as.charAt(i)=='|') { String first = stack.pop(); // System.out.println("first "+first); String second = stack.pop(); // System.out.println("second "+second); String third = ""; ArrayList<String> firstOperandArray=new ArrayList<String>(); ArrayList<String> secondOperandArray=new ArrayList<String>(); if(first.contains("&")) { for(String ands:first.split("&")) { firstOperandArray.add(ands); } } if(second.contains("&")) { for(String ands:second.split("&")) { secondOperandArray.add(ands); } } // System.out.println("firstOperandArray "+firstOperandArray); // System.out.println("secondOperandArray "+secondOperandArray); if(firstOperandArray.isEmpty() && secondOperandArray.isEmpty()) { third += first+"|"+second; } if(firstOperandArray.isEmpty() && !secondOperandArray.isEmpty()) { for(String soa:secondOperandArray) { third+=first+"|"+soa; third+="&"; } } if(!firstOperandArray.isEmpty() && secondOperandArray.isEmpty()) { for(String foa:firstOperandArray) { third+=second+"|"+foa; third+="&"; } } if(!firstOperandArray.isEmpty() && !secondOperandArray.isEmpty()) { for(String foa:firstOperandArray) { for(String soa:secondOperandArray) { third+=foa+"|"+soa; third+="&"; } } } // System.out.println("third in or"+third); if(third.charAt(third.length()-1)=='&') { third = third.substring(0,third.length()-1); } stack.push(third); } } String finalans = stack.pop(); finalans = finalans.substring(0, finalans.length()); answer.add(finalans); //System.out.println(finalans + " is the final ans"); } return answer; } public static ArrayList<String> negateInside (ArrayList<String> a) { ArrayList<String> answer = new ArrayList<String>(); for(int j=0; j<a.size(); j++) { String as = a.get(j); // System.out.println("The String is "+ as); Stack<String> stack = new Stack<String>(); for(int i=as.length()-1; i>=0 ; i--) { if(as.charAt(i)=='P') { String pred = as.substring(i,i+4); stack.push(pred); } if(as.charAt(i)=='&'||as.charAt(i)=='|') { String first = stack.pop(); String second = stack.pop(); String adding = first + as.charAt(i) + second; stack.push(adding); } if(as.charAt(i)=='~') { String firstNow=""; String first=stack.pop(); for(int k=0;k<first.length();k++) { if(k==0 && first.charAt(k)=='P') { firstNow+="~"; firstNow += first.substring(k,k+4); } else if(first.charAt(k)=='|') { firstNow += "&"; } else if(first.charAt(k)=='&') { firstNow += "|"; } else if(first.charAt(k)=='P') { if(first.charAt(k-1)=='~') { firstNow += first.substring(k,k+4); } else { firstNow += "~"+first.substring(k,k+4); } } } if(firstNow.contains("&")) { // System.out.println("yes it contains &"); ArrayList<String> a1=new ArrayList<String>(); for(String andString:firstNow.split("&")) { andString="("+andString+")"; a1.add(andString); } String tmpNewFirst=""; for(String tmp:a1) { tmpNewFirst+=tmp+"&"; } tmpNewFirst=tmpNewFirst.substring(0,tmpNewFirst.length()-1); tmpNewFirst="("+tmpNewFirst+")"; firstNow=tmpNewFirst; } stack.push(firstNow); } } //System.out.println(stack.peek() + "is the answer of negation"); answer.add(stack.pop()); } return answer; } public static ArrayList<String> removeImplication (ArrayList<String> a) { ArrayList<String> answer = new ArrayList<String>(); for(int j=0; j<a.size(); j++) { String as = a.get(j); //System.out.println("The String is "+ as); Stack<String> stack = new Stack<String>(); for(int i=as.length()-1;i>=0;i--) { if(as.charAt(i)=='P') { String pred = as.substring(i,i+4); stack.push(pred); } if(as.charAt(i)=='&'||as.charAt(i)=='|') { String first = stack.pop(); String second = stack.pop(); String adding = first + as.charAt(i) + second; stack.push(adding); } if(as.charAt(i) == '~') { String first = stack.pop(); first = "~(" + first + ")"; stack.push(first); } if(as.charAt(i)=='>') { String first = "~(" + stack.pop() + ")"; String second = stack.pop(); String adding = first + "|" + second; stack.push(adding); } } answer.add(stack.pop()); } return answer; } public static int precedence(String c) { if(c.equals("~")) { return 4; } else if( c.equals("&")) { return 3; } else if( c.equals("|")) { return 2; } else if( c.equals(">")) { return 1; } else if( c.equals(")")) { return 0; } else if( c.equals("(")) { return 0; } return (-99999); } public static ArrayList<String> prefixFunction(ArrayList<String> newS) { //System.out.println("PREFIX NOW"); Stack<Character> stack = new Stack<Character>(); ArrayList<String> prefixS = new ArrayList<String>(); for(int j=0; j<newS.size();j++) { String sstring = newS.get(j); String prefix = ""; //System.out.println("The string is" + sstring); for(int i=sstring.length()-1;i>=0;i--) { if(sstring.charAt(i)==')') { stack.push(sstring.charAt(i)); } if(sstring.charAt(i)=='P') { //String sss = sstring.substring(i,i+4); StringBuilder x1 = new StringBuilder(sstring.substring(i,i+4)); x1.reverse(); prefix += x1.toString(); } if(sstring.charAt(i)=='&'||sstring.charAt(i)=='|'||sstring.charAt(i)=='>'||sstring.charAt(i)=='~') { if(stack.isEmpty()) { stack.push(sstring.charAt(i)); } else { int prec1=precedence("" +sstring.charAt(i)+ ""); int prec2=precedence("" +stack.peek() + ""); if(prec1>prec2) { stack.push(sstring.charAt(i)); } else { while(prec1<prec2 && (!(stack.isEmpty()))) { prefix += stack.pop(); if(!stack.isEmpty()) { prec2=precedence(""+stack.peek()+""); } } stack.push(sstring.charAt(i)); } } } if(sstring.charAt(i)=='(') { while(stack.peek()!=')') { prefix += stack.pop(); } stack.pop(); } } while(!stack.isEmpty()) { prefix+=stack.pop()+""; } //String sssprefix = new String(prefix); StringBuilder x2=new StringBuilder(prefix); x2.reverse(); // System.out.println("The prefix added is "+ prefix); prefixS.add(x2.toString()); } return prefixS; } public static ArrayList<String> splitAnd(ArrayList<String> a) { ArrayList<String> kb = new ArrayList<String>(); for(String s1: a) { String[] kbrows = s1.split("&"); for(String s2 : kbrows) { kb.add(s2); } } return kb; } public static void displayHashMap(HashMap<String, String> hm) { Set s = hm.entrySet(); Iterator it = s.iterator(); while(it.hasNext()) { Map.Entry mentry = (Map.Entry)it.next(); System.out.println("Key: " + mentry.getKey() + " Value: " + mentry.getValue()); } } public static void displayKbHashMap(HashMap<String, ArrayList<String>> hmkb) { Set s = hmkb.entrySet(); Iterator it = s.iterator(); while(it.hasNext()) { Map.Entry mentry = (Map.Entry)it.next(); System.out.println("Key: " + mentry.getKey() + " Value: " + mentry.getValue()); } } public static ArrayList<String> standardizingVar(ArrayList<String> a, HashMap<String, String>hm1) { int hm2Counter = 0; ArrayList<String> answer = new ArrayList<String>(); for(int i=0 ; i<a.size(); i++) { String s = a.get(i); String pre = ""; HashMap<String, String> hm2 = new HashMap<String, String>(); for(int j=0 ; j<s.length(); j++) { //System.out.println("The string is " + s ); if(s.charAt(j) == 'P') { String predicate = s.substring(j, j+4); String value = hm1.get(predicate); // System.out.println("The valuesOfKey are " + value); j = j+3; String argument = ""; for(int k=0; k<value.length();k++) { if(value.charAt(k) == '(') { pre = pre + value.charAt(k); k++; while(k<value.length() && value.charAt(k) != ')') { if(value.charAt(k) == ',') { //hm2Counter++; //pre = pre + argument + value.charAt(k); // System.out.println("The argument is "+ argument + "And hm2 counter is " + hm2Counter); if(!hm2.containsKey(argument)) { //System.out.println(hm2); hm2Counter++; if(hm2Counter < 10) { hm2.put(argument, "x" + "00" + hm2Counter ); pre = pre + "x" + "00" + hm2Counter + value.charAt(k); } else if(hm2Counter < 100) { hm2.put(argument, "x" + "0" + hm2Counter); pre = pre + "x" + "0" + hm2Counter + value.charAt(k); } else if(hm2Counter < 1000) { hm2.put(argument, "x" + hm2Counter); pre = pre + "x" + hm2Counter + value.charAt(k); } } else { pre = pre + hm2.get(argument) + value.charAt(k); } argument = ""; } else if (value.charAt(k) >= 'A' && value.charAt(k) <= 'Z' ) { int startIndex = k; while(value.charAt(k) != ',' && value.charAt(k) != ')') { k++; } int endIndex = k; pre = pre + value.substring(startIndex, endIndex) + value.charAt(k); } else { argument = argument + value.charAt(k); } k++; } //hm2Counter++; //pre = pre + argument + value.charAt(k); // for ) // System.out.println("The argument is "+ argument + "And hm2 counter is " + hm2Counter); if(argument != "" && !hm2.containsKey(argument)) { //System.out.println(hm2); hm2Counter++; if(hm2Counter < 10) { hm2.put(argument, "x" + "00" + hm2Counter ); pre = pre + "x" + "00" + hm2Counter + ")"; } else if(hm2Counter < 100) { hm2.put(argument, "x" + "0" + hm2Counter); pre = pre + "x" + "0" + hm2Counter + ")"; } else if(hm2Counter < 1000) { hm2.put(argument, "x" + hm2Counter); pre = pre + "x" + hm2Counter + ")"; } } else if(argument != "") { pre = pre + hm2.get(argument) + ")" ; } } else { pre = pre + value.charAt(k); //for A //pre = pre + predicate; } } } else { pre = pre + s.charAt(j); // for | and & } } //pre = ""; // System.out.println("End of String ----------------------" + pre); answer.add(pre); } return answer; } // Start //End } class ReadFile{ String path; public ReadFile(String file_path) { path = file_path; } public int readLines() throws IOException { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); String tmpLine; int numberOfLines = 0; while ( (tmpLine = br.readLine()) != null) { numberOfLines++; } br.close(); return numberOfLines; } public String[] OpenFile() throws IOException { FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); int numberOfLines = readLines(); String []textData = new String [numberOfLines]; for (int i=0;i<numberOfLines; i++) { textData[i] = br.readLine(); } br.close(); return textData; } }
7f651fc8826941f1fc902f50bee271e76aef9a64
[ "Java" ]
1
Java
shahkaushal94/ResolutionAlgorithm
5c1675fd55801dd2089bd524ca51ce271cdefc23
e2d9e159ea29fc49c6f81b196c0fed7cbaaa17a1
refs/heads/main
<repo_name>MortarGOD/LegendCompiler<file_sep>/语言定义与运行时库/sylib.c #include<stdio.h> #include<stdarg.h> #include<sys/time.h> #include"sylib.h" /* Input & output functions */ int getint(){int t; scanf("%d",&t); return t; } int getch(){char c; scanf("%c",&c); return (int)c; } int getarray(int a[]){ int n; scanf("%d",&n); for(int i=0;i<n;i++)scanf("%d",&a[i]); return n; } void putint(int a){ printf("%d",a);} void putch(int a){ printf("%c",a); } void putarray(int n,int a[]){ printf("%d:",n); for(int i=0;i<n;i++)printf(" %d",a[i]); printf("\n"); } /* Timing function implementation */ __attribute((constructor)) void before_main(){ for(int i=0;i<_SYSY_N;i++) _sysy_h[i] = _sysy_m[i]= _sysy_s[i] = _sysy_us[i] =0; _sysy_idx=1; } __attribute((destructor)) void after_main(){ for(int i=1;i<_sysy_idx;i++){ fprintf(stderr,"Timer@%04d-%04d: %dH-%dM-%dS-%dus\n",\ _sysy_l1[i],_sysy_l2[i],_sysy_h[i],_sysy_m[i],_sysy_s[i],_sysy_us[i]); _sysy_us[0]+= _sysy_us[i]; _sysy_s[0] += _sysy_s[i]; _sysy_us[0] %= 1000000; _sysy_m[0] += _sysy_m[i]; _sysy_s[0] %= 60; _sysy_h[0] += _sysy_h[i]; _sysy_m[0] %= 60; } fprintf(stderr,"TOTAL: %dH-%dM-%dS-%dus\n",_sysy_h[0],_sysy_m[0],_sysy_s[0],_sysy_us[0]); } void _sysy_starttime(int lineno){ _sysy_l1[_sysy_idx] = lineno; gettimeofday(&_sysy_start,NULL); } void _sysy_stoptime(int lineno){ gettimeofday(&_sysy_end,NULL); _sysy_l2[_sysy_idx] = lineno; _sysy_us[_sysy_idx] += 1000000 * ( _sysy_end.tv_sec - _sysy_start.tv_sec ) + _sysy_end.tv_usec - _sysy_start.tv_usec; _sysy_s[_sysy_idx] += _sysy_us[_sysy_idx] / 1000000 ; _sysy_us[_sysy_idx] %= 1000000; _sysy_m[_sysy_idx] += _sysy_s[_sysy_idx] / 60 ; _sysy_s[_sysy_idx] %= 60; _sysy_h[_sysy_idx] += _sysy_m[_sysy_idx] / 60 ; _sysy_m[_sysy_idx] %= 60; _sysy_idx ++; } <file_sep>/compiler.cpp #include <bits/stdc++.h> using namespace std; #define TEXTLEN 8848 // 变量名最大长度 #define NSYMBOLS 888888 // 变量最大数量 #define INF 999999999 // 非const变量的值 #define NOREG -1 #define NOLABEL 0 const int push_reg = 32; //保存r4——r10八个寄存器的值 const int L_field = 3072; //ldr跳转预警值3KB const int OF = 2; const int Threshold = 4; //寄存器替换阈值 const int imm8 = 255; const int imm12 = 4095; const int imm16 = 65535; const int P_2[31] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824}; // Token types enum { T_EOF, // Binary operators T_ASSIGN, T_LOGOR, T_LOGAND, T_EQ, T_NE, T_LT, T_GT, T_LE, T_GE, T_PLUS, T_MINUS, T_STAR, T_SLASH, T_PER, // Other operators T_LOGNOT, // Type keywords T_VOID, T_INT, // Other keywords T_IF, T_ELSE, T_WHILE, T_CONTINUE, T_RETURN, T_BREAK, T_CONST, // Structural tokens T_INTCONST, T_STRCONST, T_SEMI, T_IDENT, T_NOTE, T_LB, T_RB, T_LP, T_RP, T_LBK, T_RBK, T_COMMA }; // Token structure struct token { int token; //单词标签 int intvalue; //单词数值 string strvalue; //单词变量名 int line; //单词所在行号 }; vector<token> token_stream; //单词序列 enum { A_ASSIGN= 1, A_LOGOR, A_LOGAND, A_EQ, A_NE, A_LT, A_GT, A_LE, A_GE, A_ADD, A_SUBTRACT, A_MULTIPLY, A_DIVIDE, A_MOD, A_INTLIT, A_STRLIT, A_IDENT, A_GLUE, A_IF, A_WHILE, A_FUNCTION, A_RETURN, A_CONTINUE, A_BREAK, A_FUNCCALL, A_ADDR, A_LOGNOT, A_DEFINE, A_RSB, A_INIT }; // Primitive types enum { P_NONE, P_VOID, P_INT }; // Abstract Syntax Tree structure struct ASTnode { int op; // AST树节点类型 int type; // 变量类型 int rvalue; // 是否是右值 int Dimension_num; // 如果是数组, 表示该数组共有几维 bool istop; // 对短路语句, 判断是否是最后一项 ASTnode *left; // 左、中、右、next子树 ASTnode *mid; ASTnode *right; ASTnode *next; union { int intvalue; // 对一个变量, 代表在symtable数组中的下标 int id; // 对一个函数, 代表在symtable数组中的下标 } v; string strvalue; int line; }; // Structural types enum { S_VARIABLE, S_FUNCTION, S_ARRAY }; // Storage classes enum { C_GLOBAL = 1, // 全局变量 C_LOCAL, // 局部变量 C_PARAM // 函数参数 }; // Symbol table structure struct symtable { string name; // 变量名 int type; // 变量类型(int) int stype; // 变量名类型(函数、变量、数组) int ctype; // 变量名类型(全局、局部、参数) int endlabel; // 对一个函数, 它的结束标签 int size; // 对一个数组, 它的大小 int posn; #define nelems posn // 对一个函数, 它的参数数量 int st_address; //对一个局部变量, 它在栈帧中的起始地址 int intvalue; //对一个数值常量, 它的数值 int paramnum; //对一个函数参数, 它是第几个参数 vector<int> Dimens; //对一个数组, 它每一维分别有多大 vector<int> conNum; //对一个const数组, 它的初始值 }; typedef struct keyword { int id; char name[16]; } KEYWORD; static KEYWORD keywords[16] = { {T_INT, "int"}, {T_RETURN, "return"}, {T_CONTINUE, "continue"}, {T_BREAK, "break"}, {T_IF, "if"}, {T_ELSE, "else"}, {T_WHILE, "while"}, {T_VOID, "void"}, {T_CONST, "const"} }; // AST node types enum { ADD, SUBTRACT, MULTIPLY, DIVIDE, MOD, INTCONST }; // 用于编译时能求值的表达式的AST树结构体 struct ASnode { int op; // 常量类型 ASnode *left; // 左、右子树 ASnode *right; int intvalue; // 常量的值 }; void new_field(); int scan(token *t); ASTnode *newASTnode(int op, int type, ASTnode *left, ASTnode *mid, ASTnode *right, int intvalue); ASTnode *newASTleaf(int op, int type, int intvalue); ASTnode *newASTunary(int op, int type, ASTnode *left, int intvalue); int genlabel(void); int genLC(void); int CodeGen(ASTnode *n, int label, int looptoplabel, int loopendlabel, int parentASTop); void printAST(ASTnode *root); void genpreamble(); void genpostamble(); void genfreeregs(); void genglobsym(int id, int num); void genglobsym_plus(int id, vector<int> &x); int genglobstr(string strvalue); void genreturn(int reg, int id); void freeall_registers(void); void ARM_preamble(); void ARM_funcpre(int id); void ARM_funcpos(int id); int ARM_loadint(int value); int ARM_loadglob(int id); int ARM_loadlocal(int id); int ARM_add(int r1, int r2); int ARM_sub(int r1, int r2); int ARM_mul(int r1, int r2); int ARM_div(int r1, int r2); int ARM_mod(int r1, int r2); int ARM_funccall(int r, int id); int ARM_str_glob(int r, int id); int ARM_str_local(int r, int id); void ARM_globsym(int id, int num); void ARM_globsym_plus(int id, vector<int> &x); int ARM_cmp_jump(int r, int label); void ARM_label(int l); void ARM_jump(int l); int ARM_cmp_jmp(int ASTop, int r1, int r2, int label, int parentASTop); void ARM_return(int reg, int id); ASTnode *Exp_Stmt(); ASTnode *Cond(); ASTnode *AddExp(); ASTnode *MulExp(); ASTnode *UnaryExp(); ASTnode *LOrExp(); ASTnode *LAndExp(); ASTnode *EqExp(); ASTnode *RelExp(); ASTnode *Block(void); void match(int t, string what); void semi(void); void lbrace(void); void rbrace(void); void lparen(void); void rparen(void); void ident(void); void fatal(string s); void fatals(string s1, string s2); void fatald(string s, int d); void fatalc(string s, int c); int findglob(string s); int findlocl(string s); int findsymbol(string s); int addglob(string name, int type, int stype, int endlabel, int size); int addlocl(string name, int type, int stype, int isparam, int size); void freeloclsyms(void); void VarDef(int type, int islocal, int isparam); ASTnode *FuncDef(int type); void CompUnit(void); int FuncType(void); ASnode *newNode(int op, ASnode *left, ASnode *right, int intvalue); ASnode *newLeaf(int op, int intvalue); ASnode *newUnary(int op, ASnode *left, int intvalue); ASnode *Exp(int rbp); int interpretAST(ASnode *n); int Inchar; //当前输入字符 int Line; //当前行号 int Putback; int Functionid; // 函数在symtable中的id int Globs; // 全局变量数 int Locls; // 局部变量数 stack<int>Locls_save; // 保存局部变量作用域 int Local_v; // 一个函数领域内的局部变量数 int func_v; // 由函数调用生成的临时变量数 int Looplevel; // while语句嵌套深度 int max_param; // 函数调用最大参数数量 bool con; // 是否const定义 bool last_or; // 是否是逻辑或语句的最后一项 bool last_and; // 是否是逻辑与语句的最后一项 FILE *Infile; FILE *Outfile; int token_index; // 当前是第几个单词 int token_size; // 单词数 int pars; // 统计是第几个函数参数 int func_field; // 当前领域 int true_L; // if和while语句的true标签 int ldr_Byte; // 当前汇编输出字节数 string nowname; //上一个读取的标识符 char Text[TEXTLEN + 1]; symtable Symtable[NSYMBOLS]; // 变量信息集合 char buf[8848]; bool if_PerformanceTest = false; //是否开启性能优化 int while_level; //while嵌套层数 int max_alloc; //while语句块中出现过的最大寄存器编号 int while_st; //while语句块起始汇编下标 int while_ed; //while语句块终止汇编下标 unordered_map<int, int> ump; //键: fp偏移量, 值: 出现次数 unordered_map<int, int> newReg; //键: fp偏移量, 值: 新分配的寄存器 bool cmp(const pair<int,int> &a, const pair<int,int> &b){ return a.second > b.second; } vector<string> ObjectCode; //汇编集合 // 用于申请的寄存器集合 static int freereg[7]; static char const *reglist[7] = { "r4", "r5", "r6", "r7", "r8", "r9", "r10"}; // 释放所有寄存器 void freeall_registers(void) { freereg[0] = freereg[1] = freereg[2] = freereg[3] = freereg[4] = freereg[5] = freereg[6] = 1; } // 申请一个寄存器 static int alloc_register(void) { for (int i = 0; i < 7; i++) { if (freereg[i]) { freereg[i] = 0; return (i); } } exit(26); fatal("Out of registers"); return (NOREG); // Keep -Wall happy } // 申请一个寄存器 static int alloc_register_plus(void) { for (int i = 6; i > max_alloc; i--) { if (freereg[i]) { freereg[i] = 0; return (i); } } return (NOREG); // Keep -Wall happy } // 释放指定寄存器 static void free_register(int reg) { freereg[reg] = 1; } void putf(string s){ string ins = "\t.ascii\t\""; int len = s.size(); for(int i = 0; i < len; ++i){ if(s[i] == '%'){ ins += '%'; ins += '%'; }else{ ins += s[i]; } } ins += "\\000\"\n"; ObjectCode.emplace_back(ins); return ; } #define MAXN 8848 vector<int>Intlist; int Intslot = 0; // 计算一个整数在汇编中的字节数 int leng(int a){ int flag = 0; while(a){ a /= 10; flag++; } return flag; } // 从标签中读取一个常量 static void set_int_offset(int r, int val) { int offset = -1; for (int i = 0; i < Intlist.size(); i++) { if (Intlist[i] == val) { offset = 4 * i; break; } } if (offset == -1) { offset = 4 * Intslot; Intlist.emplace_back(val); ++Intslot; ldr_Byte += (8 + leng(val)); } for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[r], func_field, offset); ObjectCode.emplace_back(buf); ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} } pair<int, string> LClist[MAXN]; static int LCslot = 0; static void set_lc_offset(int r, string val) { int offset = -1; for (int i = 0; i < LCslot; i++) { if (LClist[i].second == val) { offset = 4 * i; break; } } if (offset == -1) { offset = 4 * LCslot; if (LCslot == MAXN) fatal("Out of int slots in set_int_offset()"); LClist[LCslot].first = genLC(); LClist[LCslot++].second = val; } for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } offset += 4 * Intslot; sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[r], func_field, offset); ObjectCode.emplace_back(buf); ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} } void addString(string s){ int offset = -1; for (int i = 0; i < LCslot; i++) { if (LClist[i].second == s) { offset = 4 * i; break; } } if (offset == -1) { offset = 4 * LCslot; if (LCslot == MAXN) fatal("Out of int slots in set_int_offset()"); LClist[LCslot].first = genLC(); LClist[LCslot++].second = s; } return ; } //寄存器分配之扫描 void ScanRegPass(string s){ const int len = s.size(); if(len > 4){ string operand = s.substr(1, 3); //扫描出最大使用过的寄存器 int maxReg = 0; for(int i = 0; i < len; ++i){ if(s[i] == 'r' && isdigit(s[i+1])){ maxReg = max(maxReg, s[i+1]-'0'); } } max_alloc = max(maxReg, max_alloc); //统计出现次数最多的局部变量地址 if(operand == "ldr" || operand == "str"){ for(int i = 0; i < len; ++i){ if(s[i] == '[' && s[i+1] == 'f' && s[i+2] == 'p'){ int st = i + 6; int ed; for(int j = i+3; j < len; ++j){ if(s[j] == ']'){ ed = j; break; } } int var_address = stoi(s.substr(st, ed-st)); ump[var_address]++; } } } } return ; } //寄存器分配之修改 string AllocRegPass(string s){ const int len = s.size(); if(len > 4){ string operand = s.substr(1, 3); int Reg; if(operand == "ldr" || operand == "str"){ for(int i = 0; i < len; ++i){ //扫描出写入或者读出的寄存器 if(s[i] == 'r' && isdigit(s[i+1])){ Reg = s[i+1]-'0'; } //将局部变量地址替换成寄存器 if(s[i] == '[' && s[i+1] == 'f' && s[i+2] == 'p'){ int st = i + 6; int ed; for(int j = i+3; j < len; ++j){ if(s[j] == ']'){ ed = j; break; } } int var_address = stoi(s.substr(st, ed-st)); if(newReg.find(var_address) != newReg.end()){ int r = newReg[var_address]; if(operand == "ldr"){ sprintf(buf, "\tmov r%d, %s\n", Reg, reglist[r]); s = buf; }else{ sprintf(buf, "\tmov %s, r%d\n", reglist[r], Reg); s = buf; } } } } } } return s; } // 生成一个新的全局变量、常量标签, 更新ldr指令作用域 void new_field(){ sprintf(buf, "\tb\t.L%d\n", func_field+2); ObjectCode.emplace_back(buf); sprintf(buf, ".L%d:\n", func_field+1); ObjectCode.emplace_back(buf); sprintf(buf, "\t.align 2\n"); ObjectCode.emplace_back(buf); ldr_Byte = 0; sprintf(buf, ".L%d:\n", func_field); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)){ sprintf(buf, "\t.word %s\n", Symtable[i].name.c_str()); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); } } for (int i = 0; i < Intlist.size(); i++) { sprintf(buf, "\t.word %d\n", Intlist[i]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); } for (int i = 0; i < LCslot; i++) { sprintf(buf, "\t.word .LC%d\n", LClist[i].first); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); } sprintf(buf, ".L%d:\n", func_field+2); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); func_field = genlabel(); genlabel(); genlabel(); Intlist.clear(); Intslot = 0; return ; } void ARM_preamble() { freeall_registers(); fputs("\t.text\n", Outfile); fprintf(Outfile, "\t.arch\tarmv7ve\n"); } /*函数声明前缀*/ void ARM_funcpre(int id) { for (int i = 0; i < LCslot; i++) { sprintf(buf, "\t.align 2\n"); ObjectCode.emplace_back(buf); sprintf(buf, ".LC%d:\n", LClist[i].first); ObjectCode.emplace_back(buf); putf(LClist[i].second); } string name = Symtable[id].name; sprintf(buf, "\t.text\n"); ObjectCode.emplace_back(buf); sprintf(buf, "\t.align 2\n"); ObjectCode.emplace_back(buf); sprintf(buf, "\t.global\t%s\n", name.c_str()); ObjectCode.emplace_back(buf); sprintf(buf, "%s:\n", name.c_str()); ObjectCode.emplace_back(buf); sprintf(buf, "\tpush\t{r4, r5, r6, r7, r8, r9, r10, fp, lr}\n"); ObjectCode.emplace_back(buf); sprintf(buf, "\tadd\tfp, sp, #%d\n", push_reg); ObjectCode.emplace_back(buf); int subnum = Local_v*4; if(max_param > 5){ subnum += (max_param - 5)*4; } subnum += 4; if(!if_PerformanceTest) subnum += (func_v)*4; int r = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tsub\tsp, sp, #%d\n", subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); }else{ set_int_offset(r, subnum); sprintf(buf, "\tsub\tsp, sp, %s\n", reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); } free_register(r); func_v = 1; int sub = -36; for(int i = 0; i < Symtable[id].nelems && i < 4; ++i){ sprintf(buf, "\tstr\tr%d, [fp, #%d]\n", i, sub); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); sub -= 4; } if(if_PerformanceTest){ max_alloc = 0; while_st = ObjectCode.size(); ump.clear(); newReg.clear(); } } /*函数声明后缀*/ void ARM_funcpos(int id) { if(if_PerformanceTest){ while_ed = ObjectCode.size(); for(int i = while_st; i < while_ed; ++i){ ScanRegPass(ObjectCode[i]); } max_alloc -= 4; vector<pair<int, int> >a; for(auto x : ump){ a.push_back(x); } sort(a.begin(), a.end(), cmp); int now = 0; while(1){ if(now >= a.size()) break; if(a[now].second <= Threshold) break; int reg = alloc_register_plus(); if(reg == -1) break; newReg[a[now].first] = reg; ++now; } for(int i = while_st; i < while_ed; ++i){ ObjectCode[i] = AllocRegPass(ObjectCode[i]); } for(auto &x : newReg){ int address = x.first; int r = x.second; sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[r], address); ObjectCode.emplace(ObjectCode.begin() + while_ed, buf); } for(auto &x : newReg){ int address = x.first; int r = x.second; sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[r], address); ObjectCode.emplace(ObjectCode.begin() + while_st, buf); } } ARM_label(Symtable[id].endlabel); sprintf(buf, "\tsub\tsp, fp, #%d\n", push_reg); ObjectCode.emplace_back(buf); sprintf(buf, "\tpop\t{r4, r5, r6, r7, r8, r9, r10, fp, pc}\n"); ObjectCode.emplace_back(buf); sprintf(buf, ".L%d:\n", func_field+1); ObjectCode.emplace_back(buf); sprintf(buf, "\t.align 2\n"); ObjectCode.emplace_back(buf); sprintf(buf, ".L%d:\n", func_field); ObjectCode.emplace_back(buf); for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)){ sprintf(buf, "\t.word %s\n", Symtable[i].name.c_str()); ObjectCode.emplace_back(buf); } } for (int i = 0; i < Intlist.size(); i++) { sprintf(buf, "\t.word %d\n", Intlist[i]); ObjectCode.emplace_back(buf); } for (int i = 0; i < LCslot; i++) { sprintf(buf, "\t.word .LC%d\n", LClist[i].first); ObjectCode.emplace_back(buf); } Intlist.clear(); Intslot = 0; } /*将一个立即数放到一个新的寄存器*/ int ARM_loadint(int value) { int reg = alloc_register(); if (value <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg], value); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} }else { set_int_offset(reg, value); } return (reg); } /*将一个变量放到一个新的寄存器*/ int ARM_var_offset(int id) { int offset = 0; int reg = alloc_register(); for (int i = 0; i < id; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[reg], func_field, offset); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} return reg; } /*读取全局变量*/ int ARM_loadglob(int id) { int reg = alloc_register(); int reg1 = ARM_var_offset(id); sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} free_register(reg1); return (reg); } /*读取局部变量*/ int ARM_loadlocal(int id) { int reg = alloc_register(); int subnum = abs(Symtable[id].st_address); int reg1 = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], Symtable[id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, subnum); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } } free_register(reg1); return (reg); } /*读取函数参数*/ int ARM_loadparam(int id) { int reg = alloc_register(); if(Symtable[id].paramnum < 4){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], Symtable[id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } }else{ int subnum = (Symtable[id].paramnum - 3)*4; int reg1 = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, subnum); sprintf(buf, "\tadd\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } } free_register(reg1); } return (reg); } int ARM_add(int r1, int r2) { sprintf(buf, "\tadd\t%s, %s, %s\n", reglist[r1], reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); return (r1); } int ARM_sub(int r1, int r2) { sprintf(buf, "\tsub\t%s, %s, %s\n", reglist[r1], reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); return (r1); } int ARM_mla(int r1, int r2, int r3) { sprintf(buf, "\tmla\t%s, %s, %s, %s\n", reglist[r1], reglist[r2], reglist[r3], reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); free_register(r3); return (r1); } int ARM_mul(int r1, int r2) { sprintf(buf, "\tmul\t%s, %s, %s\n", reglist[r1], reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); return (r1); } int ARM_lsl(int r1, int r2, int val){ sprintf(buf, "\tlsl\t%s, %s, #%d\n", reglist[r1], reglist[r1], val); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); return (r1); } int ARM_rsb(int r){ sprintf(buf, "\trsb\t%s, %s, #0\n", reglist[r], reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } return (r); } int ARM_div(int r1, int r2) { sprintf(buf, "\tsdiv\t%s, %s, %s\n", reglist[r1], reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); return (r1); } int ARM_asr(int r1, int r2, int val){ int reg = alloc_register(); if(P_2[val] - 1 <= imm8){ sprintf(buf, "\tadd\t%s, %s, #%d\n", reglist[reg], reglist[r1], P_2[val] - 1); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int reg1 = alloc_register(); set_int_offset(reg1, P_2[val] - 1); sprintf(buf, "\tadd\t%s, %s, %s\n", reglist[reg], reglist[r1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg1); } sprintf(buf, "\tcmp\t%s, #0\n", reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmovlt\t%s, %s\n", reglist[r1], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tasr\t%s, %s, #%d\n", reglist[r1], reglist[r1], val); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg); free_register(r2); return (r1); } int ARM_mod(int r1, int r2) { int reg = alloc_register(); sprintf(buf, "\tsdiv\t%s, %s, %s\n", reglist[reg], reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmls\t%s, %s, %s, %s\n", reglist[r1], reglist[reg], reglist[r2], reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg); free_register(r2); return (r1); } /*函数调用*/ int ARM_funccall(int r, int id) { sprintf(buf, "\tbl\t%s\n", Symtable[id].name.c_str()); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } if(Symtable[id].type != P_VOID){ sprintf(buf, "\tmov\t%s, r0\n", reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } return (r); }else{ free_register(r); return (NOREG); } } /*写入数组变量*/ int ARM_str_array(int r1, int r2, int id) { //r1要赋的值, r2偏移量 if(Symtable[id].ctype == C_GLOBAL){ int r = ARM_var_offset(id); sprintf(buf, "\tstr\t%s, [%s, %s, lsl #2]\n", reglist[r1], reglist[r], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r); }else if(Symtable[id].ctype == C_LOCAL){ sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[r2], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } int reg = alloc_register(); sprintf(buf, "\tsub\t%s, fp, #%d\n", reglist[reg], push_reg); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } ARM_add(r2, reg); int subnum = abs(Symtable[id].st_address + push_reg); int reg1 = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tstr\t%s, [%s, #%d]\n", reglist[r1], reglist[r2], Symtable[id].st_address + push_reg); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, subnum); ARM_sub(r2, reg1); sprintf(buf, "\tstr\t%s, [%s]\n", reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } } }else{ int reg = alloc_register(); if(Symtable[id].paramnum < 4){ sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[r2], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], Symtable[id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } ARM_add(r2, reg); sprintf(buf, "\tstr\t%s, [%s]\n", reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[r2], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } int subnum = (Symtable[id].paramnum - 3)*4; int reg1 = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, subnum); sprintf(buf, "\tadd\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } } free_register(reg1); ARM_add(r2, reg); sprintf(buf, "\tstr\t%s, [%s]\n", reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } } free_register(r2); return r1; } /*写入全局变量*/ int ARM_str_glob(int r, int id) { int r1 = ARM_var_offset(id); sprintf(buf, "\tstr\t%s, [%s]\n", reglist[r], reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r1); return (r); } /*写入局部变量*/ int ARM_str_local(int r, int id) { int subnum = abs(Symtable[id].st_address); int reg = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[r], Symtable[id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg, subnum); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[r], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } } free_register(reg); return (r); } /*写入函数参数*/ int ARM_str_param(int r, int id) { if(Symtable[id].paramnum < 4){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[r], Symtable[id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int subnum = (Symtable[id].paramnum - 3)*4; int reg = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[r], subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg, subnum); sprintf(buf, "\tadd\t%s, fp, %s\n", reglist[reg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[r], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF);if(ldr_Byte >= L_field){ new_field(); } } free_register(reg); } return (r); } /*未初始化的全局变量声明*/ void ARM_globsym(int id, int num) { sprintf(buf, "\t.comm\t%s,%d,4\n", Symtable[id].name.c_str(), 4*num); ObjectCode.emplace_back(buf); } /*已初始化的全局变量声明*/ void ARM_globsym_plus(int id, vector<int> &x){ sprintf(buf, "\t.global\t%s\n", Symtable[id].name.c_str()); ObjectCode.emplace_back(buf); sprintf(buf, "\t.data\n"); ObjectCode.emplace_back(buf); sprintf(buf, "\t.align\t2\n"); ObjectCode.emplace_back(buf); sprintf(buf, "\t.size\t%s, %d\n", Symtable[id].name.c_str(), (int)(x.size())*4); ObjectCode.emplace_back(buf); sprintf(buf, "%s:\n", Symtable[id].name.c_str()); ObjectCode.emplace_back(buf); for(int i = 0; i < x.size(); i++){ sprintf(buf, "\t.word\t%d\n", x[i]); ObjectCode.emplace_back(buf); } } /*生成新的标签*/ void ARM_label(int l) { sprintf(buf, ".L%d:\n", l); ObjectCode.emplace_back(buf); } /*跳转到指定标签*/ void ARM_jump(int l) { sprintf(buf, "\tb\t.L%d\n", l); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } // in AST order: A_EQ, A_NE, A_LT, A_GT, A_LE, A_GE static char const *brlist[] = { "bne", "beq", "bge", "ble", "bgt", "blt" }; // in AST order: A_EQ, A_NE, A_LT, A_GT, A_LE, A_GE static char const *brlist_plus[] = { "beq", "bne", "blt", "bgt", "ble", "bge" }; /*短路语句跳转*/ int ARM_cmp_jmp(int ASTop, int r1, int r2, int label, int parentASTop) { //在逻辑或语句里但不是最后一个条件判断元素 || 在逻辑与语句里且是最后一个条件判断元素, 但不包含在最后一个逻辑或条件判断元素中 if((parentASTop == A_LOGOR && !last_or) || (parentASTop == A_LOGAND && last_and && !last_or)){ sprintf(buf, "\tcmp\t%s, %s\n", reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\t%s\t.L%d\n", brlist_plus[ASTop - A_EQ], true_L); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ sprintf(buf, "\tcmp\t%s, %s\n", reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\t%s\t.L%d\n", brlist[ASTop - A_EQ], label); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } freeall_registers(); return (NOREG); } /*对单个元素, 直接和0比较判断*/ int ARM_cmp_jump(int r, int label) { sprintf(buf, "\tcmp\t%s, #0\n", reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbeq\t.L%d\n", label); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } freeall_registers(); return (NOREG); } // 比较指令表,即mov指令的条件 // AST类型顺序: A_EQ, A_NE, A_LT, A_GT, A_LE, A_GE char const *cmplist1[] ={"eq", "ne", "lt", "gt", "le", "ge"}; char const *cmplist2[] ={"ne", "eq", "ge", "le", "gt", "lt"}; // 比较两个寄存器并设置寄存器值 int ARM_compare_and_set(int ASTop, int r1, int r2){ sprintf(buf, "\tcmp\t%s, %s\n", reglist[r1], reglist[r2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmov%s\t%s, #1\n", cmplist1[ASTop - A_EQ], reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmov%s\t%s, #0\n", cmplist2[ASTop - A_EQ], reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tuxtb\t%s, %s\n", reglist[r1], reglist[r1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(r2); return r1; } /*把逻辑非语句转换成数值0和1*/ int ARM_lognot(int r, int label, int parentASTop) { sprintf(buf, "\tcmp %s, #0\n", reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmoveq %s, #1\n", reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmovne %s, #0\n", reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tuxtb %s, %s\n", reglist[r], reglist[r]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } return (r); } /*函数调用返回语句*/ void ARM_return(int reg, int id) { if(Symtable[id].type != P_VOID){ sprintf(buf, "\tmov\tr0, %s\n", reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } ARM_jump(Symtable[id].endlabel); freeall_registers(); } int FuncType(void) { int type; switch (token_stream[token_index].token) { case T_VOID: type = P_VOID; break; case T_INT: type = P_INT; break; } ++token_index; return (type); } /*构造常量表达式AST树*/ static struct ASnode *primary(void) { struct ASnode *n; int id; switch (token_stream[token_index].token) { case T_INTCONST: n = newLeaf(INTCONST, token_stream[token_index].intvalue); match(T_INTCONST, "intconst"); return (n); case T_IDENT: { if(token_stream[token_index+1].token == T_LBK){ id = findsymbol(token_stream[token_index].strvalue); ++token_index; int offset = 0; int len = Symtable[id].Dimens.size(); int cnt = 1; while(token_stream[token_index].token == T_LBK){ match(T_LBK, "["); int temp = 1; for(int i = cnt; i < len; ++i){ temp = temp*Symtable[id].Dimens[i]; } ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; offset += temp*nowvalue; match(T_RBK, "]"); cnt++; } if(offset >= Symtable[id].conNum.size()){ fprintf(stderr, "Not Const Array!\n"); exit(2); } n = newLeaf(INTCONST, Symtable[id].conNum[offset]); return (n); }else{ id = findsymbol(token_stream[token_index].strvalue); if(Symtable[id].intvalue == INF){ fprintf(stderr, "Not Const!\n"); exit(3); } n = newLeaf(INTCONST, Symtable[id].intvalue); ++token_index; return (n); } } case T_MINUS: { int cnt = 0; int value; while((token_stream[token_index].token != T_INTCONST) && (token_stream[token_index].token != T_IDENT) && (token_stream[token_index].token != T_LP)){ if(token_stream[token_index].token == T_MINUS) ++cnt; ++token_index; } if(token_stream[token_index].token == T_INTCONST){ value = token_stream[token_index].intvalue; ++token_index; }else if(token_stream[token_index].token == T_IDENT){ if(token_stream[token_index+1].token == T_LBK){ id = findsymbol(token_stream[token_index].strvalue); ++token_index; int offset = 0; int len = Symtable[id].Dimens.size(); int cnt = 1; while(token_stream[token_index].token == T_LBK){ match(T_LBK, "["); int temp = 1; for(int i = cnt; i < len; ++i){ temp = temp*Symtable[id].Dimens[i]; } ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; offset += temp*nowvalue; match(T_RBK, "]"); cnt++; } if(offset >= Symtable[id].conNum.size()){ fprintf(stderr, "Not Const Array!\n"); exit(4); } value = Symtable[id].conNum[offset]; }else{ id = findsymbol(token_stream[token_index].strvalue); if(Symtable[id].intvalue == INF){ fprintf(stderr, "Not Const!\n"); exit(5); } value = Symtable[id].intvalue; ++token_index; } }else{ fprintf(stderr, "gg - !\n"); exit(6); } if(cnt%2 == 1) value = 0-value; n = newLeaf(INTCONST, value); return (n); } case T_PLUS: { int cnt = 0; int value; while((token_stream[token_index].token != T_INTCONST) && (token_stream[token_index].token != T_IDENT) && (token_stream[token_index].token != T_LP)){ if(token_stream[token_index].token == T_MINUS) ++cnt; ++token_index; } if(token_stream[token_index].token == T_INTCONST){ value = token_stream[token_index].intvalue; ++token_index; }else if(token_stream[token_index].token == T_IDENT){ if(token_stream[token_index+1].token == T_LBK){ id = findsymbol(token_stream[token_index].strvalue); ++token_index; int offset = 0; int len = Symtable[id].Dimens.size(); int cnt = 1; while(token_stream[token_index].token == T_LBK){ match(T_LBK, "["); int temp = 1; for(int i = cnt; i < len; ++i){ temp = temp*Symtable[id].Dimens[i]; } ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; offset += temp*nowvalue; match(T_RBK, "]"); cnt++; } if(offset >= Symtable[id].conNum.size()){ fprintf(stderr, "Not Const Array!\n"); exit(7); } value = Symtable[id].conNum[offset]; }else{ id = findsymbol(token_stream[token_index].strvalue); if(Symtable[id].intvalue == INF){ fprintf(stderr, "Not Const!\n"); exit(8); } value = Symtable[id].intvalue; ++token_index; } }else{ fprintf(stderr, "gg + !\n"); exit(9); } if(cnt%2 == 1) value = 0-value; n = newLeaf(INTCONST, value); return (n); } case T_LP: match(T_LP, "("); n = Exp(0); match(T_RP, ")"); return (n); default: fprintf(stderr, "syntax error on line %d, token %d\n", token_stream[token_index].line, token_stream[token_index].token); exit(10); } } int arithop(int tokentype) { switch (tokentype) { case T_PLUS: return (ADD); case T_MINUS: return (SUBTRACT); case T_STAR: return (MULTIPLY); case T_SLASH: return (DIVIDE); case T_PER: return (MOD); default: fprintf(stderr, "syntax error on line %d, token %d\n", Line, tokentype); exit(11); } } static int OpPrec_plus[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 20, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static int op_precedence_plus(int tokentype) { int prec = OpPrec_plus[tokentype]; if (prec == 0) { fprintf(stderr, "syntax error on line %d, token %d\n", Line, tokentype); exit(12); } return (prec); } bool check(){ switch (token_stream[token_index].token) { case T_PLUS: return true; case T_MINUS: return true; case T_STAR: return true; case T_SLASH: return true; case T_PER: return true; case T_INTCONST: return true; case T_LP: return true; case T_RP: return true; case T_IDENT: return true; default: return false; } return false; } struct ASnode *Exp(int ptp) { struct ASnode *left, *right; int tokentype; left = primary(); if (!check() || token_stream[token_index].token == T_RP) return (left); tokentype = token_stream[token_index].token; while (op_precedence_plus(tokentype) > ptp) { ++token_index; right = Exp(OpPrec_plus[tokentype]); left = newNode(arithop(tokentype), left, right, 0); if (!check() || token_stream[token_index].token == T_RP) return (left); tokentype = token_stream[token_index].token; } return (left); } // Build and return a generic AST node ASnode *newNode(int op, ASnode *left, ASnode *right, int intvalue) { ASnode *n = new ASnode; n->op = op; n->left = left; n->right = right; n->intvalue = intvalue; return (n); } ASnode *newLeaf(int op, int intvalue) { return (newNode(op, NULL, NULL, intvalue)); } ASnode *newUnary(int op, ASnode *left, int intvalue) { return (newNode(op, left, NULL, intvalue)); } // List of AST operators static char const *ASTop[] = { "+", "-", "*", "/", "%" }; int interpretAST(ASnode *n) { int leftval, rightval; if (n->left) leftval = interpretAST(n->left); if (n->right) rightval = interpretAST(n->right); switch (n->op) { case ADD: return (leftval + rightval); case SUBTRACT: return (leftval - rightval); case MULTIPLY: return (leftval * rightval); case DIVIDE: return (leftval / rightval); case MOD: return (leftval % rightval); case INTCONST: return (n->intvalue); default: fprintf(stderr, "Unknown AST operator %d\n", n->op); exit(13); } } // 变量定义 VarDef → Ident {'[' ConstExp ']'} | Ident {'[' ConstExp ']'} '=' InitVal void VarDef(int type, int islocal, int isparam) { int id; vector<int> D; if(islocal == 0){ if (token_stream[token_index].token == T_LBK) { int Array_size = 1; //数组大小 int Dimension = 0; //数组维数 while(token_stream[token_index].token == T_LBK){ match(T_LBK, "["); ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; Array_size = Array_size * nowvalue; D.emplace_back(nowvalue); match(T_RBK, "]"); ++Dimension; } if(token_stream[token_index].token == T_SEMI || token_stream[token_index].token == T_COMMA){ id = addglob(nowname, type, S_ARRAY, 0, Array_size); Symtable[id].Dimens.clear(); Symtable[id].Dimens = D; genglobsym(id, Array_size); }else{ match(T_ASSIGN, "="); //匹配 = match(T_LB, "{"); //匹配 { id = addglob(nowname, type, S_ARRAY, 0, Array_size); Symtable[id].Dimens.clear(); Symtable[id].Dimens = D; vector<int> v(Dimension + 1); for(int i = 1; i <= Dimension; ++i){ int expect = 1; for(int j = i-1; j < D.size(); ++j){ expect = expect * D[j]; } v[i] = expect; //每一维度期望匹配的元素数量 } vector<int> initnum; //数组初始化的值 vector<int> already(Dimension + 1, 0); //每一维度已经匹配到的元素数量 int k = 1; //当前'{'层数, 代表数组维度 while(token_stream[token_index].token != T_SEMI){ if(token_stream[token_index].token == T_INTCONST){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_IDENT){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_MINUS){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_PLUS){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_LP){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_LB){ ++k; match(T_LB, "{"); }else if(token_stream[token_index].token == T_RB){ while(already[k] < v[k]){ initnum.emplace_back(0); ++already[k]; } already[k] = 0; --k; already[k] += v[k+1]; if(k == 0){ match(T_RB, "}"); break; } match(T_RB, "}"); }else{ ++token_index; } } genglobsym_plus(id, initnum); if(con) Symtable[id].conNum = initnum; } } else { if(token_stream[token_index].token == T_SEMI || token_stream[token_index].token == T_COMMA){ id = addglob(nowname, type, S_VARIABLE, 0, 1); genglobsym(id, 1); }else{ match(T_ASSIGN, "="); id = addglob(nowname, type, S_VARIABLE, 0, 1); vector<int> v; ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; if(con){ Symtable[id].intvalue = nowvalue; }else{ v.emplace_back(nowvalue); genglobsym_plus(id, v); } } } }else{ if (token_stream[token_index].token == T_LBK) { int Array_size = 1; int Dimension = 0; while(token_stream[token_index].token == T_LBK){ match(T_LBK, "["); if(token_stream[token_index].token == T_RBK){ match(T_RBK, "]"); D.emplace_back(1); ++Dimension; continue; } ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; Array_size = Array_size * nowvalue; D.emplace_back(nowvalue); match(T_RBK, "]"); ++Dimension; } if(isparam == 1){ Array_size = 1; } Local_v += Array_size; id = addlocl(nowname, type, S_ARRAY, isparam, Array_size); if(isparam == 1){ Symtable[id].paramnum = pars++; } Symtable[id].Dimens.clear(); Symtable[id].Dimens = D; Symtable[id].st_address = -4*Local_v - push_reg; if(con && if_PerformanceTest){ match(T_ASSIGN, "="); match(T_LB, "{"); //匹配 { vector<int> v(Dimension + 1); for(int i = 1; i <= Dimension; ++i){ int expect = 1; for(int j = i-1; j < D.size(); ++j){ expect = expect * D[j]; } v[i] = expect; //每一维度期望匹配的元素数量 } vector<int> initnum; //数组初始化的值 vector<int> already(Dimension + 1, 0); //每一维度已经匹配到的元素数量 int k = 1; //当前'{'层数, 代表数组维度 while(token_stream[token_index].token != T_SEMI){ if(token_stream[token_index].token == T_INTCONST){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_IDENT){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_MINUS){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_PLUS){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_LP){ ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; initnum.emplace_back(nowvalue); ++already[k]; }else if(token_stream[token_index].token == T_LB){ ++k; match(T_LB, "{"); }else if(token_stream[token_index].token == T_RB){ while(already[k] < v[k]){ initnum.emplace_back(0); ++already[k]; } already[k] = 0; --k; already[k] += v[k+1]; if(k == 0){ match(T_RB, "}"); break; } match(T_RB, "}"); }else{ ++token_index; } } Symtable[id].conNum = initnum; } } else { Local_v++; id = addlocl(nowname, type, S_VARIABLE, isparam, 1); if(isparam == 1){ Symtable[id].paramnum = pars++; } Symtable[id].st_address = -4*Local_v - push_reg; if(con){ match(T_ASSIGN, "="); ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); Symtable[id].intvalue = nowvalue; } } } } // 函数形参表 FuncFParams → FuncFParam {',' FuncFParam} static int FuncFParams(void) { int type; int paramcnt=0; pars = 0; while (token_stream[token_index].token != T_RP) { type = FuncType(); ident(); VarDef(type, 1, 1); paramcnt++; switch (token_stream[token_index].token) { case T_COMMA: ++token_index; break; case T_RP: break; default: exit(14); fatald("Unexpected token in parameter list", token_stream[token_index].token); } } return(paramcnt); } // 函数定义 FuncDef → FuncType Ident '(' [FuncFParams] ')' Block ASTnode *FuncDef(int type) { ASTnode *tree = NULL; int nameslot, endlabel, paramcnt; endlabel = genlabel(); nameslot = addglob(nowname, type, S_FUNCTION, endlabel, 0); Functionid = nameslot; func_field = genlabel(); genlabel(); genlabel(); lparen(); paramcnt= FuncFParams(); Symtable[nameslot].nelems= paramcnt; rparen(); tree = Block(); return (newASTunary(A_FUNCTION, type, tree, nameslot)); } // 编译单元 CompUnit → [ CompUnit ] ( Decl | FuncDef ) void CompUnit(void) { ASTnode *tree; int type; while (token_index < token_size) { tree = NULL; if(token_stream[token_index].token == T_CONST){ ++token_index; con = true; } type = FuncType(); ident(); Local_v = 0; max_param = 0; if (token_stream[token_index].token == T_LP) { func_v = 0; LCslot = 0; ldr_Byte = 0; tree = FuncDef(type); CodeGen(tree, NOLABEL, NOLABEL, NOLABEL, 0); freeloclsyms(); } else { VarDef(type, 0, 0); while(token_stream[token_index].token == T_COMMA){ match(T_COMMA, ","); ident(); VarDef(type, 0, 0); } semi(); } con = false; } } static ASTnode *funccall(void) { ASTnode *root = NULL; ASTnode *temp; int id; if ((id = findsymbol(nowname)) == -1 || Symtable[id].stype != S_FUNCTION) { fatals("Undeclared function", nowname); } int parnum = 0; int nowline = token_stream[token_index].line; // Get the '(' lparen(); if(token_stream[token_index].token != T_RP){ if(token_stream[token_index].token == T_STRCONST){ root =newASTleaf(A_STRLIT, P_NONE, 0); addString(token_stream[token_index].strvalue); root->strvalue = token_stream[token_index].strvalue; match(T_STRCONST, "String"); }else{ root = Exp_Stmt(); } temp = root; ++parnum; while(token_stream[token_index].token == T_COMMA){ ++token_index; ASTnode *a; if(token_stream[token_index].token == T_STRCONST){ a =newASTleaf(A_STRLIT, P_NONE, 0); a->strvalue = token_stream[token_index].strvalue; match(T_STRCONST, "String"); }else{ a = Exp_Stmt(); } temp->next = a; temp = temp->next; ++parnum; } } root = newASTunary(A_FUNCCALL, Symtable[id].type, root, id); root->line = nowline; func_v += parnum; // Get the ')' max_param = max(max_param, parnum); rparen(); return (root); } static ASTnode *array_access(void) { ASTnode *tree; int id; int Dimension_num = 0; if ((id = findsymbol(nowname)) == -1 || Symtable[id].stype != S_ARRAY) { fatals("Undeclared array", nowname); } if(if_PerformanceTest && Symtable[id].conNum.size() > 0){ int cnt = 1; int index = 0; const int len = Symtable[id].Dimens.size(); while(token_stream[token_index].token == T_LBK){ int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[id].Dimens[i]; } match(T_LBK, "["); ASnode *IntExp = Exp(0); int nowvalue = interpretAST(IntExp); delete IntExp; index += nowvalue * k; match(T_RBK, "]"); } tree = newASTleaf(A_INTLIT, P_INT, Symtable[id].conNum[index]); }else{ match(T_LBK, "["); tree = Exp_Stmt(); ++Dimension_num; match(T_RBK, "]"); ASTnode *temp = tree; while(token_stream[token_index].token == T_LBK) { match(T_LBK, "["); ASTnode *a = Exp_Stmt(); temp->next = a; temp = temp->next; ++Dimension_num; match(T_RBK, "]"); } tree = newASTunary(A_ADDR, P_INT, tree, id); tree->Dimension_num = Dimension_num; } return (tree); } static ASTnode *LVal(void) { ASTnode *n; int id; ident(); if (token_stream[token_index].token == T_LP) return (funccall()); if (token_stream[token_index].token == T_LBK) return (array_access()); id = findsymbol(nowname); if (id == -1) fatals("Unknown variable", nowname); if(Symtable[id].intvalue != INF){ n = newASTleaf(A_INTLIT, P_INT, Symtable[id].intvalue); }else{ n = newASTleaf(A_IDENT, Symtable[id].type, id); } return (n); } static ASTnode *PrimaryExp(void) { ASTnode *n; int id; switch (token_stream[token_index].token) { case T_INTCONST: n = newASTleaf(A_INTLIT, P_INT, token_stream[token_index].intvalue); break; case T_IDENT: return (LVal()); case T_LP: lparen(); n = Exp_Stmt(); rparen(); return (n); default: exit(15); fatald("Expecting a PrimaryExp expression, got token", token_stream[token_index].token); } ++token_index; return (n); } ASTnode *UnaryExp(void) { ASTnode *tree; switch (token_stream[token_index].token) { case T_LOGNOT: case T_MINUS: case T_PLUS: { int cnt = 0, cnt1 = 0; while((token_stream[token_index].token == T_LOGNOT) || (token_stream[token_index].token == T_PLUS) || (token_stream[token_index].token == T_MINUS)){ if(token_stream[token_index].token == T_LOGNOT) ++cnt; if(token_stream[token_index].token == T_MINUS) ++cnt1; ++token_index; } tree = UnaryExp(); tree->rvalue = 1; if(cnt%2 == 1){ tree = newASTunary(A_LOGNOT, tree->type, tree, 0); } if(cnt1%2 == 1){ tree = newASTunary(A_RSB, tree->type, tree, 0); } break; } default: tree = PrimaryExp(); } return (tree); } // 加减表达式 AddExp → MulExp | AddExp ('+' | '-') MulExp ASTnode *AddExp() { ASTnode *left, *right; left = MulExp(); left->rvalue = 1; while((token_stream[token_index].token == T_PLUS) || (token_stream[token_index].token == T_MINUS)){ if(token_stream[token_index].token == T_PLUS){ match(T_PLUS, "+"); right = MulExp(); right->rvalue = 1; left = newASTnode(A_ADD, P_INT, left, NULL, right, 0); left->rvalue = 1; }else if(token_stream[token_index].token == T_MINUS){ match(T_MINUS, "-"); right = MulExp(); right->rvalue = 1; left = newASTnode(A_SUBTRACT, P_INT, left, NULL, right, 0); left->rvalue = 1; } } return left; } // 乘除模表达式 MulExp → UnaryExp | MulExp ('*' | '/' | '%') UnaryExp ASTnode *MulExp(){ ASTnode *left, *right; left = UnaryExp(); left->rvalue = 1; while((token_stream[token_index].token == T_STAR) || (token_stream[token_index].token == T_SLASH) || (token_stream[token_index].token == T_PER)){ if(token_stream[token_index].token == T_STAR){ match(T_STAR, "*"); right = UnaryExp(); right->rvalue = 1; left = newASTnode(A_MULTIPLY, P_INT, left, NULL, right, 0); left->rvalue = 1; }else if(token_stream[token_index].token == T_SLASH){ match(T_SLASH, "/"); right = UnaryExp(); right->rvalue = 1; left = newASTnode(A_DIVIDE, P_INT, left, NULL, right, 0); left->rvalue = 1; }else if(token_stream[token_index].token == T_PER){ match(T_PER, "%"); right = UnaryExp(); right->rvalue = 1; left = newASTnode(A_MOD, P_INT, left, NULL, right, 0); left->rvalue = 1; } } return left; } ASTnode *Exp_Stmt() { return AddExp(); } // Prototypes static ASTnode *BlockItem(void); static ASTnode *Stmt(void); // 条件表达式 Cond → LOrExp ASTnode *Cond() { return LOrExp(); } // 逻辑或表达式 LOrExp → LAndExp | LOrExp '||' LAndExp ASTnode *LOrExp() { ASTnode *left, *right; left = LAndExp(); left->rvalue = 1; while(token_stream[token_index].token == T_LOGOR){ match(T_LOGOR, "||"); right = LAndExp(); right->rvalue = 1; left = newASTnode(A_LOGOR, P_INT, left, NULL, right, 0); left->rvalue = 1; } return left; } // 逻辑与表达式 AndExp → EqExp | AndExp '&&' EqExp ASTnode *LAndExp() { ASTnode *left, *right; left = EqExp(); left->rvalue = 1; while(token_stream[token_index].token == T_LOGAND){ match(T_LOGAND, "&&"); right = EqExp(); right->rvalue = 1; left = newASTnode(A_LOGAND, P_INT, left, NULL, right, 0); left->rvalue = 1; } return left; } // 相等性表达式 EqExp → RelExp | EqExp ('==' | '!=') RelExp ASTnode *EqExp() { ASTnode *left, *right; left = RelExp(); left->rvalue = 1; while((token_stream[token_index].token == T_EQ) || (token_stream[token_index].token == T_NE)){ if(token_stream[token_index].token == T_EQ){ match(T_EQ, "=="); right = RelExp(); right->rvalue = 1; left = newASTnode(A_EQ, P_INT, left, NULL, right, 0); left->rvalue = 1; }else{ match(T_NE, "!="); right = RelExp(); right->rvalue = 1; left = newASTnode(A_NE, P_INT, left, NULL, right, 0); left->rvalue = 1; } } return left; } // 关系表达式 RelExp → AddExp | RelExp ('<' | '>' | '<=' | '>=') AddExp ASTnode *RelExp() { ASTnode *left, *right; left = AddExp(); left->rvalue = 1; while((token_stream[token_index].token == T_LT) || (token_stream[token_index].token == T_GT) || (token_stream[token_index].token == T_LE) || (token_stream[token_index].token == T_GE)){ if(token_stream[token_index].token == T_LT){ match(T_LT, "<"); right = AddExp(); right->rvalue = 1; left = newASTnode(A_LT, P_INT, left, NULL, right, 0); left->rvalue = 1; }else if(token_stream[token_index].token == T_GT){ match(T_GT, ">"); right = AddExp(); right->rvalue = 1; left = newASTnode(A_GT, P_INT, left, NULL, right, 0); left->rvalue = 1; }else if(token_stream[token_index].token == T_LE){ match(T_LE, "<="); right = AddExp(); right->rvalue = 1; left = newASTnode(A_LE, P_INT, left, NULL, right, 0); left->rvalue = 1; }else{ match(T_GE, ">="); right = AddExp(); right->rvalue = 1; left = newASTnode(A_GE, P_INT, left, NULL, right, 0); left->rvalue = 1; } } return left; } static ASTnode *if_Stmt(void) { ASTnode *condAST, *trueAST, *falseAST = NULL; match(T_IF, "if"); lparen(); condAST = Cond(); rparen(); trueAST = Stmt(); if (token_stream[token_index].token == T_ELSE) { ++token_index; falseAST = Stmt(); } return (newASTnode(A_IF, P_NONE, condAST, trueAST, falseAST, 0)); } static ASTnode *while_Stmt(void) { ASTnode *condAST, *bodyAST; match(T_WHILE, "while"); lparen(); condAST = Cond(); rparen(); Looplevel++; bodyAST = Stmt(); Looplevel--; return (newASTnode(A_WHILE, P_NONE, condAST, NULL, bodyAST, 0)); } static ASTnode *return_Stmt(void) { ASTnode *tree = NULL; match(T_RETURN, "return"); if (Symtable[Functionid].type == P_INT){ tree = Exp_Stmt(); if (tree == NULL) fatal("Incompatible type to return"); } tree = newASTunary(A_RETURN, P_NONE, tree, 0); semi(); return (tree); } static ASTnode *break_Stmt(void) { if (Looplevel == 0) fatal("no loop to break out from"); match(T_BREAK, "break"); semi(); return (newASTleaf(A_BREAK, 0, 0)); } static ASTnode *continue_Stmt(void) { if (Looplevel == 0) fatal("no loop to continue to"); match(T_CONTINUE, "continue"); semi(); return (newASTleaf(A_CONTINUE, 0, 0)); } /* 语句 Stmt → LVal '=' Exp ';' | [Exp]';' | Block | 'if' '(' Cond ')' Stmt ['else' Stmt] | 'while' '(' Cond ')' Stmt | 'break' ';' | 'continue' ';' | 'return' [Exp] ';' */ static ASTnode *Stmt(void){ ASTnode *left, *right; switch (token_stream[token_index].token) { case T_IF: return (if_Stmt()); case T_WHILE: return (while_Stmt()); case T_RETURN: return (return_Stmt()); case T_BREAK: return (break_Stmt()); case T_CONTINUE: return (continue_Stmt()); case T_LB: return (Block()); case T_SEMI: semi(); return (NULL); default: { bool flag = false; int index = token_index; while(token_stream[index].token != T_SEMI){ if(token_stream[index].token == T_ASSIGN){ flag = true; break; } ++index; } if(flag){ right = LVal(); match(T_ASSIGN, "="); left = Exp_Stmt(); semi(); ASTnode *tree = newASTnode(A_ASSIGN, P_INT, left, NULL, right, 0); tree->rvalue = 1; return tree; }else{ left = Exp_Stmt(); semi(); return left; } } } return (NULL); } // 语句块项 BlockItem → Decl | Stmt static ASTnode *BlockItem(void) { int type; if(token_stream[token_index].token == T_CONST){ ++token_index; con = true; } switch (token_stream[token_index].token) { case T_INT: { ASTnode *root = newASTunary(A_DEFINE, P_NONE, NULL, 0); ASTnode *temp = root; type = FuncType(); int tindex = token_index; string str = token_stream[token_index].strvalue; ident(); VarDef(type, 1, 0); while(token_stream[token_index].token != T_SEMI){ if(token_stream[token_index].token == T_COMMA){ match(T_COMMA, ","); tindex = token_index; str = token_stream[token_index].strvalue; ident(); VarDef(type, 1, 0); }else if(token_stream[token_index].token == T_ASSIGN && token_stream[token_index+1].token == T_LB){ token_index = tindex; ASTnode *right = LVal(); match(T_ASSIGN, "="); match(T_LB, "{"); int id = findsymbol(str); ASTnode *left = newASTnode(A_INIT, Symtable[id].size, NULL, NULL, NULL, Symtable[id].st_address); ASTnode *temp1 = left; int Dimension = Symtable[id].Dimens.size(); vector<int> D = Symtable[id].Dimens; vector<int> v(Dimension + 1); for(int i = 1; i <= Dimension; ++i){ int expect = 1; for(int j = i-1; j < D.size(); ++j){ expect = expect * D[j]; } v[i] = expect; } vector<int> already(Dimension + 1, 0); int k = 1; while(token_stream[token_index].token != T_SEMI){ if(token_stream[token_index].token == T_INTCONST){ ASTnode *tree1 = newASTleaf(A_INTLIT, P_INT, token_stream[token_index].intvalue); tree1->rvalue = 1; temp1->next = tree1; temp1 = temp1->next; ++already[k]; ++token_index; }else if(token_stream[token_index].token == T_IDENT){ ASTnode *tree1 = LVal(); tree1->rvalue = 1; temp1->next = tree1; temp1 = temp1->next; ++already[k]; }else if(token_stream[token_index].token == T_LB){ ++k; match(T_LB, "{"); }else if(token_stream[token_index].token == T_RB){ while(already[k] < v[k] && k != 1){ ASTnode *tree1 = newASTleaf(A_INTLIT, P_INT, 0); tree1->rvalue = 1; temp1->next = tree1; temp1 = temp1->next; ++already[k]; } already[k] = 0; --k; already[k] += v[k+1]; if(k == 0){ match(T_RB, "}"); break; } match(T_RB, "}"); }else{ ++token_index; } } ASTnode *tree = newASTnode(A_ASSIGN, P_INT, left, NULL, right, 0); tree->rvalue = 1; temp->next = tree; temp = temp->next; }else if(token_stream[token_index].token == T_ASSIGN){ token_index = tindex; ASTnode *right = LVal(); match(T_ASSIGN, "="); ASTnode *left = Exp_Stmt(); ASTnode *tree = newASTnode(A_ASSIGN, P_INT, left, NULL, right, 0); tree->rvalue = 1; temp->next = tree; temp = temp->next; }else{ fprintf(stderr, "ERROR!\n"); exit(16); } } semi(); con = false; return (root); } default: return (Stmt()); } return (NULL); } // 语句块 Block → '{' {BlockItem} '}' ASTnode *Block(void) { ASTnode *left = NULL; ASTnode *tree; lbrace(); if (token_stream[token_index].token == T_RB) { rbrace(); return (left); } while (1) { tree = BlockItem(); if (tree != NULL) { if (left == NULL) left = tree; else left = newASTnode(A_GLUE, P_NONE, left, NULL, tree, 0); } if (token_stream[token_index].token == T_RB) { rbrace(); return (left); } } } static int genIF(ASTnode *n, int looptoplabel, int loopendlabel) { int Ltrue, Lfalse, Lend; Ltrue = genlabel(); true_L = Ltrue; Lfalse = genlabel(); if (n->right) Lend = genlabel(); if(n->left->op == A_LOGOR) n->left->istop = true; int reg = CodeGen(n->left, Lfalse, looptoplabel, loopendlabel, n->op); if(reg != NOREG){ ARM_cmp_jump(reg, Lfalse); } genfreeregs(); ARM_label(Ltrue); if(n->mid) CodeGen(n->mid, NOLABEL, looptoplabel, loopendlabel, NOLABEL); genfreeregs(); if (n->right) ARM_jump(Lend); ARM_label(Lfalse); if (n->right) { CodeGen(n->right, NOLABEL, looptoplabel, loopendlabel, NOLABEL); genfreeregs(); ARM_label(Lend); } return (NOREG); } static int genWHILE(ASTnode *n) { int Lstart, Ltrue, Lend; Lstart = genlabel(); Ltrue = genlabel(); true_L = Ltrue; Lend = genlabel(); if(if_PerformanceTest){ if(while_level == 0){ while_ed = ObjectCode.size(); for(int i = while_st; i < while_ed; ++i){ ScanRegPass(ObjectCode[i]); } max_alloc -= 4; vector<pair<int, int> >a; for(auto x : ump){ a.push_back(x); } sort(a.begin(), a.end(), cmp); int now = 0; while(1){ if(now >= a.size()) break; if(a[now].second <= Threshold) break; int reg = alloc_register_plus(); if(reg == -1) break; newReg[a[now].first] = reg; ++now; } for(int i = while_st; i < while_ed; ++i){ ObjectCode[i] = AllocRegPass(ObjectCode[i]); } for(auto &x : newReg){ int address = x.first; int r = x.second; sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[r], address); ObjectCode.emplace(ObjectCode.begin() + while_ed, buf); } for(auto &x : newReg){ int address = x.first; int r = x.second; sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[r], address); ObjectCode.emplace(ObjectCode.begin() + while_st, buf); } max_alloc = 0; while_st = ObjectCode.size(); ump.clear(); newReg.clear(); } while_level++; } ARM_label(Lstart); if(n->left->op == A_LOGOR) n->left->istop = true; int reg = CodeGen(n->left, Lend, Lstart, Lend, n->op); if(reg != NOREG){ ARM_cmp_jump(reg, Lend); } genfreeregs(); ARM_label(Ltrue); if(n->right) CodeGen(n->right, NOLABEL, Lstart, Lend, NOLABEL); genfreeregs(); ARM_jump(Lstart); ARM_label(Lend); if(if_PerformanceTest){ while_level--; if(while_level == 0){ while_ed = ObjectCode.size(); for(int i = while_st; i < while_ed; ++i){ ScanRegPass(ObjectCode[i]); } max_alloc -= 4; vector<pair<int, int> >a; for(auto x : ump){ a.push_back(x); } sort(a.begin(), a.end(), cmp); int now = 0; while(1){ if(now >= a.size()) break; int reg = alloc_register_plus(); if(reg == -1) break; newReg[a[now].first] = reg; ++now; } for(int i = while_st; i < while_ed; ++i){ ObjectCode[i] = AllocRegPass(ObjectCode[i]); } for(auto &x : newReg){ int address = x.first; int r = x.second; sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[r], address); ObjectCode.emplace(ObjectCode.begin() + while_ed, buf); } for(auto &x : newReg){ int address = x.first; int r = x.second; sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[r], address); ObjectCode.emplace(ObjectCode.begin() + while_st, buf); } max_alloc = 0; while_st = ObjectCode.size(); ump.clear(); newReg.clear(); } } return (NOREG); } vector<pair<int, int> > nested_calls[MAXN]; int nested_index = 0; int OutputFunccall(ASTnode* L, int ri){ ASTnode *r; int reg; r = L->next; if(r != NULL){ OutputFunccall(r, ri+1); } if(L->op != A_INTLIT && Symtable[L->v.id].stype == S_ARRAY && L->Dimension_num < Symtable[L->v.id].Dimens.size()){ int len = Symtable[L->v.id].Dimens.size(); int cnt = 1; ASTnode *test = L->left; bool flag = true; int off_size = 0; while(test != NULL){ if(test->op == A_INTLIT){ int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[L->v.id].Dimens[i]; } off_size += k * (test->v.intvalue); test = test->next; ++cnt; }else{ flag = false; break; } } int reg1 = alloc_register(); if(flag){ if(off_size <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg1], off_size); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, off_size); } }else if(len == 1){ free_register(reg); ASTnode *a = L->left; reg = CodeGen(a, NOLABEL, NOLABEL, NOLABEL, L->op); }else{ int rightreg; ASTnode *a = L->left; cnt = 1; while(a != NULL){ rightreg = CodeGen(a, NOLABEL, NOLABEL, NOLABEL, L->op); a = a->next; int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[L->v.id].Dimens[i]; } if(cnt < len){ int reg2 = alloc_register(); if (k <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg2], k); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} }else { int offset = -1; for (int i = 0; i < Intlist.size(); i++) { if (Intlist[i] == k) { offset = 4 * i; break; } } if (offset == -1) { offset = 4 * Intslot; Intlist.emplace_back(k); ++Intslot; ldr_Byte += (8 + leng(k)); } for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[reg2], func_field, offset); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } if(cnt == 1){ sprintf(buf, "\tmul\t%s, %s, %s\n", reglist[reg1], reglist[reg2], reglist[rightreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(rightreg); free_register(reg2); }else{ reg1 = ARM_mla(reg1, rightreg, reg2); } }else{ ARM_add(reg1, rightreg); } ++cnt; } } sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } reg = alloc_register(); int address = -4*Local_v - push_reg - 4*func_v; if(Symtable[L->v.id].ctype == C_GLOBAL){ int offset = 0; for (int i = 0; i < L->v.id; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[reg], func_field, offset); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } if(if_PerformanceTest){ if(ri < 4){ sprintf(buf, "\tadd\tr%d, %s, %s\n", ri, reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg1); }else{ int off = (ri-4)*4; ARM_add(reg, reg1); sprintf(buf, "\tstr\t%s, [sp, #%d]\n", reglist[reg], off); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } }else{ ARM_add(reg, reg1); int off = abs(address); int reg2 = alloc_register(); if(off <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[reg], address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg2, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg2], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[reg], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg2); } }else if(Symtable[L->v.id].ctype == C_LOCAL){ int subnum = abs(Symtable[L->v.id].st_address); int reg2 = alloc_register(); if(subnum <= imm12){ sprintf(buf, "\tsub\t%s, fp, #%d\n", reglist[reg], subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg2, subnum); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg2); if(if_PerformanceTest){ if(ri < 4){ sprintf(buf, "\tadd\tr%d, %s, %s\n", ri, reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg1); }else{ int off = (ri-4)*4; ARM_add(reg, reg1); sprintf(buf, "\tstr\t%s, [sp, #%d]\n", reglist[reg], off); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } }else{ ARM_add(reg, reg1); int off = abs(address); int reg3 = alloc_register(); if(off <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[reg], address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg3, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg3], reglist[reg3]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[reg], reglist[reg3]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg3); } }else{ if(Symtable[L->v.id].paramnum < 4){ sprintf(buf, "\tldr %s, [fp, #%d]\n", reglist[reg], Symtable[L->v.id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int subnum = (Symtable[L->v.id].paramnum-3)*4; if(subnum <= imm8){ sprintf(buf, "\tldr %s, [fp, #%d]\n", reglist[reg], subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int reg2 = alloc_register(); set_int_offset(reg2, subnum); sprintf(buf, "\tadd\t%s, fp, %s\n", reglist[reg2], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr %s, [%s]\n", reglist[reg], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg2); } } if(if_PerformanceTest){ if(ri < 4){ sprintf(buf, "\tadd\tr%d, %s, %s\n", ri, reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg1); }else{ int off = (ri-4)*4; ARM_add(reg, reg1); sprintf(buf, "\tstr\t%s, [sp, #%d]\n", reglist[reg], off); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } }else{ ARM_add(reg, reg1); int off = abs(address); int reg2 = alloc_register(); if(off <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[reg], address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg2, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg2], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[reg], reglist[reg2]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg2); } } nested_calls[nested_index].emplace_back(address, ri); func_v++; free_register(reg); }else{ reg = CodeGen(L, NOLABEL, NOLABEL, NOLABEL, A_FUNCCALL); int address = -4*Local_v - push_reg - 4*func_v; if(if_PerformanceTest){ if(ri < 4){ sprintf(buf, "\tmov\tr%d, %s\n", ri, reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int off = (ri-4)*4; sprintf(buf, "\tstr\t%s, [sp, #%d]\n", reglist[reg], off); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } }else{ int off = abs(address); int reg1 = alloc_register(); if(off <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[reg], address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg1); } nested_calls[nested_index].emplace_back(address, ri); func_v++; free_register(reg); } return reg; } int CodeGen(ASTnode *n, int label, int looptoplabel, int loopendlabel, int parentASTop) { if(n == NULL) return NOREG; int leftreg = -1, rightreg = -1; if((n->op == A_FUNCCALL) && (Symtable[n->v.id].name == "starttime")){ sprintf(buf, "\tmov\tr0, #%d\n", n->line); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbl _sysy_starttime\n"); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } return (NOREG); } if((n->op == A_FUNCCALL) && (Symtable[n->v.id].name == "stoptime")){ sprintf(buf, "\tmov\tr0, #%d\n", n->line); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbl _sysy_stoptime\n"); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } return (NOREG); } if(n->op == A_STRLIT){ leftreg = alloc_register(); set_lc_offset(leftreg, n->strvalue); return leftreg; } /*局部数组初始化*/ if(n->op == A_ASSIGN && n->left->op == A_INIT){ n = n->left; int address = n->v.intvalue; int num = n->type*4; int subnum = abs(address); int reg = alloc_register(); if(subnum <= imm8){ sprintf(buf, "\tsub\tr3, fp, #%d\n", subnum); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg, subnum); sprintf(buf, "\tsub\tr3, fp, %s\n", reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } if(num <= imm16){ sprintf(buf, "\tmov\tr2, #%d\n", num); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg, num); sprintf(buf, "\tmov\tr2, %s\n", reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } sprintf(buf, "\tmov\tr1, #0\n"); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tmov\tr0, r3\n"); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbl\tmemset\n"); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg); int cnt = 0; ASTnode *a = n->next; while(a != NULL){ leftreg = CodeGen(a, label, looptoplabel, loopendlabel, A_GLUE); a = a->next; int off = abs(address + 4*cnt); if(off <= imm8){ sprintf(buf, "\tstr\t%s, [fp, #%d]\n", reglist[leftreg], address + 4*cnt); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int reg1 = alloc_register(); set_int_offset(reg1, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[leftreg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg1); } genfreeregs(); ++cnt; } return (NOREG); } switch (n->op) { /*局部变量初始化*/ case A_DEFINE: { ASTnode *a = n->next; while(a != NULL){ CodeGen(a, label, looptoplabel, loopendlabel, A_GLUE); genfreeregs(); a = a->next; } return (NOREG); } /*if-else语句*/ case A_IF: return (genIF(n, looptoplabel, loopendlabel)); /*while语句*/ case A_WHILE: return (genWHILE(n)); /*语句直接的连接枢纽*/ case A_GLUE: CodeGen(n->left, label, looptoplabel, loopendlabel, n->op); genfreeregs(); CodeGen(n->right, label, looptoplabel, loopendlabel, n->op); genfreeregs(); return (NOREG); /*函数声明*/ case A_FUNCTION: ARM_funcpre(n->v.id); CodeGen(n->left, NOLABEL, NOLABEL, NOLABEL, n->op); ARM_funcpos(n->v.id); genfreeregs(); return (NOREG); /*数组*/ case A_ADDR: { int len = Symtable[n->v.id].Dimens.size(); int cnt = 1; ASTnode *test = n->left; bool flag = true; int off_size = 0; while(test != NULL){ if(test->op == A_INTLIT){ int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[n->v.id].Dimens[i]; } off_size += k * (test->v.intvalue); test = test->next; ++cnt; }else{ flag = false; break; } } int reg = alloc_register(); //计算偏移量 if(flag){ if(off_size <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg], off_size); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg, off_size); } }else if(len == 1){ free_register(reg); ASTnode *a = n->left; reg = CodeGen(a, NOLABEL, NOLABEL, NOLABEL, n->op); }else{ cnt = 1; ASTnode *a = n->left; while(a != NULL){ rightreg = CodeGen(a, NOLABEL, NOLABEL, NOLABEL, n->op); a = a->next; int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[n->v.id].Dimens[i]; } if(cnt < len){ int reg1 = alloc_register(); if (k <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg1], k); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else { int offset = -1; for (int i = 0; i < Intlist.size(); i++) { if (Intlist[i] == k) { offset = 4 * i; break; } } if (offset == -1) { offset = 4 * Intslot; Intlist.emplace_back(k); ++Intslot; ldr_Byte += (8 + leng(k)); } for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[reg1], func_field, offset); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } if(cnt == 1){ sprintf(buf, "\tmul\t%s, %s, %s\n", reglist[reg], reglist[reg1], reglist[rightreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(rightreg); free_register(reg1); }else{ reg = ARM_mla(reg, rightreg, reg1); } }else{ ARM_add(reg, rightreg); } ++cnt; } } int reg1 = alloc_register(); if(Symtable[n->v.id].ctype == C_GLOBAL){ int reg2 = ARM_var_offset(n->v.id); sprintf(buf, "\tldr\t%s, [%s, %s, lsl #2]\n", reglist[reg1], reglist[reg2], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg2); }else if(Symtable[n->v.id].ctype == C_LOCAL){ int reg2 = alloc_register(); sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[reg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tsub\t%s, fp, #%d\n", reglist[reg2], push_reg); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } ARM_add(reg, reg2); int off = abs(Symtable[n->v.id].st_address + push_reg); if(off <= imm8){ sprintf(buf, "\tldr\t%s, [%s, #%d]\n", reglist[reg1], reglist[reg], Symtable[n->v.id].st_address + push_reg); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int reg3 = alloc_register(); set_int_offset(reg3, off); sprintf(buf, "\tsub\t%s, %s, %s\n", reglist[reg], reglist[reg], reglist[reg3]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg1], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg3); } }else{ int reg2 = alloc_register(); if(Symtable[n->v.id].paramnum < 4){ sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[reg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg2], Symtable[n->v.id].st_address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } ARM_add(reg, reg2); sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg1], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field();} }else{ sprintf(buf, "\tlsl\t%s, %s, #2\n", reglist[reg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } int off = (Symtable[n->v.id].paramnum - 3)*4; if(off <= imm8){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg2], off); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int reg3 = alloc_register(); set_int_offset(reg3, off); sprintf(buf, "\tadd\t%s, fp, %s\n", reglist[reg3], reglist[reg3]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg2], reglist[reg3]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg3); } ARM_add(reg, reg2); sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg1], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } } free_register(reg); return reg1; } case A_LOGAND: leftreg = CodeGen(n->left, label, looptoplabel, loopendlabel, n->op); if(leftreg != NOREG){ sprintf(buf, "\tcmp\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbeq\t.L%d\n", label); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } genfreeregs(); if(n->istop) last_and = true; leftreg = CodeGen(n->right, label, looptoplabel, loopendlabel, n->op); if(leftreg != NOREG){ if(last_and && !last_or){ sprintf(buf, "\tcmp\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbne\t.L%d\n", true_L); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ sprintf(buf, "\tcmp\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbeq\t.L%d\n", label); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } } if(n->istop) last_and = false; genfreeregs(); return (NOREG); case A_LOGOR: { int Lfalse = genlabel(); if(n->left->op == A_LOGAND) n->left->istop = true; leftreg = CodeGen(n->left, Lfalse, looptoplabel, loopendlabel, n->op); if(leftreg != NOREG){ sprintf(buf, "\tcmp\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbne\t.L%d\n", true_L); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } genfreeregs(); ARM_label(Lfalse); if(n->istop) last_or = true; if(n->right->op == A_LOGAND) n->right->istop = true; leftreg = CodeGen(n->right, label, looptoplabel, loopendlabel, n->op); if(leftreg != NOREG){ if(last_or){ sprintf(buf, "\tcmp\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbeq\t.L%d\n", label); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ sprintf(buf, "\tcmp\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tbne\t.L%d\n", true_L); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } } if(n->istop) last_or = false; genfreeregs(); return (NOREG); } } if((n->op == A_FUNCCALL) && (n->left == NULL)){ leftreg = alloc_register(); ++nested_index; } if (n->left){ if(n->op == A_FUNCCALL){ ++nested_index; leftreg = OutputFunccall(n->left, 0); freereg[leftreg] = 0; }else{ leftreg = CodeGen(n->left, NOLABEL, NOLABEL, NOLABEL, n->op); } } if (n->right){ if(n->op == A_ASSIGN){ if(n->right->op == A_ADDR){ ASTnode *t = n->right; ASTnode *test = t->left; bool flag = true; int len = Symtable[t->v.intvalue].Dimens.size(); int cnt = 1; int off_size = 0; while(test != NULL){ if(test->op == A_INTLIT){ int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[t->v.id].Dimens[i]; } off_size += k * (test->v.intvalue); test = test->next; ++cnt; }else{ flag = false; break; } } int reg = alloc_register(); if(flag){ if(off_size <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg], off_size); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg, off_size); } }else if(len == 1){ free_register(reg); ASTnode *a = t->left; reg = CodeGen(a, NOLABEL, NOLABEL, NOLABEL, t->op); }else{ ASTnode *a = t->left; cnt = 1; while(a != NULL){ rightreg = CodeGen(a, NOLABEL, NOLABEL, NOLABEL, t->op); a = a->next; int k = 1; for(int i = cnt; i < len; ++i){ k = k*Symtable[t->v.id].Dimens[i]; } if(cnt < len){ int reg1 = alloc_register(); if (k <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[reg1], k); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else { int offset = -1; for (int i = 0; i < Intlist.size(); i++) { if (Intlist[i] == k) { offset = 4 * i; break; } } if (offset == -1) { offset = 4 * Intslot; Intlist.emplace_back(k); ++Intslot; ldr_Byte += (8 + leng(k)); } for (int i = 0; i < Globs; i++) { if ((Symtable[i].stype == S_VARIABLE || Symtable[i].stype == S_ARRAY) && (Symtable[i].intvalue == INF)) offset += 4; } sprintf(buf, "\tldr\t%s, .L%d+%d\n", reglist[reg1], func_field, offset); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } if(cnt == 1){ sprintf(buf, "\tmul\t%s, %s, %s\n", reglist[reg], reglist[reg1], reglist[rightreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(rightreg); free_register(reg1); }else{ reg = ARM_mla(reg, rightreg, reg1); } }else{ ARM_add(reg, rightreg); } ++cnt; } } rightreg = reg; } }else{ rightreg = CodeGen(n->right, NOLABEL, NOLABEL, NOLABEL, n->op); } } switch (n->op) { case A_ADD: return (ARM_add(leftreg, rightreg)); case A_SUBTRACT: return (ARM_sub(leftreg, rightreg)); case A_MULTIPLY: { int val = -1; if(n->right->op == A_INTLIT){ int value = n->right->v.intvalue; for(int ii = 0; ii < 31 && value>=P_2[ii]; ++ii){ if(value == P_2[ii]){ val = ii; break; } } } if(val != -1 && if_PerformanceTest){ return (ARM_lsl(leftreg, rightreg, val)); }else{ return (ARM_mul(leftreg, rightreg)); } } case A_DIVIDE: { int val = -1; if(n->right->op == A_INTLIT){ int value = n->right->v.intvalue; for(int ii = 0; ii < 31 && value>=P_2[ii]; ++ii){ if(value == P_2[ii]){ val = ii; break; } } } if(val != -1 && if_PerformanceTest){ return (ARM_asr(leftreg, rightreg, val)); }else if(n->right->op == A_INTLIT && if_PerformanceTest){ int value = n->right->v.intvalue; if(value == 1){ free_register(rightreg); return leftreg; }else if(value == -1){ free_register(rightreg); return ARM_rsb(leftreg); }else{ int val = abs(value); int k = 0; while((2 << k) < val) ++k; --k; unsigned long long t = pow(2, k+32); int factor = ceil(1.0 * t / val); set_int_offset(rightreg, factor); int reg = alloc_register(); sprintf(buf, "\tsmull\t%s, %s, %s, %s\n", reglist[reg], reglist[rightreg], reglist[rightreg], reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg); sprintf(buf, "\tasr\t%s, %s, #31\n", reglist[leftreg], reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\trsb\t%s, %s, %s, asr #%d\n", reglist[leftreg], reglist[leftreg], reglist[rightreg], k); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(rightreg); return leftreg; } }else{ return (ARM_div(leftreg, rightreg)); } } case A_MOD: { if(n->right->op == A_INTLIT && if_PerformanceTest){ int value = n->right->v.intvalue; int p = -1; for(int ii = 0; ii < 31 && value>=P_2[ii]; ++ii){ if(value == P_2[ii]){ p = ii; break; } } if(value == 1 || value == -1){ sprintf(buf, "\tmov\t%s, #0\n", reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(rightreg); return leftreg; }else if(p != -1){ int reg = alloc_register(); sprintf(buf, "\trsbs\t%s, %s, #0\n", reglist[reg], reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } if(P_2[p]-1 <= imm8){ sprintf(buf, "\tand\t%s, %s, #%d\n", reglist[reg], reglist[reg], P_2[p]-1); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(rightreg, P_2[p]-1); sprintf(buf, "\tand\t%s, %s, %s\n", reglist[reg], reglist[reg], reglist[rightreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } if(P_2[p]-1 <= imm8){ sprintf(buf, "\tand\t%s, %s, #%d\n", reglist[leftreg], reglist[leftreg], P_2[p]-1); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(rightreg, P_2[p]-1); sprintf(buf, "\tand\t%s, %s, %s\n", reglist[leftreg], reglist[leftreg], reglist[rightreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } sprintf(buf, "\trsbpl\t%s, %s, #0\n", reglist[leftreg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(rightreg); return leftreg; }else{ int reg = alloc_register(); sprintf(buf, "\tmov\t%s, %s\n", reglist[reg], reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } int val = abs(value); int k = 0; while((2 << k) < val) ++k; --k; unsigned long long t = pow(2, k+32); int factor = ceil(1.0 * t / val); set_int_offset(rightreg, factor); int reg1 = alloc_register(); sprintf(buf, "\tsmull\t%s, %s, %s, %s\n", reglist[reg1], reglist[rightreg], reglist[rightreg], reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg1); sprintf(buf, "\tasr\t%s, %s, #31\n", reglist[leftreg], reglist[leftreg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\trsb\t%s, %s, %s, asr #%d\n", reglist[leftreg], reglist[leftreg], reglist[rightreg], k); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } if(-255 <= value && value <= imm16){ sprintf(buf, "\tmov\t%s, #%d\n", reglist[rightreg], value); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(rightreg, value); } sprintf(buf, "\tmls\t%s, %s, %s, %s\n", reglist[leftreg], reglist[rightreg], reglist[leftreg], reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } free_register(reg); free_register(rightreg); return leftreg; } }else{ return (ARM_mod(leftreg, rightreg)); } } case A_EQ: case A_NE: case A_LT: case A_GT: case A_LE: case A_GE: if(parentASTop == A_EQ || parentASTop == A_NE || parentASTop == A_LT || parentASTop == A_GT || parentASTop == A_LE || parentASTop == A_GE) { return ARM_compare_and_set(n->op, leftreg, rightreg); } else { return (ARM_cmp_jmp(n->op, leftreg, rightreg, label, parentASTop)); } case A_INTLIT: return (ARM_loadint(n->v.intvalue)); case A_IDENT: if (n->rvalue) { int r; if (Symtable[n->v.id].ctype == C_GLOBAL) { r = ARM_loadglob(n->v.id); } else if(Symtable[n->v.id].ctype == C_LOCAL){ r = ARM_loadlocal(n->v.id); }else{ r = ARM_loadparam(n->v.id); } return r; } else return (NOREG); case A_ASSIGN: switch (n->right->op) { case A_IDENT: if (Symtable[n->right->v.id].ctype == C_GLOBAL){ return (ARM_str_glob(leftreg, n->right->v.id)); }else if(Symtable[n->right->v.id].ctype == C_LOCAL){ return (ARM_str_local(leftreg, n->right->v.id)); }else{ return (ARM_str_param(leftreg, n->right->v.id)); } case A_ADDR: return (ARM_str_array(leftreg, rightreg, n->right->v.id)); default: fatald("Can't A_ASSIGN in CodeGen(), op", n->op); } case A_RETURN: ARM_return(leftreg, Functionid); return (NOREG); case A_FUNCCALL: { if(nested_calls[nested_index].size() > 0 && !if_PerformanceTest){ int reg = alloc_register(); for(auto &x:nested_calls[nested_index]){ int address = x.first, ri = x.second; if(ri < 4){ int off = abs(address); int reg1 = alloc_register(); if(off <= imm8){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg1); sprintf(buf, "\tmov\tr%d, %s\n", ri, reglist[reg]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ int off = abs(address); int reg1 = alloc_register(); if(off <= imm8){ sprintf(buf, "\tldr\t%s, [fp, #%d]\n", reglist[reg], address); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, off); sprintf(buf, "\tsub\t%s, fp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tldr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } off = (ri-4)*4; if(off <= imm8){ sprintf(buf, "\tstr\t%s, [sp, #%d]\n", reglist[reg], off); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } }else{ set_int_offset(reg1, off); sprintf(buf, "\tadd\t%s, sp, %s\n", reglist[reg1], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } sprintf(buf, "\tstr\t%s, [%s]\n", reglist[reg], reglist[reg1]); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } } free_register(reg1); } } free_register(reg); nested_calls[nested_index].clear(); } --nested_index; if(Symtable[n->v.id].name == "putf"){ sprintf(buf, "\tbl\tprintf\n"); ObjectCode.emplace_back(buf);ldr_Byte += (strlen(buf) + OF); if(ldr_Byte >= L_field){ new_field(); } return (NOREG); }else{ int r = ARM_funccall(leftreg, n->v.id); return r; } } case A_BREAK: ARM_jump(loopendlabel); return (NOREG); case A_CONTINUE: ARM_jump(looptoplabel); return (NOREG); case A_RSB: return ARM_rsb(leftreg); case A_LOGNOT: return (ARM_lognot(leftreg, label, parentASTop)); default: exit(17); fatald("Unknown AST operator", n->op); } return (NOREG); } void genpreamble() { ARM_preamble(); } void genfreeregs() { freeall_registers(); } void genglobsym(int id, int num) { ARM_globsym(id, num); } void genglobsym_plus(int id, vector<int> &x) { ARM_globsym_plus(id, x); } void match(int t, string what) { if (token_stream[token_index].token == t) { ++token_index; } else { exit(1); fprintf(stderr, "This is %d\n", token_stream[token_index].token); fatals("Expected", what); } } void semi(void) { match(T_SEMI, ";"); } void lbrace(void) { match(T_LB, "{"); Locls_save.push(Locls); } void rbrace(void) { match(T_RB, "}"); Locls = Locls_save.top(); Locls_save.pop(); } void lparen(void) { match(T_LP, "("); } void rparen(void) { match(T_RP, ")"); } void ident(void) { nowname = token_stream[token_index].strvalue; match(T_IDENT, "identifier"); } void fatal(string s) { fprintf(stderr, "%s on line %d\n", s.c_str(), token_stream[token_index].line); exit(18); } void fatals(string s1, string s2) { fprintf(stderr, "%s:%s on line %d\n", s1.c_str(), s2.c_str(), token_stream[token_index].line); exit(19); } void fatald(string s, int d) { fprintf(stderr, "%s:%d on line %d\n", s.c_str(), d, token_stream[token_index].line); exit(20); } void fatalc(string s, int c) { fprintf(stderr, "%s:%c on line %d\n", s.c_str(), c, token_stream[token_index].line); exit(21); } static int chrpos(char *s, int c) { char *p; p = strchr(s, c); return (p ? p - s : -1); } static int next(void) { if (Putback) { Inchar = Putback; Putback = 0; return Inchar; } Inchar = fgetc(Infile); if ('\n' == Inchar) Line++; return Inchar; } static void putback(int c) { Putback = c; } static int skip(void) { Inchar = next(); while (isspace(Inchar)) { Inchar = next(); } return (Inchar); } static int get_an_escape(void) { Inchar = next(); if (Inchar == '\\') { return '\\'; } if (Inchar == 'n') { return '\n'; } if (Inchar == 't') { return '\t'; } if (Inchar == 'b') { return '\b'; } return 0; } static int iskeyword() { int i = 0; while (strcmp(keywords[i].name, "")) { if (!strcmp(keywords[i].name, Text)) { return keywords[i].id; } ++i; } return 0; } static int scan_alpha() { int i = 0, num; while (isalpha(Inchar) || isdigit(Inchar) || Inchar == '_') { Text[i++] = Inchar; Inchar = next(); } putback(Inchar); Text[i] = '\0'; num = iskeyword(); if (num == 0) { return T_IDENT; } else { return num; } } static int getdight(char c){ if(isdigit(c)){ return c - '0'; }else{ if('a' <= c && c <= 'z'){ return (c-97)+10; }else{ return (c-65)+10; } } } static int scan_digit() { int val = 0; if (Inchar != '0') //Decimal { int k; while ((k = chrpos((char*)"0123456789", Inchar)) >= 0) { val = val * 10 + k; Inchar = next(); } } else { Inchar = next(); if (Inchar == 'x' || Inchar == 'X') //Hexadecimal { Inchar = next(); while (isxdigit(Inchar)) { val = val * 16 + getdight(Inchar); Inchar = next(); } } else if (Inchar == 'b' || Inchar == 'B') //Binary { Inchar = next(); while (Inchar >= '0' && Inchar <= '1') { val = val * 2 + getdight(Inchar); Inchar = next(); } } else //Octal { while (Inchar >= '0' && Inchar <= '7') { val = val * 8 + getdight(Inchar); Inchar = next(); } } } putback(Inchar); return val; } static int scan_text() { int index = 0; Inchar = next(); while (Inchar != '"' && Inchar != EOF) { if (Inchar == '\\') { Text[index] = get_an_escape(); } else { Text[index] = Inchar; } Inchar = next(); index++; } if (Inchar == EOF) { printf("lex error: \" expected\n"); exit(22); } Text[index] = 0; return T_STRCONST; } int scan(token *t) { Inchar = skip(); if(Inchar == EOF) { t->token = T_EOF; return (0); } else if (isalpha(Inchar) || Inchar == '_') { t->token = scan_alpha(); } else if (isdigit(Inchar)) { t->token = T_INTCONST; t->intvalue = scan_digit(); } else if (Inchar == '"') { t->token = scan_text(); } else if (Inchar == '=') { Inchar = next(); if(Inchar == '='){ t->token = T_EQ; }else{ t->token = T_ASSIGN; putback(Inchar); } } else if (Inchar == '!') { Inchar = next(); if(Inchar == '='){ t->token = T_NE; }else{ t->token = T_LOGNOT; putback(Inchar); } } else if (Inchar == '>') { Inchar = next(); if(Inchar == '='){ t->token = T_GE; }else{ t->token = T_GT; putback(Inchar); } } else if (Inchar == '<') { Inchar = next(); if(Inchar == '='){ t->token = T_LE; }else{ t->token = T_LT; putback(Inchar); } } else if (Inchar == '&') { Inchar = next(); t->token = T_LOGAND; } else if (Inchar == '|') { Inchar = next(); t->token = T_LOGOR; } else if (Inchar == '/') { Inchar = next(); if(Inchar == '/'){ t->token = T_NOTE; while(Inchar != EOF){ Inchar = next(); if(Inchar == '\n'){ break; } } }else if(Inchar == '*'){ t->token = T_NOTE; while(Inchar != EOF){ Inchar = next(); if(Inchar == '*'){ Inchar = next(); if(Inchar == '/') break; } } }else{ t->token = T_SLASH; putback(Inchar); } } else { switch (Inchar) { case '+': t->token = T_PLUS; break; case '-': t->token = T_MINUS; break; case '*': t->token = T_STAR; break; case '%': t->token = T_PER; break; case '(': t->token = T_LP; break; case ')': t->token = T_RP; break; case '[': t->token = T_LBK; break; case ']': t->token = T_RBK; break; case '{': t->token = T_LB; break; case '}': t->token = T_RB; break; case ',': t->token = T_COMMA; break; case ';': t->token = T_SEMI; break; default: printf("Unrecognised character %c on line %d\n", Inchar, Line); exit(23); } } return (1); } static void Scanner() { struct token T; while (scan(&T)) { if (T.token == T_INTCONST){ token_stream.push_back({T.token, T.intvalue, "", Line}); }else if(T.token == T_IDENT || T.token == T_STRCONST){ token_stream.push_back({T.token, 0, Text, Line}); }else if(T.token != T_NOTE){ token_stream.push_back({T.token, 0, "", Line}); } } } int findglob(string s) { int i; for (i = 0; i < Globs; i++) { if (s == Symtable[i].name) return (i); } return (-1); } static int newglob(void) { int p; if ((p = Globs++) >= Locls){ exit(25); fatal("Too many global symbols"); } return (p); } int findlocl(string s) { int i; for (i = Locls + 1; i < NSYMBOLS; i++) { if (s == Symtable[i].name) return (i); } return (-1); } static int newlocl(void) { int p; if ((p = Locls--) <= Globs){ exit(24); fatal("Too many local symbols"); } return (p); } void freeloclsyms(void) { Locls = NSYMBOLS - 1; } static void updatesym(int slot, string name, int type, int stype, int ctype, int endlabel, int size, int posn) { if (slot < 0 || slot >= NSYMBOLS){ exit(23); fatal("Invalid symbol slot number in updatesym()"); } Symtable[slot].name = name; Symtable[slot].type = type; Symtable[slot].stype = stype; Symtable[slot].ctype = ctype; Symtable[slot].endlabel = endlabel; Symtable[slot].size = size; Symtable[slot].posn = posn; Symtable[slot].intvalue = INF; Symtable[slot].paramnum = 0; Symtable[slot].Dimens.clear(); Symtable[slot].conNum.clear(); } int addglob(string name, int type, int stype, int endlabel, int size) { int slot; slot = newglob(); updatesym(slot, name, type, stype, C_GLOBAL, endlabel, size, 0); ldr_Byte += (8 + name.size()); return (slot); } int addlocl(string name, int type, int stype, int isparam, int size) { int localslot, globalslot; localslot = newlocl(); if (isparam) { updatesym(localslot, name, type, stype, C_PARAM, 0, size, 0); } else { updatesym(localslot, name, type, stype, C_LOCAL, 0, size, 0); } return (localslot); } int findsymbol(string s) { int slot; slot = findlocl(s); if (slot == -1) slot = findglob(s); return (slot); } ASTnode *newASTnode(int op, int type, ASTnode *left, ASTnode *mid, ASTnode *right, int intvalue) { ASTnode *n = new ASTnode; n->op = op; n->type = type; n->left = left; n->mid = mid; n->right = right; n->next = NULL; n->istop = false; n->Dimension_num = 0; n->v.intvalue = intvalue; n->strvalue = ""; return (n); } ASTnode *newASTleaf(int op, int type, int intvalue) { return (newASTnode(op, type, NULL, NULL, NULL, intvalue)); } ASTnode *newASTunary(int op, int type, ASTnode *left, int intvalue) { return (newASTnode(op, type, left, NULL, NULL, intvalue)); } static void init() { Line = 1; Putback = '\n'; Globs = 0; Locls = NSYMBOLS - 1; Local_v = 0; func_v = 0; max_param = 0; Looplevel = 0; token_index = 0; con = false; last_or = false; last_and = false; pars = 0; func_field = -1; ldr_Byte = 0; true_L = -1; while_level = 0; max_alloc = 0; } int genlabel(void) { static int id = 1; return (id++); } int genLC(void) { static int lc = 1; return (lc++); } int main(int argc, char *argv[]) { if(argc == 6){ if_PerformanceTest = true; } init(); // Open up the input file Infile = fopen(argv[4], "r"); // Create the output file Outfile = fopen(argv[3], "w"); // 添加宏定义 addglob("getint", P_INT, S_FUNCTION, 0, 0); addglob("getch", P_INT, S_FUNCTION, 0, 0); addglob("getarray", P_INT, S_FUNCTION, 0, 0); addglob("putint", P_VOID, S_FUNCTION, 0, 0); addglob("putch", P_VOID, S_FUNCTION, 0, 0); addglob("putarray", P_VOID, S_FUNCTION, 0, 0); addglob("before_main", P_VOID, S_FUNCTION, 0, 0); addglob("after_main", P_VOID, S_FUNCTION, 0, 0); addglob("_sysy_starttime", P_VOID, S_FUNCTION, 0, 0); addglob("_sysy_stoptime", P_VOID, S_FUNCTION, 0, 0); addglob("starttime", P_VOID, S_FUNCTION, 0, 0); addglob("stoptime", P_VOID, S_FUNCTION, 0, 0); addglob("putf", P_VOID, S_FUNCTION, 0, 0); Scanner(); token_size = token_stream.size(); genpreamble(); CompUnit(); for(string &x : ObjectCode){ fprintf(Outfile, "%s", x.c_str()); } fclose(Outfile); return 0; } <file_sep>/README.md # CSC2021-HDU-WeaverGirlsDescendToWorld 2021 年全国大学生计算机系统能力大赛编译系统设计赛项目<br> 队伍学校:杭州电子科技大学<br> 队伍名称:织女下凡<br> 队伍成员:吴璋达、郭佳毅 ## Compiler架构 这是一个 SysY 语言 ( 简化的 C 语言 ) 的编译器, 目标平台是树莓派 ( ARMv7 ) ( 32bit )<br> Scanner → Parser → CodeGen<br> 0层IR, 共3895行; 三步到位, 极致的简洁, 飞一般的感觉 ## 要你命三板斧性能优化系统 1.编译期可以求值的表达式直接用常量替代<br> 2.除法和取模优化 ( 针对除数为2的幂次方、常量、变量三种情况有不同的处理方式 )<br> 3.目标代码层面使用沃兹基发明的ScanAndReplace ( SAR ) 寄存器分配算法 ## 输入与输出 输入文件地址通过Infile传入, 输出文件地址通过Outfile传入 <file_sep>/语言定义与运行时库/README.md # 运行时库 `libsysy.a`: arm架构的SysY运行时静态库 `libsysy.so`: arm架构的SysY运行时动态库 `sylib.h`: SysY运行时库头文件 `sylib.c`: SysY运行时库源文件
2782e39c55adb4c462d959f2e3e1df877f2496a5
[ "Markdown", "C", "C++" ]
4
C
MortarGOD/LegendCompiler
9d9f69c95a07dfd6eae5bf8ffbfc89f2377c4bd7
b6db4a62a93f43e91066b086584f3f5d05291c7e
refs/heads/master
<repo_name>bettinson/todo.app<file_sep>/Todo/Todo.swift // // Todo.swift // Todo // // Created by <NAME> on 2016-06-03. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation class Todo : NSObject, NSCoding { var name : String var done : Bool init(name: String) { self.name = name self.done = false } required init(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("name") as! String done = aDecoder.decodeObjectForKey("done") as! Bool super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(done, forKey: "done") } }<file_sep>/Todo/TodoStore.swift // // TodoStore.swift // Todo // // Created by <NAME> on 2016-06-03. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation class TodoStore { var allTodos: [Todo] = [] let todoArchiveURL: NSURL = { let documentDirectories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let documentDirectory = documentDirectories.first! return documentDirectory.URLByAppendingPathComponent("todos.archive") }() init () { if let archivedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(todoArchiveURL.path!) as? [Todo] { allTodos += archivedItems } } func moveTodoAtIndex(fromIndex: Int, toIndex: Int) { if fromIndex == toIndex { return } let movedTodo = allTodos[fromIndex] allTodos.removeAtIndex(fromIndex) allTodos.insert(movedTodo, atIndex: toIndex) } func changeTodo (todo: Todo, index: Int) { allTodos[index] = todo } func addTodo (todo: Todo) { allTodos.append(todo) } func removeTodo(todo: Todo) { print ("removing item") if let index = allTodos.indexOf(todo) { allTodos.removeAtIndex(index) } } func saveChanges() -> Bool { print("Saving items to \(todoArchiveURL.path!)") return NSKeyedArchiver.archiveRootObject(allTodos, toFile: todoArchiveURL.path!) } }<file_sep>/README.md # Todo.app ![Todo](http://i.imgur.com/cDT3fWo.png "Todo") This is my minimal todo app. You can add todos, clear them, edit them inline, and check them off. ## Things I learned - Delegates - Writing my own protocol - How to use a model to supply data to a view controller - UI code - Creating custom cells - Segues - Saving to the local file system - How to shut up and actually _make_ something instead of just reading books <file_sep>/Todo/AddTodoViewController.swift // // AddTodoViewController.swift // Todo // // Created by <NAME> on 2016-06-03. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class AddTodoViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate { var todoStore : TodoStore! @IBOutlet weak var nameTextField: UITextField! @IBAction func done(sender: AnyObject) { finishAdding() } @IBAction func cancel(sender: AnyObject) { nameTextField.resignFirstResponder() self.dismissViewControllerAnimated(true, completion: {}) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor() navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() self.setNeedsStatusBarAppearanceUpdate() navigationController?.navigationBar.translucent = true navigationController?.navigationBar.barStyle = UIBarStyle.Black navigationController?.navigationBar.barTintColor = Colours.greenColourHighlight navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationController?.setNavigationBarHidden(false, animated: true) nameTextField.becomeFirstResponder() } func textFieldDidEndEditing(textField: UITextField) { textField.resignFirstResponder() } func finishAdding() { if (nameTextField.text) == "" { let title = "You can't have a blank todo" let message = "Please add some text." let ac = UIAlertController(title: title, message: message, preferredStyle: .Alert) let okayAction = UIAlertAction(title: "Okay", style: .Cancel, handler: nil) ac.addAction(okayAction) presentViewController(ac, animated: true, completion: nil) } else { let todo = Todo(name: nameTextField.text!) todoStore.addTodo(todo) nameTextField.resignFirstResponder() self.dismissViewControllerAnimated(true, completion: {}) } } func textFieldShouldReturn(textField: UITextField) -> Bool { finishAdding() return true } } <file_sep>/TodosViewController.swift // // TodosViewController.swift // Todo // // Created by <NAME> on 2016-06-03. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class TodosViewController : UITableViewController, UITextFieldDelegate, TodoCellDelegate { var todoStore = TodoStore() private var currentTodo : Todo? private var currentIndex : Int? private var isEditing = false override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) navigationItem.leftBarButtonItem = editButtonItem() } override func viewDidLoad() { super.viewDidLoad() self.setNeedsStatusBarAppearanceUpdate() navigationController?.navigationBar.translucent = true navigationController?.navigationBar.barTintColor = Colours.greenColourHighlight navigationController?.navigationBar.tintColor = UIColor.whiteColor() navigationController?.view.backgroundColor = UIColor.clearColor() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoStore.allTodos.count } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "AddTodo" { let nav = segue.destinationViewController as! UINavigationController let addTodoViewController = nav.topViewController as! AddTodoViewController addTodoViewController.todoStore = todoStore } } func didFinishEditing(sender: TodoCellDelegate, cell: TodoCell) { let newTodo = Todo(name: cell.nameField.text!) todoStore.changeTodo(newTodo, index: currentIndex!) isEditing = false tableView.reloadData() } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let todo = todoStore.allTodos[indexPath.row] let done = UITableViewRowAction(style: .Destructive, title: "Done", handler: { (action, indexPath) in self.tableView.beginUpdates() self.todoStore.removeTodo(todo) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left) self.tableView.endUpdates() //Delete item }) done.backgroundColor = Colours.greenColour return [done] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TodoCell", forIndexPath: indexPath) as! TodoCell cell.updateLabels() let todo = todoStore.allTodos[indexPath.row] cell.userInteractionEnabled = true cell.nameField.text = todo.name cell.todoDelegate = self cell.nameField.userInteractionEnabled = false return cell } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { todoStore.moveTodoAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if isEditing == false { let cell = tableView.cellForRowAtIndexPath(indexPath) as! TodoCell let todo = todoStore.allTodos[indexPath.row] currentTodo = todo cell.nameField.text = todo.name cell.nameField.userInteractionEnabled = true cell.currentTodo = todo currentIndex = indexPath.row isEditing = true cell.becomeFirstResponder() } } }<file_sep>/Todo/TodoCell.swift // // TodoCell.swift // Todo // // Created by <NAME> on 2016-06-03. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit protocol TodoCellDelegate: class { func didFinishEditing(sender: TodoCellDelegate, cell: TodoCell) } class TodoCell: UITableViewCell, UITextFieldDelegate { var currentTodo : Todo! weak var todoDelegate:TodoCellDelegate? weak var delegate:UITextFieldDelegate? // @IBAction func tappedNameField(sender: AnyObject) { // print("Tapped text field") // // nameField.userInteractionEnabled = true // nameField.becomeFirstResponder() // } @IBOutlet weak var nameField: UITextField! func updateLabels() { let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) nameField.font = bodyFont } override func becomeFirstResponder() -> Bool { nameField.userInteractionEnabled = true nameField.delegate = self nameField.becomeFirstResponder() return true } func textFieldShouldReturn(textField: UITextField) -> Bool { print (currentTodo.name) textField.resignFirstResponder() return true } func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true } func textFieldDidBeginEditing(textField: UITextField) { } func textFieldDidEndEditing(textField: UITextField) { textField.resignFirstResponder() todoDelegate?.didFinishEditing(self.todoDelegate!,cell: self) // currentTodo = nil } } <file_sep>/Todo/Colours.swift // // Colours.swift // Todo // // Created by <NAME> on 2016-06-09. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import UIKit public struct Colours { static let greenColour = UIColor(colorLiteralRed: 6/255, green: 180/255, blue: 110/255, alpha: 1) static let greenColourHighlight = greenColour }
7a4330900c7f75475b8d8cba302d3d8582b3e9a2
[ "Swift", "Markdown" ]
7
Swift
bettinson/todo.app
8b3b7067681d625eb4ee2edf49f04ad83a501b2b
867c030bb191f9326ceb4609f4646c019692ee34
refs/heads/master
<repo_name>Rutba27/Detecting-HCC<file_sep>/HCC_code.R #*********************************************************************************# #********************* Machine Learning *****************************# #********************* by <NAME> ********************************# #*********************************************************************************# #*********************loading data****************************** #setting the work directory and loading the data into a dataframe from the csv file #As seen in the csv file, there is some missing data denoted by ? which is read as NA while #loading the csv file setwd("C:/Users/reply/Rcode") data1 <-read.csv("HCC_Survival.csv",header = TRUE,na.strings = c("?")) head(data1) # we can check the file and observe that ? issue solved #*************** Data visualization *************************** library(ggplot2) #plotting graphs accordig to the basic understanding that smoking,age,gender etc can effect # the HCC occurence. it does not specify any correlation #Gender count1 <- table(data1$Gender,data1$Class..1.Year.Survival.) barplot(count1,main = "Survival w.r.t Gender",col=c("pink","light blue"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,4), legend= c("Female","Male")) plot.new() #Symptom count2 <- table(data1$Symptoms,data1$Class..1.Year.Survival.) barplot(count2,main = "Survival w.r.t Symptoms",col=c("yellow","light green"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,5), legend=c("Symptom-No","Symptom-Yes")) #Alcohol count3 <- table(data1$Alcohol,data1$Class..1.Year.Survival.) barplot(count3,main = "Survival w.r.t Alcohol",col=c("aquamarine","chocolate"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,5), legend=c("Alcohol-No","Alcohol-Yes")) #Endemic Countries count4 <- table(data1$Endemic.Countries,data1$Class..1.Year.Survival.) barplot(count4,main = "Survival w.r.t Endemic Countries",col=c("cyan","pink"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,5), legend=c("Ende.Cntry - No","Ende.Cntry - Yes")) #Smoking count5<- table(data1$Smoking,data1$Class..1.Year.Survival.) barplot(count5,main = "Survival w.r.t Smoking",col=c("#CCFF66","#FF3399"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,5), legend=c("Smoking - No","Smoking - Yes")) #Diabetes count6<- table(data1$Diabetes,data1$Class..1.Year.Survival.) barplot(count6,main = "Survival w.r.t Diabetes",col=c("#CC00FF","#66CC66"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,5), legend=c("Diabetes - No","Diabetes - Yes")) #Obesity count7<- table(data1$Obesity,data1$Class..1.Year.Survival.) barplot(count7,main = "Survival w.r.t Obesity",col=c("#FFCCFF","#FF33FF"), ylab = "No.of Customers",xlab = "Survival",xlim=c(0,5), legend=c("Obesity - No","Obesity - Yes")) #Age at diagnosis Survived<- factor(data1$Class..1.Year.Survival.) ggplot(data1,aes(x=Survived, y=Age.at.diagnosis,fill=Survived)) + geom_boxplot(colour=c("#CC99CC","#3300FF"),outlier.color = "red")+ ggtitle("Survival w.r.t Age at Diagnosis") mean = mean(data1$Age.at.diagnosis, na.rm = T) var = var(data1$Age.at.diagnosis, na.rm = T) sd = sd(data1$Age.at.diagnosis, na.rm = T) hist(data1$Age.at.diagnosis, col = "#3399FF", border="white",freq = FALSE,main=NULL) curve(dnorm(x, mean = mean, sd = sd), add = T,col = "red", lwd = 1) #Grams per Day ggplot(data1,aes(x=Survived, y=Grams...day,fill=Survived)) + geom_boxplot(colour=c("#CC99CC","#3300FF"),outlier.color = "red")+ ggtitle("Survival w.r.t Grams per Day") mean = mean(data1$Grams...day, na.rm = T) var = var(data1$Grams...day, na.rm = T) sd = sd(data1$Grams...day, na.rm = T) hist(data1$Grams...day, col = "#3399FF", border="white",freq = FALSE,main=NULL) curve(dnorm(x, mean = mean, sd = sd), add = T,col = "red", lwd = 1) #Packs per Year ggplot(data1,aes(x=Survived, y=Packs...year,fill=Survived)) + geom_boxplot(colour=c("#CC99CC","#3300FF"),outlier.color = "red")+ ggtitle("Survival w.r.t Packs per Year") mean = mean(data1$Packs...year, na.rm = T) var = var(data1$Packs...year, na.rm = T) sd = sd(data1$Packs...year, na.rm = T) hist(data1$Packs...year, col = "#3399FF", border="white",freq = FALSE, main=NULL,xlim = c(0,150)) curve(dnorm(x, mean = mean, sd = sd), add = T,col = "red", lwd = 1) #*************** Data Exploration *************************** #Check the data types of the variables str(data1) data1$Gender<-as.factor(data1$Gender) data1$Symptoms<-as.factor(data1$Symptoms) data1$Alcohol<-as.factor(data1$Alcohol) data1$HBsAg<-as.factor(data1$HBsAg) data1$HBeAg<-as.factor(data1$HBeAg) data1$HBcAb<-as.factor(data1$HBcAb) data1$HBVAb<-as.factor(data1$HBVAb) data1$Cirrhosis<-as.factor(data1$Cirrhosis) data1$Endemic.Countries<-as.factor(data1$Endemic.Countries) data1$Smoking<-as.factor(data1$Smoking) data1$Diabetes<-as.factor(data1$Diabetes) data1$Obesity<-as.factor(data1$Obesity) data1$Hemochromatosis<-as.factor(data1$Hemochromatosis) data1$AHT<-as.factor(data1$AHT) data1$CRI<-as.factor(data1$CRI) data1$HIV<-as.factor(data1$HIV) data1$NASH<-as.factor(data1$NASH) data1$Esophageal.varices<-as.factor(data1$Esophageal.varices) data1$Splenomegaly<-as.factor(data1$Splenomegaly) data1$Portal.hypertension<-as.factor(data1$Portal.hypertension) data1$Portal.vein.thrombosis<-as.factor(data1$Portal.vein.thrombosis) data1$Liver.metastasis<-as.factor(data1$Liver.metastasis) data1$Radiological.hallmark<-as.factor(data1$Radiological.hallmark) data1$Class..1.Year.Survival.<- as.factor(data1$Class..1.Year.Survival.) data1$Age.at.diagnosis<-as.numeric(data1$Age.at.diagnosis) data1$Grams...day<-as.numeric(data1$Grams...day) data1$Performance.status<-as.numeric(data1$Performance.status) data1$Encefalopathy <-as.numeric(data1$Encefalopathy ) data1$Ascites<-as.numeric(data1$Ascites) data1$ALT<-as.numeric(data1$ALT) data1$AST<-as.numeric(data1$AST) data1$Number.of.nodules<-as.numeric(data1$Number.of.nodules) #summarize data summary(data1) #according to data summary,there seem to be lot of missing data hence we would first check for #missing data #visualizing missing data library(VIM) mice_plot <- aggr(data1, col=c('blue','yellow'), numbers = TRUE, sortVars = TRUE, labels=names(data1), cex.axis=.4, gap=1) #missing data count miss_data = colSums(is.na(data1)) miss_data #*************** Data Preprocessing *************************** #Imputing Missing values #imputing missing values by KNN, this method is taken for imputation inorder to find the missing #value by comparing values near to this. KNN is a known method for imputing values in medical stream predictions a<- kNN(data1[,-50],k=5) summary(a) #creating complete data (original data plus imputed data) data2<- a[,c(1:49)] data2$Survival = data1$Class..1.Year.Survival. #check if values have been imputed miss_data = colSums(is.na(data2)) miss_data #Scaling the data # As seen some attributes like AFP,Leukocytes have large range of values hence we need to scalr the data #inorder to get relative values. Since data has both binary as well as continuous data, we would be #performing scaling on numeric and integer data and leaving the binary as it is for (colName in names(data2)) { # Check if the column contains numeric data. if(class(data2[,colName]) == 'integer' | class(data2[,colName]) == 'numeric') { # Scale this column (scale() function applies z-scaling). data2[,colName] = scale(data2[,colName]) } } #************** adding code for PCA ***************************** #install.packages("stats") library(stats) #filtering numeric and integer data data3 <- Filter(is.numeric,data2) sample_pca <- prcomp(data3, center = TRUE, scale = TRUE) summary(sample_pca) #**************Creating machine learning model and testing the model********************* #Creating training and testing data library(caTools) set.seed(11) #creating split split1<- sample.split(data2,SplitRatio = .70) #training set train <- subset(data2,split1==TRUE) head(train) #testing set test <- subset(data2,split1==FALSE) head(test) #As the target variable is binomial we can use SVM technique for modelling #creating classifier #install.packages("e1071") library(e1071) classifier_svm = svm(formula = Survival ~ ., data = train, type = 'C-classification', kernel = 'linear') # Predicting the test set results using svm -linear test_data_svm = predict(classifier_svm, newdata = test[-50]) #creating Confusion Matrix for svm -linear conf_matrix_svm = table(test[,50], test_data_svm) conf_matrix_svm #Accuracy for SVM -linear accuracy_svm<-(sum(diag(conf_matrix_svm)))/sum(conf_matrix_svm) accuracy_svm #rounding to 3 digits accuracy_svm <- round(accuracy_svm,3) accuracy_svm #Creating model using SVM- Radial basis function classifier_svmR = svm(formula = Survival ~ ., data = train, type = 'C-classification', kernel = 'radial') # Predicting the test set results for radial basis function on SVM test_data_svmR = predict(classifier_svmR, newdata = test[-50]) #Making the confusion Matrix for SVM radial basis conf_matrix_svmR = table(test[,50], test_data_svmR) conf_matrix_svmR #Accuracy of svm radial basis accuracy_svmR<-(sum(diag(conf_matrix_svmR)))/sum(conf_matrix_svmR) accuracy_svmR #rounding to 3 digits accuracy_svmR <- round(accuracy_svmR,3) accuracy_svmR #Using KNN (K nearest neighbour) for creating the model. For an optimum result, #for predicting the result, we would be comparing it with 15 close points library(class) test_knn <- knn(train = train[,-50], test = test[,-50], cl = train[,50], k=15) test_knn #Making the confusion Matrix for knn conf_matrix_knn = table(test[,50],test_knn ) conf_matrix_knn #Accuracy for knn accuracy_knn<-(sum(diag(conf_matrix_knn)))/sum(conf_matrix_knn) accuracy_knn #rounding to 3 digits accuracy_knn <- round(accuracy_knn,3) accuracy_knn
e127644c203269b6a3a91e3c5a928e311e3b288c
[ "R" ]
1
R
Rutba27/Detecting-HCC
ebe980d39cf92a9f01bc1aba421e8651cd472bf6
a45cdf387ff12352371bd8290d85a36e1ef6b7c9
refs/heads/master
<file_sep>var config = { baseUrl: window.location.href + "api/user" }; var userMap = new Map(); var folderMap = new Map(); var sendFolder = new Map(); details(); listUsers().then(function () { listSrcTransfers(); listDstTransfers(); }); listDstFolder(); listSrcFolder(); function details() { $.ajax({ type: "GET", url: config.baseUrl + "/user/details", success: function (res) { if (res === "10001") { $("#menu").append("<button onclick='managerPanel()'>管理</button>") } } }) } // 我发送的 function listSrcTransfers() { $.ajax( { type: "GET", url: config.baseUrl + "/transfer/src", success: function (res) { setSrcTransfer(res); }, error: function (e) { errorHandler(e); } } ) } // 我接收的 function listDstTransfers() { $.ajax( { type: "GET", url: config.baseUrl + "/transfer/dst", success: function (res) { setDstTransfer(res); }, error: function (e) { errorHandler(e); } } ) } // 我发送的 function listSrcFolder() { $.ajax( { type: "GET", url: config.baseUrl + "/folder/src", success: function (res) { console.log(res); for (var i = 0; i < res.length; i ++) { var item = res[i]; var date = convertDate(item.createTime); $("#s-folder").append("<p style='border: solid 1px #000;' id='" + item.id + "'><a href='javascript:void(0);' onclick='folderDetails(\"" + item.id + "\", \"src\")'>" + item.name + " </a>&nbsp;&nbsp;" + item.comment + " &nbsp;&nbsp;" + date + " " + "<a href=\"javascript:void(0);\" onclick='folderUser(\"" + item.id + "\")'>U</a> <a href=\"javascript:void(0);\" onclick='delFolder(\"" + item.id + "\")'>D</a></p>"); folderMap.set(item.id, item.name); sendFolder.set(item.id, item.name); } }, error: function (e) { console.log(e); } } ) } // 我接收的 function listDstFolder() { $.ajax( { type: "GET", url: config.baseUrl + "/folder/dst", success: function (res) { console.log(res); for (var i = 0; i < res.length; i ++) { var item = res[i]; var date = convertDate(item.createTime); $("#r-folder").append("<p style='border: solid 1px #000;' id='" + item.id + "'><a href='javascript:void(0);' onclick='folderDetails(\"" + item.id + "\", \"dst\")'>" + item.name + "</a>&nbsp;&nbsp;" + item.comment + " &nbsp;&nbsp;" + date + " " + "</p>"); folderMap.set(item.id, item.name); } }, error: function (e) { console.log(e); } } ) } function listUsers() { return new Promise(function (resolve, reject) { $.ajax( { type: "GET", url: config.baseUrl + "/user", success: function (res) { console.log(res); for (var i = 0; i < res.length; i ++) { userMap.set(res[i].id, res[i].nick); } resolve(); setUserSelector(); }, error: function (e) { console.log(e); reject(); } } ) }); } function addTransfer() { var type = $("#type")[0].value; var target = $("#selector")[0].value; var file = $("#file")[0].files[0]; var fd = new FormData(); fd.append("type", type); fd.append("target", target); fd.append("file", file); $.ajax( { type: "POST", url: config.baseUrl + "/transfer", data: fd, processData: false, contentType: false, dataType: "text", success: function (res) { alert("发送成功"); window.location.reload(); }, error: function (e) { alert("发送失败"); console.log(e); } } ) } function addFolder() { var name = $("#create-name")[0].value; var comment = $("#create-comment")[0].value; var usernameElements = $("#username input"); var username = []; for (var i = 0; i < usernameElements.length; i ++) { if (usernameElements[i].checked) { username.push(usernameElements[i].value); } } var d = { "name" : name, "comment" : comment, "uid" : username }; $.ajax( { type: "POST", url: config.baseUrl + "/folder", data: JSON.stringify(d), processData: false, contentType: "application/json", dataType: "text", success: function (res) { alert("创建成功"); window.location.reload(); }, error: function (e) { alert("创建失败"); console.log(e); } } ) } function folderUser(id) { $.ajax({ type: "GET", url: config.baseUrl + "/user/folder?folderId=" + id, success: function (res) { $("#folder-user").text(""); res.forEach(function (item) { $("#folder-user").append("&nbsp;" + item.nick + " &nbsp;"); }) $("#folderPanel")[0].style.display = "block"; }, error: function (e) { errorHandler(e); } }); } function closeFolderUser() { $("#folderPanel")[0].style.display = "none"; } function delFolder(id) { $.ajax({ type: "DELETE", url: config.baseUrl + "/folder?id=" + id, dataType: "text", success: function (res) { alert("删除成功"); window.location.reload(); }, error: function (e) { errorHandler(e); } }); } function setDstTransfer(res) { console.log(res); $("#r-data p").remove(); for (var i = 0; i < res.length; i ++) { var item = res[i]; var size = convertSize(item.size); var date = convertDate(item.createTime); var username = userMap.get(item.uid); username = username === undefined ? " " : username; var folder; if (item.targetFolder == null || item.targetFolder === undefined) { folder = ""; } else { folder = folderMap.get(item.targetFolder); } $("#r-data").append("<p style='border: solid 1px #000;' id='" + item.id + "' onclick='download(\"" + item.id + "\")'><span style=\"border: solid 1px #000; font-weight: 600\">" + folder + "</span>&nbsp;&nbsp;&nbsp;" + username + " &nbsp;&nbsp;<a href='javascript:void(0);'>" + item.filename + "</a>&nbsp;&nbsp;" + item.extension + " &nbsp;&nbsp;" + size + " &nbsp;&nbsp;" + date + " " + "</p>"); } } function setSrcTransfer(res) { console.log(res); $("#s-data p").remove(); for (var i = 0; i < res.length; i ++) { var item = res[i]; var size = convertSize(item.size); var date = convertDate(item.createTime); var username = userMap.get(item.uid); username = username === undefined ? " " : username; var folder; if (item.targetFolder == null || item.targetFolder === undefined) { folder = ""; } else { folder = folderMap.get(item.targetFolder); } $("#s-data").append("<p style='border: solid 1px #000;' id='" + item.id + "' onclick='download(\"" + item.id + "\")'><span style=\"border: solid 1px #000; font-weight: 600\">" + folder + "</span>&nbsp;&nbsp;&nbsp;" + username + " &nbsp;&nbsp;<a href='javascript:void(0);'>" + item.filename + "</a>&nbsp;&nbsp;" + item.extension + " &nbsp;&nbsp;" + size + " &nbsp;&nbsp;" + date + " " + "</p>"); } } function errorHandler(e) { console.log(e); } function download(id) { window.location.href=config.baseUrl + "/transfer/download?id=" + id; } function folderDetails (id, type) { $.ajax( { type: "GET", url: config.baseUrl + "/transfer/folder?folderId=" + id, success: function (res) { if (type === "dst") { setDstTransfer(res); } else { setSrcTransfer(res); } }, error: function (e) { console.log(e); } } ) } function setSelector() { if ($("#type")[0].value === "FOLDER") { setFolderSelector(); } else { setUserSelector(); } } function setUserSelector() { $("#selector option").remove(); userMap.forEach(function (value, key) { $("#selector").append("<option value='" + key + "'>" + value + "</option>") }); } function setFolderSelector() { $("#selector option").remove(); sendFolder.forEach(function (value, key) { $("#selector").append("<option value='" + key + "'>" + value + "</option>") }); } function showCreateFolderPanel() { $("#createFolder")[0].style.display = "block"; $("#username").text(""); var i = 0; userMap.forEach(function (value, key) { if (i%6 === 0) { $("#username").append("<br>"); } $("#username").append("<input type=\"checkbox\" value=\"" + key + "\">" + value + "&nbsp;&nbsp;"); i++; }) } function cancelAndClose() { $("#createFolder")[0].style.display = "none"; } function passwordPanel() { $("#password")[0].style.display = "block"; } function closePassword() { $("#password")[0].style.display = "none"; } function updatePassword() { var fd = new FormData(); fd.append("opd", $("#opd")[0].value); fd.append("npd", $("#npd")[0].value); $.ajax( { type: "PUT", url: config.baseUrl + "/user", data: fd, processData: false, contentType: false, dataType: "text", success: function (res) { if (res === "success") { alert("修改成功"); window.location.reload(); }else { alert("修改失败"); } }, error: function (e) { alert("修改失败"); console.log(e); } } ) } function managerPanel() { $.ajax("/api/admin/period").success(function (res) { $("#period")[0].value = res; }); $("#admin")[0].style.display = "block"; } function closeManager() { $("#admin")[0].style.display = "none"; } function addUser() { var name = $("#name")[0].value; var nick = $("#nick")[0].value; var password = $("#pwd")[0].value; var d = { "username": name, "nick": nick, "password": <PASSWORD> }; $.ajax( { type: "POST", url: "/api/admin/user", data: JSON.stringify(d), processData: false, contentType: "application/json", dataType: "text", success: function (res) { alert("添加成功"); window.location.reload(); }, error: function (e) { alert("添加失败"); console.log(e); } } ) } function setPeriod() { $.ajax({ type:"PUT", url: "/api/admin/period?time=" + $("#period")[0].value, dataType: "text", success: function () { alert("设置成功"); window.location.reload(); }, error: function (e) { alert("设置失败"); console.log(e); } }) } function convertSize(size) { var dan = ["B", "KB", "MB", "G", "T"] var i = 0; while (size >= 1024) { size = size/1024; i ++; } return size.toFixed(3) + " " + dan[i]; } function convertDate(time) { var date = new Date(time); var mins = date.getMinutes(); if (mins < 10) { mins = "0" + mins; } return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + mins; }<file_sep>server.port=80 spring.datasource.url=jdbc:sqlite::resource:anzhi.sqlite spring.datasource.driver-class-name=org.sqlite.JDBC spring.servlet.multipart.max-file-size=4096MB spring.servlet.multipart.max-request-size=4096MB file.temp.location=c:\\anzhi\\transfer\\file\\<file_sep># Transfer 局域网文件传输助手 ### 使用说明(产品) 启动程序步骤: * 程序所在目录,双击 start.bat 启动程序 * (内网 80 端口不可被占用) * 本机浏览器可通过 http://localhost; http://127.0.0.1;访问 * 其他机器需要通过 服务器[程序所在的机器] 的内网IP 访问 * 推荐所有机器使用 http://file.anzhiyule.com 访问(需要网络,域名代理,只是方便查找服务器IP)。 * 关闭CMD会话窗口即可关闭程序 运行环境:windows xp/7/8/10 (解压后大小:121MB. 包含基本环境) [安知鱼乐](https://www.anzhiyule.com)
243521140661927e3bc37a6cc54f32365e28358a
[ "JavaScript", "Markdown", "INI" ]
3
JavaScript
Question7/transfer-product
047e9cb2f42a22f77d82921be8e6242f640d26fc
6176b16df6cb9da9eb3f38898bebf6c61f4f3b78
refs/heads/main
<repo_name>thesagarsutar/sagar.sutar.in<file_sep>/code/app/projects/nano-pico.html <!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta charset="utf-8"> <title>Nano-Pico &ndash; <NAME> </title> <meta name="description" content="Researcher and Designer in practice"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui"> <meta http-equiv="cleartype" content="on"> <meta name="msapplication-tap-highlight" content="no"> <link type="text/plain" rel="author" href="/humans.txt"> <link href="https://fonts.googleapis.com/css?family=Merriweather:300i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400,400i,700" rel="stylesheet"><!-- build:css ../css/beauty.min.css --> <link rel="stylesheet" href="../css/beauty.css"><!-- /build --> <script src="../js/vendor/modernizr-2.7.1.min.js"></script> <script> (function(d) { var config = { //- kitId: 'tcm8vgy', kitId: 'tey3fkw', scriptTimeout: 3000 }, h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+=" wf-loading";tk.src='//use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s) })(document); </script> </head> <body> <main> <div class="l-center-70p wrapper-for-float"> <header id="menu"><a id="home-link" href="/" class="nonstylized-link"><span><NAME></span></a> <nav> <ul> <li><a data-tab-index="0" href="../about">about</a></li> <li class="seperator-menu">/</li> <li><a data-tab-index="1" href="../files/sagar_sutar.pdf">resume</a></li> <li class="seperator-menu">/</li> <li><a data-tab-index="2" href="../archive">archive</a></li> </ul> </nav> </header> </div> <article class="l-center-50p portfolio-article detail-article"> <header> <h3 class="article-title">Nano-Pico</h3> <p class="subheading">Interactive Product Design </p> </header> <section> <div class="fluid-width-video-wrapper"> <video poster="../img/portfolio/nano-pico/poster.jpg" controls> <source src="../vdo/nano-pico.webm" type="video/webm"> </video> <p class="meta-info">Nano-Pico Concept Video </p> </div> </section> <section> <p> Nano-Pico attempts to promote natural habit of writing, along with that it powers the written thoughts with digital technology. This project uses a novel and cheaper technology to achieve this purpose without affecting experience of writing, which makes it unique from trending smartpens technologies. Smartphone app for nano­pico defines simple and intuitive interactions and gives a new language for note taking and task automation. </p> </section> <section> <h4>Concept</h4> <p>The experience of writing by a pen on a paper is always better than typing or touching on a screen. Increasing use of technology in daily life is enforcing us to divorce pen from paper. “Nano­-Pico” tries to bridge the gap between physical and digital medium without affecting the natural experience of writing, presenting your thoughts to the whole world. “Nano” is a digital device which also holds the papers. Once paper is attached with the nano, it starts to capture handwritten text with the help of “Pico - a small magnetic ring” attachable to any pen. Nano­Pico works together seamlessly for writing with natural interfaces like pen and paper. Nano­Pico is designed in various forms to blend into different context. This project demonstrates two applications of nano­pico - note taking and task automation. Pino - a smartphone application extends the capabilities of nano­pico, further providing various configuration choices to user. Simple and intuitive gestures defined by this application gives a new language for note­taking and task automation. Nano­-Pico not only promotes the writing but also encapsulates it with zeros and ones.</p> </section> <section> <h4>Prototype </h4> <figure class="multi-image-wrapper"> <ul class="inline-list"> <li><a href="../img/portfolio/nano-pico/hd/1.gif" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/1.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/2.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/2.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/3.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/3.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/4.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/4.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/5.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/5.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/6.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/6.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/7.png" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/7.png" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/8.png" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/8.png" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/9.png" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/9.png" class="grayscale"></a></li> <li><a href="../img/portfolio/nano-pico/hd/10.png" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/nano-pico/10.png" class="grayscale"></a></li> </ul> </figure> </section> <section> <h4>Smarphone Application Prototype</h4> <p>Nano-Pico Product communicate with its smartphone application called as Pino. </p> <div class="center-content"><a role="button" href="https://invis.io/JY70BU7HX#/151908774_Pino-01" class="button primary"><span>Pino Prototype </span></a></div> </section> <section> <h4>Credits</h4> <p class="subheading">Dr. <NAME>, <NAME>, <NAME>, <NAME></p> </section> </article> </main><!-- build:js ../js/interactions.min.js --> <script src="../js/interactions.js"></script><!-- /build --> </body> </html><file_sep>/checklist/launch_checklist.md ![image](http://f.cl.ly/items/1F0y2N1W3V1M1v2m2k1C/wdtuts-logo.png) #Website Launch Checklist At [FHOKE](http://www.fhoke.com) we’ve been through it all, from perfect launches to ones that have turned into complete nightmares! Through our experiences we’ve compiled a list, in no particular order, of a process we go through before we launch our sites. This won’t cover everything, but should give you a quick overview of what you could be doing or adding to your own checklist. *** ##Successful Launch After having invested a lot of time in a project, launch day will be in sight. Before you get there you’ll still have important issues that need addressing to achieve a successful launch, get these right and both you and your client will be happy. Remember, before you show anything to a client make sure the site matches the original spec, is pixel perfect to the designs you presented and fulfills their original brief. *** ##Content Get a small team together and go over the content of the site with a fine tooth comb - **make sure you get this right**. Good content is the cornerstone of a great site. - **Spelling**: Check and check again. Run a spell check. Better still, get others involved. You can never have enough people making sure copy is correct. Look out for grammatical errors as well as checking for widows or orphaned words in important paragraphs. - **Copy**: Make sure real copy is in place and all placeholder text is removed. There is nothing worse than seeing lorem ipsum in a mission statement. - **Contact Details**: It seems obvious but make sure these are correct. Without them how do you expect people to get in touch? Check phone numbers, check email addresses and test that these are working, make a call or send an email and check they are received. - **Copyright**: If you plan on using a date in the copyright info make sure it is set to automatically refresh from the time stamp on the server, and that the copyright owner is correct. - **Terms**: If you are providing a service or are involved in promotions then you will need terms available for visitors to read. If you are unsure as to how these should be written then consult a lawyer for best advice. Remember: *make these as clear as possible*. There is nothing worse than being baffled by legal jargon. - **Privacy**: If you use cookies, capture data, or distribute data, then you need a privacy policy. Keep these simple and be clear on what data you collect and provide details of how you can be contacted for further information. *** ##Functionality Does it work? This might seem an obvious question to ask, but above all else this is the most important part of a project. You might have everything else in place but if the site doesn't work correctly what’s the point in launching it? Minor bugs may appear when visitors use the site for the first time but making sure it works at near 100% will ensure a successful launch. - **Compatability**: Check the site works across all browsers and platforms. Specify at the beginning of a project to the client what platforms you will build and test to and stick to these. Use platforms such as [Responsivator](http://dfcb.github.com/Responsivator/) and [BrowserStack](http://www.browserstack.com/) to test sites quickly as well as on physical browsers and devices. - **Favicon**: Obvious, but this can be missed. Look at creating an iOS home screen icon too. - **Logo**: Does the logo link to the index page? - **404 Pages**: Check you have these in place, make sure they signpost ways for a user to get back into the site or direct them to pages of interest with relevant links. - **Redirects**: If you are redirecting pages use suitable 301 re-directs over 302. - **Forms**: Make sure they aren’t sending to spam mail boxes, or returning an error once submitted and include a thank you state once a form is submitted so a visitor knows it is sent. Above all else make sure the clients email address is specified when the site goes live. - **Links**: Do internal page links work? Do all external links work and do they open in a new tab if so intended? - **RSS Feeds**: Feeds can be useful. You don’t have to limit these to articles, you can have feeds for most pages for example new work or case studies added to a site. *** ##Standards &amp; Validation These two things should be considered throughout the design and build to make every users experience on your site as good as it can be. Points to consider: - **Accessibility**: It's easy to forget how inaccessible a webpage is for some users. Have you considered how assistive technologies [such as screenreaders](http://webdesign.tutsplus.com/articles/general/accessibility-whats-your-markup-saying-to-you/) will navigate your site? Have you implemented [WIA-ARIA](http://en.wikipedia.org/wiki/WAI-ARIA) roles and states, or at least considered the tab order of form controls? - **Contrast**: This follows on from our point about accessibility. Using the very latest monitors it’s easy to see subtle differences in color, be sure to test your site on multiple devices and laptops to make sure the design has clarity and text can be read with ease. - **Text Size**: Make text clear and easy to read, adjust line spacing and allow plenty of white space. Bigger, can mean better, when it comes to text on the web. - **Alt Tags**: Make sure all images have clear descriptive ALT tags for the visually impaired. Not only that but without them they can’t be found in search engines. - **Consistency**: Make sure common elements across the site are consistent to avoid confusing your users. Make buttons look like buttons, links look like links, and titles and text should be the consistent in size and color. - **Device Compatibility**: Consider how the website will be used across multiple devices, responsive or not your website should work for desktop and mobile web users. - **Validation**: Always aim for 100% validity. If your site fails to validate fully don’t get too upset, but be sure to understand any errors in order to to eliminate any unwanted issues. - **JavaScript**: Many people browsing the web have JavaScript turned off for security reasons. Make sure your site is fully functional and forms still perform server-side validation checks without it. - **Flash**: Yeah, we know, nobody uses Flash anymore right? If Flash has to be used, be sure to include an alternative backup image should Flash Player not be installed. *** ##Sitemaps Make sure you include sitemaps. These help search engines correctly index your website during the crawling process. - **HTML Sitemaps**: Although not as common practice as they were, this form of sitemap can have its benefits in helping visitors see a complete overview of the sites pages. Links for these are normally found in the footer of a site. - **XML Sitemaps**: These are only ever used by search engines such as Google, Bing and Yahoo. Create an [XML Sitemap](http://webdesign.tutsplus.com/articles/general/all-you-need-to-know-about-xml-sitemaps/) easily and submit it via Webmaster Tools. These will then be used to inform search engines about the pages you have published. *** ##Performance A faster site is a better ranking site. You’ll also lower bounce rates on pages if you can reduce load times - who wants to wait for pages to load? - **Check site speed**: You can use services such as [Google Page Speed](https://developers.google.com/speed/pagespeed/) or [Blame Stella](https://www.blamestella.com/) to check the load times of your site's pages. - **Image sizes**: Keep your images as small as possible. Although network speeds are better than ever, no one wants to wait for a 10Mb page to load. Compressing images will only improve page load times. *** ##SEO Great SEO will mean your site will work harder and achieve greater success than a site that uses little or bad techniques. Get your research right and the rest will fall into place. This list is by no means extensive and if you want to learn more then we recommend reading more from these recent articles [Search Engine Optimization FAQ](http://webdesign.tutsplus.com/articles/general/search-engine-optimization-faq/) and [A Web Designer’s SEO Checklist](http://webdesign.tutsplus.com/articles/general/seo-checklist/?search_index=3). - **Keyword Research**: Make sure you are targeting the right demographic and market. It’s important to get this right in order to attract relevant traffic to your site. Carry out some research with [Google AdWords](http://www.google.co.uk/AdWords) and see which keyword (or search term) has the highest traffic potential and the least amount of competition and balance these two factors. - **Page Titles & Descriptions**: Do all the templates have the necessary page titles and meta data based on your keyword research? When focusing on a particular keyword try and get these to the front of descriptions and look at using both singular and plural forms. - **Image Alt-tags**: Do the main images of the site contain relevant and descriptive alt-tags? Using short descriptions will help. And remember try and choose a descriptive file name instead of random words and numbers for these images. - **Keywords**: Embed these in titles, descriptions and copy. - **Content**: If the content is good it will work to optimize and compliment the SEO. Good keyword density within the copy works well so use both singular and plural forms of keywords in your text. Don’t overload the content or over think this, make it natural and only add when and if it is relevant. Search engines also prefer longer pages of content so look at getting the content to +300 words but focus more on the quality than quantity. - **URLs**: Make sure the site's URLs are clean. Using a descriptive URL instead of ones that are made up of random numbers or words will help with SEO and visitors finding a page they may want to return to, and look at getting a keyword into the URL if relevant. *** ##Analytics No matter how small a site is, having web analytics running will gather you valuable information on how to improve your website going forward.. - **Monitoring**: With good SEO in place use tracking codes to measure this. Tools such as [Google Analytics](http://www.google.co.uk/analytics/) (free) or services such as [Hubspot](http://www.hubspot.com/), [GoSquared](https://www.gosquared.com/) or [KISSmetrics](https://www.kissmetrics.com/) (paid) will give valuable feedback. *** ##Security You may have a lot of things you do not want the world to know about. For example; user-uploaded media, or shoppers' Credit Card details. - **Protect Sensitive Pages**: Protect any sensitive pages or folders from being indexed on search engines by putting in place robots.txt files and by excluding them from within Webmaster Tools. Also consider whether you need to use an .htaccess file to disable folder view within directories. - **Security Certificates**: When developing an eCommerce website, or a site that handles sensitive visitor information, the level of security will be paramount. Make sure to use protocols such as [SSL encryption](http://www.thawte.com/) to protect against unwanted information theft. It has also been proven that displaying seals such as [TRUSTe](http://www.truste.com/products-and-services/enterprise-privacy/TRUSTed-websites), can increase the credibility of a site. *** ##Hosting &amp; Backups Finding a web hosting provider can be hard and knowing what you need can be even harder to understand. There are many options and pricing plans to choose from but make sure to choose a provider that meets your needs, not one that offers more than you need to pay for. - **Types**: Shared Hosting, Reseller Hosting, Cloud Hosting, VPS Hosting and Dedicated Servers. Not sure what these mean? Then read these [quick tips](http://webdesign.tutsplus.com/articles/general/quick-tip-choose-a-hosting-provider-based-on-your-needs/?search_index=1). - **Backups**: Make sure you use a provider who can provide daily and weekly backups of your server and make sure to take local backups as well. - **Monitoring**: Setup services such as [Pingdom](https://www.pingdom.com/) or other server monitoring tools to monitor the health of your server. *** ##Legal Before you start any project a signed contract should be in place. The contract should clearly outline the project deliverables and processes so both parties are 100% clear on what will be achieved as an end result. As part of that contract make sure the following has been agreed to cover any unforeseen circumstances. - **Image/Content Rights**: Clearly state that any supplied content or imagery that is handled by you remains the clients responsibility. Make clear that you will not be held liable for publishing content and images that they do not have the rights to use. Also educate the client that they should be using images or content that are either paid for or they have the rights to use. - **Payment Terms**: Set fair and staged payment terms at clearly defined milestones of a project (at the end of the design phase - before any development starts for example), never move on to the next phase of a project until the agreed payment is in. - **Timelines**: Set reasonable timelines that are fair to your client as well as manageable for you and your team. Clearly state that you will not be held responsible for any loss or damages as a result of a delay in the schedule caused by the client. It is a good idea to use something like [Basecamp](http://basecamp.com/) to manage your projects so all work and conversations are recorded should you need them to fall back on in the future. - **Intellectual Property Rights**: This will be different depending on who you are, what you’re offering, or the project in question. Clearly state what is owned by you and the client once the project is complete and payment has been made in full. Consider the rights to any software or code written by you that you wouldn’t want sold on, or anything similar that you feel you need to retain the rights to. *** ##Deliverables In the project contract clearly explain what the client will physically receive once a project is complete. The following is what we’d recommend. - **Live Website**: This is the bare minimum. Make sure their website is up and live and fully functioning as intended. - **Style Guide**: A simple style guide is extremely beneficial for any website owner, points to consider include: + Font Styles + Image Sizes + Tone of Voice + Colours + Imagery Style + Colours - **Assets & Icons**: Any icons, illustrations, or infographics design and created for the website may be helpful to your client going forward. Supply them the files in different formats so they can use them in presentations or future design work. - **Offline Copy**: If requested by the client provide a copy of the site. Remember websites are a living document that should be continually updated and improved, so unless the site is static you will have to be making regular offline backups for the client. *** ##When to Launch? Remember: never hand over a project or files without sign off and any outstanding payments settled. You will have no come back at this point if you do without either of these. Handing over a project without payment is the equivalent of a shop owner letting a customer walk out of a shop with a trolley full of goods on the promise that they will ‘pay you later’. Now everything is in place you are ready to launch. But when should you? We try our very best to never launch a site within two days of a weekend. Sometimes this practice has to go out the window on occasions but we always try and aim for a Monday to Wednesday launch slot. This will give you the opportunity to iron out any live bugs that surface during a working week. Trying to fix these during a weekend when either you or your developers are not around will only cause you headaches when you have a client who needs their site to be fully functional. Trust us, you will only learn the hard way if you don’t adopt this approach. *** ##Ongoing Maintenance So you’ve launched the site, it’s working great and the client is happy, now what? You need to make sure that it continues to run without a hitch. Things can go wrong or get missed, server security compromised, or it could fall over. Make sure you’re ready for every eventuality. - **Backups**: Always, always, make sure backups are in place. Run at least two backups daily - one in the morning and one 12 hours later, limiting the amount of data that can go missing. - **Version Control**: Try running a project through [Git](http://git-scm.com/), it’s a great version control system for teams of developers working in collaboration. Source code history is saved meaning that you can refer or revert back to previous versions if and when needed. For an introduction to Git read this in-depth article [Easy Version Control with Git](http://net.tutsplus.com/tutorials/other/easy-version-control-with-git/). - **Analytics**: In order to suggest improvements going forwards ask to be set up on the client's analytics, this way you can monitor traffic and site stats for the client and suggest improvements over the following month and year after launch. *** Let us know your launch checklist recommendations [on Webdesigntuts+](http://enva.to/XpDQqR) <file_sep>/content/portfolio/making of sagar.sutar.in/content.md While redesigning my portfolio, I have learned importance of design process for Web/UI design. So I thought to share my experience. I started my design career with web design. Initially I used to code website/UI directly in [sublime text](http://sublimetext.com) without thinking much about experience and content of website. I used to decide content at the time of writing a code, so I always needed to shift my focus between design, content and coding. After working on few interactive projects in last 6-8 months at [National Institute of Design, Ahmadabad](http://nid.edu) as a student ( I am not saying here that NID help us to learn web design ), I have ~~learnt~~ been learning to do a lot of research and analysis before designing any product. I tried to apply my learning to Web/UI design. ###### RESEARCH While redesigning, instead of directly diving into the sea of HTML tags, I planned whole process of designing. I thought about what I want to hightlight in my portfolio, what is the purpose my portfolio. Answers for those questions helped me to decide content - ***I thought about menus*** - including number of menus, text of menu, position of menubar. I tried to keep menubar minimal. [Image research_menu.JPG](http://) ***I thought about contents*** - I decided to put videos, photographs and text related to my projects because my primary focus was on projects and its content. I filled dozens of pages with hand-written content and finalized quality content. I wanted to keep all my projects open source, hence I have written about it from concept generation to implementation making this portfolio filled with text, photographs and videos. I tried to find out my own qualities and skills which I need to hightlight while deciding contents for **about** page. I tried to get these content verified. [Image making_tss_5.JPG](http://) ***I thought about fonts*** - It has been well said that web designing is 95% about typography. I tried out different fonts starting from Open Sans, Source Sans pro, Merriweather etc. I ended up with Open Sans as it reads good on devices with all screen sizes. [Image research_fonts.JPG](http://) ***I thought about colors***- As my focus is content especially my projects, I used only dual color theme, with more weight to neutral colors - black and white, This helped to design clean and minimal design. Other color that I chose was #C1272D, which has almost 75% of red in it. I felt this color is enough warm and refreshing. I played with different color before finalizing the color palette. [Image research_colors.JPG](http://) ***I thought about interactions***- I thought about animations and feedbacks that needs to be shown when menu, links, buttons, images or videos are clicked. I used ripple animations as seen in Google's material design. [Image research_interactions.JPG](http://) ***I redesigned my personal logo***- [First version](http://thesagarsutar.me/websites/design2013) of my website carried only initials of my name as a logo/favicon. I redesigned my logo completely. Initially I doodled few ideas by focusing on my personality attributes but later I found it is good to focus on my skills, so I tried to doodle ideas which can represent my art and technology skills. I doodled few alternatives and finalized one, which represents my development skills and my focus on art and technology domain, with two angular brackets connected with each other and forming a S-alphabet - my initial. * [Image final_logo.JPG](http://) * [Image logo1.JPG](http://) * [Image logo2.JPG](http://) * [Image logo3.JPG](http://) > Inspirations and trying out different alternatives helped me throughout this process of design. * [Image making_tss_4.JPG](http://) * [Image making_tss_6.JPG](http://) ###### VISUAL DESIGN I started with visual design parallel with my research just to get feedbacks for my research. I initially designed with dummy text and parallely finalized my content. I designed three different visual designs for my portfolio with each better than the previous one. * [Image making_tss_1.JPG](http://) * [Image making_tss_2.JPG](http://) * [Image making_tss_3.JPG](http://) * [Image making_tss_7.JPG](http://) ###### IMPLEMENTATION I implemented entire website with latest technologies like [nodejs](https://nodejs.org/) and [ghost](https://ghost.org/) as blogging platform. I used [waves.js](https://github.com/fians/Waves) for animating interactions as seen in Google's material design. [Less](http://lesscss.org/) a CSS preprocessor and finally of course HTML5 and CSS3. [Image making_tss_10.JPG](http://) ###### CONCLUSION This research helped me to set my focus on different phases of making my portfolio -- design, content generation and coding/implementation. Finally, I could say that I have found a UI design process which suits to me. This process is not complete yet but good to start with and it will definitely evolve over the time. [Image my_design_process.JPG](http://) So there is a lot of research and analysis behind the web/UI design than just coding. [Image making_tss_9.JPG](http://) <file_sep>/code/app/content/portfolio/intution/content.md ### Intuition: Predefined <p class="heading">Interactive art installation</p> <iframe width="560" height="315" src="https://www.youtube.com/embed/mR2TpKCa0jI?rel=0&amp;showinfo=0;theme=light" frameborder="0" allowfullscreen></iframe> This project is the part of **Interactive arts** course held by [New Media Design](http://cargocollective.com/nmd) department at [National Institute of Design, Ahmadabad](http://nid.edu) ###### ABOUT CONCEPT Intuition means strong feeling or hunch of future events, it is a gut feeling. Everyone has experienced a gut feeling -- that unconscious reasoning that forces us to do something without telling us why or how. It's a knowing without knowing. It's a sixth sense. Sometimes we think logical. However sometimes we go totally illogical. This illogical or unconscious thinking is called intuitive thinking. Surprisingly, these intuitive thoughts turns into reality most of the time. Why does it happen that these intuitions are correct? I think that intuition is an inner force, a driving force which already knows our next destination. It guides us to travel from one destination to another destination in our life. If we think that life has predefined path, our intuitions helps us to travel along that path. When we start believing on intuition we get more and more intuitions and we start to realize their power. My attempt was to explore intuitive thought process. I tried to create system which could trigger a thought in viewer’s mind. I designed an installation which tried to engage viewer and making them aware about the power of intuitions through different perspectives. ###### IMPLEMENTATION [Image from /content/portfolio/intuition/img/intuition1.png](http://) When we see an uneven surface, it's our natural tendency to wish that it could be flat. I found this could trigger an intuitive thought in a mind. I think intuitive is superpower that all of us holds. So I thought to make user interaction with installation more magical which will make them to feel as if they are superhumans. ###### MAKING OF INSTALLATION I started with the simple piece of wooden board ([MDF](http://en.wikipedia.org/wiki/Medium-density_fibreboard)), styrofoam, DC motor, ultrasonic proximity sensor and arduino micro-controller. Here is making of first prototype of installation. [Image from /content/portfolio/intuition/img/intuition_proto_1.jpg](http://) [Image from /content/portfolio/intuition/img/intuition_proto_2.jpg](http://) [Image from /content/portfolio/intuition/img/intuition_proto_3.jpg](http://) > Proximity sensor detects human presence or obstacle within its range and program written for arduino decides the direction of DC motor. I used LD29D IC for controlling DC motor direction. After successfully testing the concept on a small prototype. I decided a form of the installation. So considering a wall as a metaphor for intuition installation, I implemented the next prototype with a wall. [Image from /content/portfolio/intuition/img/intuition2.png](http://) The wall is made up of styrofoam and it is painted with acrylic colors. There are three bricks in the wall which are sensitive to user's presence or user's gesture. Each of the three bricks has a ultrasonic proximity sensor embedded inside. [Image from /content/portfolio/intuition/img/making_intuition_1.png](http://) I used the DC motor and converted its rotational motion into linear motion using rack and pinion gears. [Image from /content/portfolio/intuition/img/making_intuition_2.png](http://) Each of the brick has rack gear attached from behind. [Image from /content/portfolio/intuition/img/making_intuition_3.png](http://) [Image from /content/portfolio/intuition/img/making_intuition_4.png](http://) DC motor is attached with pinion gear. [Image from /content/portfolio/intuition/img/making_intuition_5.png](http://) All of these components are connected on a wooden block and ultrasonic sensors and DC motors are connected to arduino. [Image from /content/portfolio/intuition/img/making_intuition_6.png](http://) [Image from /content/portfolio/intuition/img/making_intuition_7.png](http://) This whole assembly is fixed inside the styrofoam wall. I used random number logic to decide which brick should come out. [Images from /content/portfolio/intuition/img/behind_wall_1.jpg](http://) to [Images from /content/portfolio/intuition/img/behind_wall_10.jpg](http://) ###### SOURCE CODE [Download from github](https://github.com/thesagarsutar/intuition_interactiveArts) ###### REFERENCES * [Documentary on intuition : Intuition Factor, Genius or chance](http://www.cultureunplugged.com/documentary/watch-online/play/50378/The-Intuitive-Factor--Genius-or-Chance-) * [Intuition: Brain Games Episode](http://bg3.nationalgeographic.com/episode/20/) * [How Does Intuition Speak To Me?](http://www.takingcharge.csh.umn.edu/explore-healing-practices/intuition-healthcare/how-does-intuition-speak-me) * [The Science of “Intuition”](http://www.brainpickings.org/2012/11/08/the-science-of-intuition-answers-for-aristotle/) * [Reversing motor using L293D IC chip](https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/lm293d) <file_sep>/code/app/content/portfolio/constellate/content.md ###### VIDEO <iframe width="560" height="315" src="https://www.youtube.com/embed/02gX7aKi68I?rel=0&amp;showinfo=0;theme=light" frameborder="0" allowfullscreen></iframe> *Video credits [<NAME>](https://www.facebook.com/sagar.sharma.587)* This interactive installation was presented on the occasion of 35th Convocation Ceremony took place at [National Institute of Design, Ahmadabad](http://nid.edu). This installation was actively designed and implemented by [New Media Design](http://cargocollective.com/nmd) department of National Institute of Design. ###### ABOUT CONCEPT When we achieve success like getting convocation from an institute or when we are leaving the institute, we had made new connections, we had connected with new people, new things. Considering "constellate" as a metaphor for "connections", our team made this interactive installation. ###### IMPLEMENTATION We thought of an implementation in which people in the field of installation will connect with each other by the lines projected from the projector. We also thought of the laser lights which will be installed on the edge of field and these laser lights will converge to nearest person in the field. [Image from content\portfolio\constellate\img\constellate1.jpg](http://) **Technology used for installation** * [Microsoft Kinect](http://www.amazon.com/Microsoft-L6M-00001-Kinect-for-Windows/dp/B006UIS53K) * [Processing ](https://processing.org/) * Short throw projector [Image from content\portfolio\constellate\img\constellate2.jpg](http://) Microsoft kinect sensor comes up with IR, RGB cameras. We used the kinect to track people inside the installation field. Processing has an API [simple-openni](http://code.google.com/p/simple-openni/), which has number of functions to use kinect with processing. This API gives you the co-ordinates of detected people. After getting co-ordinates the task was to draw a lines between people. We mapped the kinect with projector to get exact co-ordinates of a person on the ground. ###### MAKING OF INSTALLATION [Images from making_contellation_1.jpg](http://) to [making_contellation_7.jpg](http://) from [content\portfolio\constellate\img\](http://) ###### SOURCE CODE [Download from github](https://github.com/thesagarsutar/constellate) ###### REFERENCES [Getting Started with Kinect and Processing](http://shiffman.net/p5/kinect/) ###### Credits > <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Nandhini, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Pratish KS &ndash; Special thanks to Dr. <NAME>, <NAME>, <NAME> <file_sep>/code/app/content/writing/simplephotogallary.md Simple photo gallery using jquery -- January 13th, 2013 When I was designing my [Personal Website](http://thesagarsutar.me), I designed a photo gallery to show my art work. I had downloaded some plugins for that but I was not satisfied. Finally I created my own script using [jquery.reveal plugin](http://www.zurb.com/playground/reveal-modal-plugin). I had planned to write this post a month ago, so here is how I have created photo gallery. I know everyone (includingme) want to see demo first, so see demo from below link. [View Demo](http://sagarsutar.com/sources/2013/demos/photo_gallery/demo.html) [Download](http://thesagarsutar/sources/2013/demos/photo_gallery/photo_gallery.zip) Let’s take a look at html code first. ######HTML <ul class="gallery"> <li> <a href="" class="image"> <img src="images/1.jpg" alt="horse"> </a> <span class="img‐title">Friendship</span> </li> <li> <a href="" class="image"> <img src="images/2.jpg" alt="cat"> </a> <span class="img‐title">Little Tom</span> </li> <li> <a href="" class="image"> <img src="images/3.jpg" alt="beach"> </a> <span class="img‐title">wow</span> </li> <li> <a href="" class="image"> <img src="images/4.jpg" alt="seashore"> </a> <span class="img‐title">Beautiful Beach</span> </li> </ul> The list `‘.gallery’` holds all the images in gallery. Each `<li>…</li>` holds image previews and their title. What we want is, when we click on image it should show original image in modal screen.Original image might be large in size, so by considering the initial page load, I have shown small image previews in photo gallery, when we click on that preview, original image loads in modal popup.See the [demo](http://thesagarsutar.me/sources/2013/demos/photo_gallery/1.html) of this little html work. ######Now let’s style our gallery ######CSS .gallery { margin:5%; list‐style:none; /* remove the list‐item marker*/ text‐align: center; /*horizontally center list items*/ } li { display: inline‐block; /*display items inline*/ padding: 20px; } li img { /*specify how to display image */ border: 5px solid #505050; width: 250px; height: 200px; } .image { /*make image anchor display block so ‘img‐title’ spa n aligned at bottom of image*/ display: block; } .img‐title { display: inline‐block; line‐height: 20px; color: #fff; background‐color: #101010; margin‐top:10px; padding:10px 30px; ‐moz‐border‐radius: 50px; ‐webkit‐border‐radius: 50px; border‐radius: 50px; opacity: 0.7; } In `‘.img-title’` css `‘display: inline-block’` allows image title to set at image bottom as well as set width of span automatically equal total width of title. See [demo](http://thesagarsutar.me/sources/2013/demos/photo_gallery/2.html) after adding the above style. ######JavaScript This is important part of this tutorial because it does everything we are looking for. This javascript contains three parts. * [Create a modal popup](internal link to create modal section) * [Get original image link and load original image in modal popup](internal link to Get original image link and load original image) * [Auto adjust image width or height according to screen resolution keeping aspect ratio of an image](internal link to Auto adjust image width section) ######Create a modal popup Simple modal popup can be created using following HTML: ######HTML <div class="modal‐bg"></div> <div class="modal"> <a href="" class="close"></a> <img class="enlarged‐img"> <span class="image‐title"></span> </div> The modal popup contains `‘.modal’` div which pops up.`‘.modal-bg’` div is a popup background. Modal popup contains one close button to close popup, tag with class `‘enlarged-img’` which shows our original image and span for image title. We will see shortly how to get original image link and its title. But now let’s add some style for modal popup first. ######CSS .modal { display: none; position: absolute !important; z‐index: 200; background: #505050; ‐moz‐box‐shadow: 2px 2px 10px 2px #000; ‐webkit‐box‐shadow: 2px 2px 10px 2px #000; box‐shadow: 2px 2px 10px 2px #000; } .modal‐bg { display: none; position: fixed; height: 100%; width: 100%; top: 0; left: 0; background: #141414; /*fallback color if browser doesn’t sup port rgba*/ background: rgba(14,14,14,0.85); cursor: pointer; z‐index: 199; } The modal is absolutely positioned which will take it out of normal HTML flow. Similarly modal background (‘modal-bg’) is positioned fixed and its dimensions are set equal to screen using `height:100%, width:100%, top:0,left:0`. Also both modal and its background are initially hidden using display: none. This modal is opened and closed using jquery. ######JavaScript to open modal function modalOpen(delay) { modalON=true; $('.modal‐bg').stop().fadeIn(delay/2); $('.modal').css({'opacity':0,'display':'block'}); $('.modal').stop().delay(delay/2).animate({'opacity':1}, delay); } While opening modal,its background fades in , then modal popup appears, popup appears when css is set to `display:block`. ######JavaScript to close modal function modalClose(delay) { $('.modal').stop().fadeOut(delay/2); $('.modal‐bg').stop().delay(delay/2).fadeOut(delay, function() { $('.modal').removeAttr('style'); $('.modal‐bg').removeAttr('style'); modalON=false; }); } Modal popup is closed using jquery’s `fadeOut()`. [`fadeIn()`](http://api.jquery.com/fadeIn/) and [`fadeOut()`](http://api.jquery.com/fadeOut/) adds inline css to element hence we will remove inline css after modal is closed using [`removeAttr()`](http://api.jquery.com/removeAttr/). ######Get original image link and load original image Here a simple logic is used to get original image path. If you have observed `alt` attribute of image, you will see text inside it, this text is actually used to get original image name. ######JavaScript Var imgTitle; $(".image").click( function() { var clickedImg = $(this).find('img'); imgTitle = $(this).next().text(); var imgName = "images/" + clickedImg.attr("alt") + ".jpg"; $(".loader").show(); if($('.enlarged‐img').attr('src')) { //if has src attr remove it $('.enlarged‐img').removeAttr('src'); } $(".enlarged‐img").attr("src",imgName); return false; //cancel default behavior of anchor tag }); When we click on `.image`, we get value of `alt` attribute which we combine with `.jpg` extension and `images/` directory. That’s original image path. Similarly we store the image title in imgTitle variable using jquery’s [`text()`](http://api.jquery.com/text/). ######What is that `$(“.loader”).show();` ? If you have seen demo, you might have noticed a loader animation is shown when original image starts loading. This animation uses `.gif` image and it is shown using code below. <span class="loader"><img src="images/loader.gif" alt="Loading..."></span> This span is shown when image loads and we hide it when image loads completely. You can download your custom loader image from [ajaxload](http://www.ajaxload.info/). ######Now how to load image in modal popup ? Jquery provides `attr()` method. We can use it to set `src` attribute of `<img>`, we can also use it to check if `src` attribute of `<img>` is already there or not. Thus we do `$(“.enlarged-img”).attr(“src”,imgName);` to load new image. We also made check to see if `src` attribute is already there, if it is present we simply remove it. This check is particularity required when we close modal and open it again. jquery also provides one more methods called as `load()`, which is sent to element when it and its sub-elements are completely loaded. In our case we can used to show original image as soon as it is loaded and to hide loader image. Let’s look at our `load()`. ######JavaScript $(".enlarged‐img").load(function() { $(".loader").hide(); modalOpen(400); positionImg(); var w,h; w=$(this).width(); h=$(this).height(); $('.modal .image‐title').text(imgTitle); $(".modal").css({'height':h,'width':w}); $(window).resize(); }).error(function () { /*alert("Can't Load image.");*/ }); As soon as the above code snippet executes, it hides loading animation. Then call `modalOpen()` function which was explained above. Then it adjusts image height and width according to screen resolution using `positionImg()` then it takes new dimensions of image and set dimensions of popup modal accordingly. `$(window).resize()` triggers window’s `resize()` event, which contains code to center modal popup on screen. ######JavaScript var modalON=false; $(window).resize(function() { if(modalON) { $('.modal').css({ 'top':($(window).height() ‐ $('.modal').outerHeight()) / 2 + $(document).scrollTop(), 'left':($(window).width() ‐ $('.modal').outerWidth()) / 2 + $(document).scrollLeft() }); } }); ######Auto adjust image width or height according to screen resolution keeping aspect ratio of an image ######JavaScript var imgorgH, imgorgW; function realSize(){ var orgImg = $('.enlarged‐img'); var newImg = new Image(); newImg.src=orgImg.attr('src'); imgorgH = newImg.height; imgorgW = newImg.width; } The code above gets original dimensions of image without reloading image. The original width and height is stored in global variables `imgorgH` and `imgorgW`.You can read more about this from [css-tricks](http://css-tricks.com/snippets/jquery/get-an-images-native-width). ######Layout of auto-adjusting image [layout-simple-gallary.jpg]( insert image here) It works on percentage. It requires image to have atleast 10% distance of windows width and height horizontally and vertically. That’s what we need to check. windowW = browser windows’s inner width windowH = browser windows’s inner height minHdiff = 10% of browser’s inner height * 2, minWdiff = 10% of browser’s inner width * 2, Then we calculate actual vertical and horizontal distance between image and window and store them in `diffV` and `diffH`. We check them against `minHdiff` and `minWdiff`. If actual dimensions are greater than required then we change image dimensions to newly calculated dimensions else we display original image directly. ######JavaScript function positionImg() { var windowH, windowW, minHdiff, minVdiff, diffH, diffV; var newW,newH; realSize(); windowW = $(window).innerWidth(); windowH = $(window).innerHeight(); minHdiff = (windowW / 10)*2; minVdiff = (windowH / 10)*2; diffH = windowW ‐ imgorgW; diffV = windowH ‐ imgorgH; //calculate new width if((windowW‐minHdiff) >= imgorgW) newW = imgorgW; else newW = (windowW ‐ minHdiff); if((windowH ‐ minVdiff) >= imgorgH) newH = imgorgH; else newH = (windowH ‐ minVdiff); $(".enlarged‐img").css({ "width":"auto", "height":"auto" }); //auto adjust width or height if other one changes in below code if(diffH <= minHdiff && diffV <= minVdiff) { if(diffH <= diffV) $(".enlarged‐img").css("width", newW); else $(".enlarged‐img").css("height", newH); } else if(diffH<=minHdiff) //recalculate image width { $(".enlarged‐img").css("width",newW); } else if(diffV <= minVdiff) //recalculate image height { $(".enlarged‐img").css("height", newH); } } That’s it. I think this might be heavy tutorial but I have tried my best to explain all necessary code snippets. Also I have skipped some snippets, you can find this skipped code inside downloaded files. Comment if you didn’t understand any part and feel free to give suggestion. ######Links [View Demo](http://sagarsutar.com/sources/2013/demos/photo_gallery/demo.html) [Download](http://sagarsutar.com/sources/2013/demos/photo_gallery/photo_gallery.zip) >As this tutorial only explains how to create simple photo gallery, you can easily extend it to full featured image gallery by creating next and previous links which will show next image and previous image without closing modal popup. <file_sep>/content/portfolio/sparsh-uicomponenets/content.md ###### VIDEO <iframe width="560" height="315" src="https://www.youtube.com/embed/01c8cegXpS8?rel=0&amp;showinfo=0;theme=light" frameborder="0" allowfullscreen></iframe> ###### ABOUT SPARSH **SPARSH** is hindi word which means **touch**. The purpose of this project is to make UI/Web designing and prototyping easier. This software helps designers/developers to generate UI components as they want. As a name suggests, the purpose of this initiative is to make these components touch friendly. As a designer and developer I always need to use UI components (buttons, checkboxes, option buttons, text boxes etc.) in my projects. So rather than writing a code for these components each time, I have developed a piece of software, which will generate a code of these components for you. This tool provides user interface to generate these components as per your needs. As this project is under development it only supports creation of buttons as of now. Further components are in release queue. If you are interested you can contribute in development to make this tool better. I have shared a link of github repository at the end of this page. ###### IMPLEMENTATION **Button creation module** [Image from \content\portfolio\sparsh-uicomponenets\img\wireframes.png](http://) I started with deciding how the interface will look like for a button creation module. I decided which properties of button to be included inside the interface, starting from button background color to text shadow and fonts. While designing the module I done research and analysis about latests trends going on in web industry. So I included 3D and flat button creation option. I have written the whole code for this tool in JavaScript, HTML and CSS. One can choose the custom icons and custom fonts. To integrate custom web fonts and iconic fonts, I used [google web font](http://www.google.com/fonts) API and [fontello](http://fontello.com/) respectively. ###### SOURCE CODE [Download from github](https://github.com/thesagarsutar/sparsh) <file_sep>/code/app/projects/webuis/srv/scripts/slider.js $(document).ready(function () { $('#hero-slider ul a').click(function () { //reset all the items $('#hero-slider ul a').removeClass('active'); //set current item as active $(this).addClass('active'); //scroll it to the right position $('.mask').scrollTo($(this).attr('rel'), 600); //disable click event return false; }); });<file_sep>/code/app/projects/webuis/srv/scripts/tab.js var currrent_active=0; var new_active=0; var bk_color=0; var hoverColour = "#FFF"; $(function() { $("a.hoverbk").show("fast", function() { $(this).wrap("<div class=\"hoverbk\">"); $(this).attr("class",""); }); $("div.hoverbk").show("fast", function() { //append the background div $(this).append("<div></div>"); var w = $(this).find("a").width(); var h = $(this).find("a").height() + 20; $(this).width(w); $(this).height(h); $(this).find("div").width(w); $(this).find("div").height(h); $(this).find("a").hover(function(){ $(this).parent().children("div") .stop() .css({"display": "none", "opacity": "1"}) .fadeIn("fast"); bk_color=$(this).parent().children("div").css("background-color"); $(this) .stop() .css({"color": hoverColour}) .animate({"color": hoverColour}, 350); },function() { $(this).parent().children("div") .stop() .fadeOut("slow"); $(this) .stop() .animate({"color": hoverColour}, 250); }); $("div.hoverbk").find("a").click(function(){ new_active = $(this).attr("id"); if(currrent_active==0) { /*$("a#tab1").css({"background":"rgb(50, 50, 50)"}); $("a#tab1").css({"border-bottom":"1px solid rgb(53, 167, 255)"});*/ $("div.hoverbk").find("a#" + new_active).css({"background":"rgb(50, 50, 50)"}); $("div.hoverbk").find("a#" + new_active).css({"border-bottom":"1px solid rgb(53, 167, 255)"}); currrent_active = $(this).attr("id"); }else { $("div.hoverbk").find("a#" + currrent_active).css({"background":"transparent none repeat-x 0 0 scroll"}); $("div.hoverbk").find("a#" + currrent_active).css({"border-bottom":""}); $("div.hoverbk").find("a#" + new_active).css({"background":"rgb(50, 50, 50)"}); $("div.hoverbk").find("a#" + new_active).css({"border-bottom":"1px solid rgb(53, 167, 255)"}); currrent_active = $(this).attr("id"); } }); }); }); $(document).ready(function() { $('#navblock').localScroll({duration:800}); });<file_sep>/README.md #### [sagar.sutar.in](http://sagar.sutar.in) Personal website and portfolio website. <file_sep>/content/about/about.md <NAME> INTERACTION DESIGNER AND SOFTWARE DEVELOPER I AM FROM PUNE, INDIA. ####Namaste, I'm Sagar -- An **interaction designer** with strong focus on Human Computer Interaction (HCI), elegant user interfaces and user experience and a **software developer** with focus on Javascript, HTML5, CSS3, nodejs, java and open source hardware technologies like Arduino and a **product designer**. I worked in industry for one year as software engineer, before getting into design. I have **Bachelor’s Degree in Computer Science** from Pune University. Currently I am a design student of [**New Media Design**](http://cargocollective.com/nmd) at National Institute of Design, Ahmedabad. I always enjoyed working on open source technologies, automating tasks and simplifying complex things. I love handcoding :) **" I always try to create something new by combining art and technology "** Apart from designing and development, I spend my time with [colors and pencils](http://thesagarsutar.me), friends and family, meetups and startups. Take a look at [my portfolio](http://thesagarsutar.me). If you think I may help you or we can work together, let's take tea/coffee someday. <file_sep>/code/app/content/about/about.md ####Namaste, I'm Sagar - an **interaction designer** with strong focus on Human Computer Interaction (HCI), elegant user interfaces and user experience and a **software developer** with focus on Javascript, HTML5, CSS3, nodejs, java and open source hardware technologies like Arduino and a **product designer**. I worked in tech industry for one year as software engineer, before getting into design. I have **Bachelor’s Degree in Computer Science** from Pune University. Currently I am a design student of [New Media Design](http://cargocollective.com/nmd) at National Institute of Design, Ahmedabad. I always enjoyed working with open source technologies, automating tasks and simplifying complex things. I love hand-coding :) > " I always try to create something new by combining art and technology " Apart from designing and development, I spend my time with [colors and pencils](./artwork), friends and family, meetups and startups. Take a look at [my portfolio](./portfolio). If you think I may help you or we can work together, let's take tea/coffee someday. <file_sep>/code/app/content/writing/shakeit.md Shake it – Jquery log in box ------------------------------ July 29th, 2013 What’s our first reaction when we want to say ‘no’ ? It’s natural we shake our headto say no. So can we make log in box which will show this natural behavior ? Ofcourse yes, we can make log in box to shake for invalid login. Have a look at this demo. [Embedd this pen from codepen](http://codepen.io/thesagarsutar/pen/Aszkp) If you break down this animation, it will look like this. [shakeit.jpg from assets folder](http://) Initially our log in box is at center, in second step we move it to left side by some distance say x pixels then in third step we move this box to right 2x pixels from current position which is x pixels from center. In fourth step move it back to left side by 2x pixles and finally to the center. All these transitions we do using jquery [animate()](http://api.jquery.com/animate/) and for each transition we animate left margin. Also make a note that these transitions occur successively not simultaneously. So we have to delay each step. This is where jquery animate() helps us. We can wrap each animation inside another, so that each transition executes one after another. See this following example. #####Jquery $('#login‐box').animate({marginLeft:'‐=40'}, 80, function(){ $(this).animate({marginLeft:'+=80'}, 80}); }); You must have noticed, in above code I have wrapped second animation inside first, which executes after first animation is complete. Similarly we can wrap our 5 steps one inside another. This makes our log in box to shake. #####Note >It is important to set accurate duration for [animate()](http://api.jquery.com/animate/). Make sure that you have kept it small, which will make animation to feel natural. [See Demo](http://codepen.io/thesagarsutar/pen/Aszkp) [Download](http://sagarsutar.com/sources/2013/demos/shake-it-login-box/shake-it-login-box.zip) <file_sep>/checklist/README.md ##Website-Launch-Checklist-for-Web-Designers At FHOKE we’ve been through it all, from perfect launches to ones that have turned into complete nightmares! Through our experiences we’ve compiled a list, in no particular order, of a process we go through before we launch our sites. http://webdesign.tutsplus.com/articles/workflow/a-web-designers-site-launch-checklist-including-portable-formats/ ‎ <file_sep>/code/app/projects/webuis/kailash-parbat/css/rgba.php <?php /***************************************************************** * Script for automatic generation of one pixel * alpha-transparent images for non-RGBA browsers. * @author <NAME> * @version 1.0 beta * Licensed under a MIT license *****************************************************************/ ######## SETTINGS ############################################################## /** * Enter the directory in which to store cached color images. * This should be relative and SHOULD contain a trailing slash. * The directory you specify should exist and be writeable (CHMOD 666 or 777). * If you want to store the pngs at the same directory, leave blank (''). */ define('COLORDIR', 'colors/'); /** * If you requently use a color with varying alphas, you can name it * below, to save you some typing and make your CSS easier to read. */ $color_names = array( 'white' => array(255,255,255), 'black' => array(0,0,0) // , 'mycolor' => array(red value, green value, blue value) ); /** * If you don't want the generated pngs to be stored in the server, set the following to * false. This is STRONGLY NOT RECOMMENDED. It's here only for testing/debugging purposes. */ define('CACHEPNGS', true); ######## NO FURTHER EDITING, UNLESS YOU REALLY KNOW WHAT YOU'RE DOING ########## $dir = substr(COLORDIR,0,strlen(COLORDIR)-1); if(!is_writable($dir)) { die("The directory '$dir' either doesn't exist or isn't writable."); } $rgb = $color_names[$_REQUEST['name']]; $red = is_array($rgb)? $rgb[0] : intval($_REQUEST['r']); $green = is_array($rgb)? $rgb[1] : intval($_REQUEST['g']); $blue = is_array($rgb)? $rgb[2] : intval($_REQUEST['b']); // "A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent." // http://www.php.net/manual/en/function.imagecolorallocatealpha.php $alpha = intval(127 - 127 * ($_REQUEST['a'] / 100)); // Send headers header('Content-type: image/png'); header('Expires: Sun, 1 Jan 2026 00:00:00 GMT'); header('Cache-control: max-age=2903040000'); // Does it already exist? $filepath = COLORDIR . "color_r{$red}_g{$green}_b{$blue}_a$alpha.png"; if(/*CACHEPNGS and */file_exists($filepath)) { // The file exists, is it cached by the browser? $headers = apache_request_headers(); if (isset($headers['If-Modified-Since'])) { // We don't need to check if it actually was modified since then as it never changes. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($filepath)).' GMT', true, 304); } else { header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($filepath)).' GMT', true, 200); header('Content-Length: '.filesize($filepath)); die(file_get_contents($filepath)); } } else { $img = @imagecreatetruecolor(1,1) or die('Cannot Initialize new GD image stream'); // This is to allow the final image to have actual transparency // http://www.php.net/manual/en/function.imagesavealpha.php imagealphablending($img, false); imagesavealpha($img, true); // Allocate our requested color $color = imagecolorallocatealpha($img, $red, $green, $blue, $alpha); // Fill the image with it imagefill($img,0,0,$color); // Save the file //if(CACHEPNGS) { imagepng($img,$filepath,0,NULL); } // Serve the file imagepng($img); // Free up memory imagedestroy($img); } ?><file_sep>/content/portfolio/constellation/content.md ###### VIDEO <iframe width="560" height="315" src="https://www.youtube.com/embed/02gX7aKi68I?rel=0&amp;showinfo=0;theme=light" frameborder="0" allowfullscreen></iframe> *Video credits [<NAME>](https://www.facebook.com/sagar.sharma.587)* This interactive installation was presented on the occasion of 35th Convocation Ceremony took place at [National Institute of Design, Ahmadabad](http://nid.edu). This installation was actively designed and implemented by [New Media Design](http://cargocollective.com/nmd) department of NID. ###### ABOUT CONCEPT When we achieve success like getting convocation from an institute or when we are leaving the institute, we had made new connections, we had connected with new people, new things. Considering "constellation" as a metaphor for "connections", our team made this interactive installation. ###### IMPLEMENTATION We thought of an implementation in which people in the field of installation will connect with each other by the lines projected from the projector. We also thought of the laser lights which will be installed on the edge of field and these laser lights will converge to nearest person in the field. [Image from content\portfolio\constellation\img\constellation1.jpg](http://) **Technology used for installation** * [Microsoft Kinect](http://www.amazon.com/Microsoft-L6M-00001-Kinect-for-Windows/dp/B006UIS53K) * [Processing ](https://processing.org/) * Short throw projector [Image from content\portfolio\constellation\img\constellation2.jpg](http://) Microsoft kinect sensor comes up with IR, RBG cameras. We used the kinect to track people inside the installation field. Processing has an API [simple-openni](http://code.google.com/p/simple-openni/), which has number of functions to use kinect with processing. This API gives you the co-ordinates of detected people. After getting co-ordinates the task was to draw a lines between people. We mapped the kinect with projector to get exact co-ordinates of a person on the ground. ###### MAKING OF INSTALLATION [Images from making_contellation_1.jpg](http://) to [making_contellation_7.jpg](http://) from [content\portfolio\constellation\img\](http://) ###### SOURCE CODE [Download from github](https://github.com/thesagarsutar/constellation) ###### REFERENCES [Getting Started with Kinect and Processing](http://shiffman.net/p5/kinect/) <file_sep>/content/contact/contact.md " Don't forget to say hello :) " * [<EMAIL>](mailto:<EMAIL>) * [tweets on twitter](http://twitter.com/thesagarsutar) * [answers on stackoverflow](http://stackoverflow.com/users/1278767/sagar-sutar) * [quetions on quora](http://www.quora.com/Sagar-Sutar) * [experiments on codepen](http://codepen.io/thesagarsutar) * [collaborate on github](http://github.com/thesagarsutar) * [inspirations from dribbble](http://dribbble.com/thesagarsutar) <file_sep>/code/app/projects/webuis/srv/index.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>:: SRV Polytex ::</title> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge "> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link rel="stylesheet" type="text/css" href="styles/index.css"> <link rel="stylesheet" type="text/css" href="styles/slider.css"> <script type="text/javascript" src="scripts/jquery.min.js"></script> <script type="text/javascript" src="scripts/jquery.localscroll-1.2.7-min.js"></script> <script type="text/javascript" src="scripts/jquery.scrollto.js"></script> <script type="text/javascript" src="scripts/slider.js"></script> <script type="text/javascript" src="scripts/tab.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function() { $("#navblock").find("a#tab1").trigger('click'); }); </script> <div id="hdr"> <img src="images/srv.png" alt="SRV Polytex"> <div id="navblock"> <a class="hoverbk" id="tab1" href="#home">HOME</a> <a class="hoverbk" id="tab2" href="#aboutus">ABOUT US</a> <a class="hoverbk" id="tab3" href="#products">PRODUCTS</a> <a class="hoverbk" id="tab4" href="#exports">EXPORTS</a> <a class="hoverbk" id="tab5" href="#contactus">CONTACT US</a> <div class="clear"></div> </div> </div> <div style="display:block;height:1px;"></div> <!-- ########################################### menu ############################################### --> <div id="wrapper"> <div class="mnu" id="home"> <div class="topgap"></div> <div id="hero-slider"> <div class="mask"> <div class="slider-body"> <div class="panel" id="panel-1"> <img src="images/1.jpg" alt="SRV"> </div> <div class="panel" id="panel-2"> <img src="images/2.jpg" alt="SRV"> </div> <div class="panel" id="panel-3"> <img src="images/3.jpg" alt="SRV"> </div> </div> </div> <!-- .mask --> <div id="slider-menu"> <ul> <li><a id="aleft" href="#" rel="#panel-1" class="active"><span class="mnutext">SRV Polytex</span></a></li> <li><a href="#" rel="#panel-2"><span class="mnutext">Suraj Industries</span></a></li> <li><a id="aright" href="#" rel="#panel-3"><span class="mnutext">SRV Synthetics</span></a></li> </ul> </div> <div class="clear"></div> </div> <!-- #hero-slider --> <div id="tagline"><img id="quote" src="images/quote.png" alt=" "><p>However big or small the customer, whatever their demands, we go out of our way to cater to those needs.</p><img id="quoter" src="images/quoter.png" alt=" "></div> </div> <div class="cover"></div> <div class="mnu" id="aboutus"> <div class="topgap"></div> <table id="table-aboutus"> <tr> <td><div class="info"><span><h1>SRV Polytex</h1><br>SRV Polytex Pvt.Ltd is the leading producer of polyester yarn in India. It started in the year 1997 by name of SRV Polytex Pvt.Ltd with 3 machines for texturising fine denier POY. SRV was first texturiser in India to process 250/34D POY at the speed of 1000mts per min on their machines which was great achievement that won them many accolades and became the talk of texturising industry. By 2012, they have 33 machines in SRV Polytex Pvt.Ltd, Suraj Industries and SRV Synthetics. The turnover of all the companies is about 350 crores. It has headquaters in Mumbai and manufacturing unit in Silvassa since last 15 years. </span></div></td> <td><div class="info"><span><h1>Origin and Growth</h1><br>SRV Polytex Pvt.Ltd launched in the year 1997 in Silvassa with 3 machines for texturising fine denier POY.After having a strong hold in the market SRV Polytex Pvt.Ltd advanced more in to manufacturing sector by establishing Suraj Industries and SRV Synthetics in year 2004 and 2009 respectively. SRV advanced with the help of strong technical team that has largely been able to contribute towards imporving operational efficiency at the plant as well as increasing profitability. The company is also working out on expansions and adding new products. </span></div></td> </tr> <tr> <td><div class="info"><span><h1>Management</h1><br> <p class="founder">Rajendra.V.Shah:</p> He is the chairman of the company since last 15 years. He looks after the Purchase department and the sales department. <p class="founder">Sudhir.V.Shah:</p> He is the managing director of the company since last 15 years. He looks after the production department and the things related to assets.</span></div></td> <td><div class="info"><span><h1>Certification</h1><br> [ICRA]BBB+(stable)</span></div></td> </tr> </table> </div> <div class="mnu" id="products"> <div class="topgap"></div> <table id="prods"> <tr id="thr"> <td colspan="4"> 100% Polyester Texturized Yarn and Spandex Yarn </td> </tr> <tr> <td class="odd">80 ROTO</td> <td class="odd">80 COTLUK</td> <td class="odd">80/2 S&Z COTLUK ROTO</td> <td class="odd">75 TEX</td> </tr> <tr> <td class="even">72/48 ROTO</td> <td class="even">80/2 LIM</td> <td class="even">155 ROTO</td> <td class="even">155 TEX</td> </tr> <tr> <td class="odd">155/34 LIM</td> <td class="odd">155/108 LIM</td> <td class="odd">155/108 MICRO ROTO</td> <td class="odd">155/108 MICRO HIM</td> </tr> <tr> <td class="even">155 BLACK ROTO</td> <td class="even">155 BLACK TEX</td> <td class="even">160 LIM</td> <td class="even">160 TEX</td> </tr> <tr> <td class="odd">170/108 LIM</td> <td class="odd">155/48 HIM</td> <td class="odd">155 BLACK TEX</td> <td class="odd">160 LIM</td> </tr> <tr> <td class="even">160 TEX</td> <td class="even">170/108 LIM</td> <td class="even">155/48 HIM</td> <td class="even">155/48/2 S&Z LIM</td> </tr> <tr> <td class="odd">150 BLACK HIM</td> <td class="odd">155 COTLUK ROTO</td> <td class="odd">155/2 MILANGE</td> <td class="odd">155/48 BRIGHT HIM</td> </tr> <tr> <td class="even">220/34 LIM</td> <td class="even">210 BLACK HIM</td> <td class="even">220/48 HIM</td> <td class="even">220 BRIGHT PRINT HIM</td> </tr> <tr> <td class="odd">240 VD 51</td> <td class="odd">230 STRETCH</td> <td class="odd">360 BLACK STRETCH</td> <td class="odd">450 HIM</td> </tr> <tr> <td class="even">300 ROTO</td> <td class="even">320 ROTO</td> <td class="even">320 TEX</td> <td class="even">320 LIM</td> </tr> <tr> <td class="odd">320/216 MICRO LIM</td> <td class="odd">320 BLACK ROTO</td> <td class="odd">320 BLACK TEX</td> <td class="odd">320 BLACK HIM</td> </tr> <tr> <td class="even">320 HIM</td> <td class="even">300 BRIGHT HIM</td> <td class="even">300 LIM</td> <td class="even">320 COTLUK ROTO</td> </tr> <tr> <td class="odd">360 STRECTCH</td> <td class="odd">400 LIM</td> <td class="odd">450/192 BRIGHT HIM</td> <td class="odd">450 BLACK HIM</td> </tr> <tr> <td class="even">600 ROTO</td> <td class="even">600 ROTO BLACK</td> <td class="even"></td> <td class="even"></td> </tr> </table> </div> <div class="mnu" id="exports"> <div class="topgap"></div> <div id="exp" class="info"><span><h2>SRV Exports</h2><br> " SRV Polytex Pvt.Ltd gives their customers a competitive advantage through superior products and services at the best price. " It is one of the well known exporters of quality yarns. It started exporting since the year 2004 with a vision to expand its business operations globally.It is also looking forward to export at other parts of the world. It is renowned manufacturer and exporter and has satisfied customers around the world. It uses the best technology available which helps to provide the superior quality.It exports according to the market demand and at cost effective price. High quality, reasonable price and fast service are their objectives.In addition,its competitive pricing policy and ethical business practices,it has also expaneded their spread out clientele globally.</span></div> </div> <div class="mnu" id="contactus"> <div class="topgap"></div> <table id="cnus"> <tr> <td><div class="outer"><span class="inner"><div id="hd3">HEAD OFFICE</div> 201, 202, 203, SUPER MARKET, 2nd FLOOR,<br> <NAME>, <NAME>(EAST),<br> MUMBAI-400057.<br> TELEPHONE: (022)26160770/26160769.<br> EMAIL: <EMAIL></span> <iframe marginheight="10" marginwidth="10" src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=CWNzSXwjrX8OFaJwIwEdeodXBCnFuy-ptsnnOzEK1b_JrStmiw&amp;q=Monghibai+Rd,+Vile+Parle,+Vile+Parle+East,+Mumbai,+Maharashtra,+India&amp;aq=&amp;sll=19.104621,72.850256&amp;sspn=0.04923,0.084372&amp;ie=UTF8&amp;hq=&amp;hnear=Monghibai+Rd,+Mumbai,+Maharashtra,+India&amp;ll=19.09981,72.845178&amp;spn=0.012308,0.021093&amp;t=m&amp;z=14&amp;output=embed"></iframe> </div> </td> <td> <div class="outer"> <span class="inner"> <h4>SRV SYNTHETICS</h4> SURVEY NO:259/12, PARSHWANATH INDUSTRIAL ESTATE, VILLAGE DADRA, DADRA & NAGAR HAVELI,(U.T), SILVASSA-396230. <br><br> <h4> SURAJ INDUSTRIES</h4> SURVEY NO:118/1-2, NEAR DADRA CHECK POST, DADRA & <NAME>, DADRA,SILVASSA-396230. <br><br> <h4> SRV POLYTEX PVT.LTD</h4> 118/1,VILLAGE DADRA, NEAR DADRA CHECK POST, DADRA & <NAME>,(U.T), SILVASSA-396230. </span> <iframe marginheight="10" marginwidth="10" src="https://maps.google.co.in/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=118%2F1,Dadra,+Dadra+and+Nagar+Haveli&amp;aq=&amp;sll=20.316667,72.966667&amp;sspn=0.041936,0.064888&amp;g=Dadra,+Dadra+and+Nagar+Haveli&amp;ie=UTF8&amp;hq=&amp;hnear=Valson+Industries+Dadra+Unit,+SH+185A,+Dadra,+Dadra+and+Nagar+Haveli&amp;ll=20.326393,72.960291&amp;spn=0.083866,0.129776&amp;t=m&amp;z=13&amp;output=embed"></iframe> </div> </td> </tr> </table> </div> <!--<div id="ftr"> </div>--> </div> </body> </html><file_sep>/code/app/content/portfolio/nano-pico/content.md ### NANO-PICO <file_sep>/code/app/projects/webuis/kailash-parbat/scrollbar/scrollbar.js (function($){ $(window).load(function(){ $(".content-outer").mCustomScrollbar({ set_height:$('.content').height()-44, scrollButtons:{ enable:true }, callbacks:{ onScrollStart:function(){ OnScrollStart(); }, onScroll:function(){ OnScroll(); }, onTotalScroll:function(){ OnTotalScroll(); }, onTotalScrollBack:function(){ OnTotalScrollBack(); }, onTotalScrollOffset:30, whileScrolling:function(){ WhileScrolling(); } } }); $("#deals .outer").mCustomScrollbar({ scrollButtons:{ enable:true }, callbacks:{ onScrollStart:function(){ OnScrollStart(); }, onScroll:function(){ OnScroll(); }, onTotalScroll:function(){ OnTotalScroll(); }, onTotalScrollBack:function(){ OnTotalScrollBack(); }, onTotalScrollOffset:30, whileScrolling:function(){ WhileScrolling(); } } }); $(".signature").mCustomScrollbar({ set_height:$('.main-content').height(), scrollButtons:{ enable:true }, callbacks:{ onScrollStart:function(){ OnScrollStart(); }, onScroll:function(){ OnScroll(); }, onTotalScroll:function(){ OnTotalScroll(); }, onTotalScrollBack:function(){ OnTotalScrollBack(); }, onTotalScrollOffset:30, whileScrolling:function(){ WhileScrolling(); } } }); function OnScrollStart(){ $(".output .onScrollStart").stop(true,true).text("").css("display","inline-block").text("Scroll started").fadeOut(500,"easeInCirc"); } function OnScroll(){ $(".output .onScroll").stop(true,true).text("").css("display","inline-block").text("Scrolled...").fadeOut(500,"easeInCirc"); } function OnTotalScroll(){ $(".output .onTotalScroll").stop(true,true).text("").css("display","inline-block").text("Scroll end reached").fadeOut(500,"easeInCirc"); } function OnTotalScrollBack(){ $(".output .onTotalScrollBack").stop(true,true).text("").css("display","inline-block").text("Scroll begin reached").fadeOut(500,"easeInCirc"); } function WhileScrolling(){ $(".output .whileScrolling").stop(true,true).css("display","inline-block").text("Scrolling").fadeOut(500,"easeInCirc"); } }); })(jQuery); (function($){ $(document).ready(function(){ $('.isotope-item').click(function(){ $(".signature").mCustomScrollbar("update"); }); $(window).resize(function() { $(".content-outer").mCustomScrollbar("destroy"); $("#deals .outer").mCustomScrollbar("destroy"); $(".signature").mCustomScrollbar("destroy"); $(window).load(); }); }); })(jQuery);<file_sep>/content/writing/goforprogressivejpeg.md Go for progressive JPEG ---------------------- January 27th, 2013 Is your webpage loading slowly? It’s important to load page quickly as possible otherwise this loading time impacts on visitors view. The site visitors will not wait, because they want quick response. Why webpage loads slowly? One of the reason is images. See these [stats](http://httparchive.org/interesting.php). [chart.png from assets folder](http://httparchive.org/interesting.php) These stats show that one of the reason behind slow webpage is an image. #####How to optimize an image for a web ? A high quality image increases website’s beauty, but also increases page loading time. Can we optimize image without losing quality? Yes, using “JPEG”. These jpegs are of two types Baseline jpeg and Progressive jpeg. ######Baseline jpeg [baselinejpeg.jpg from assets folder](http://) Baseline jpegs are displayed as image data receives. When a baseline jpeg of high quality is being loaded, we can notice their top to bottom rendering. Example of baseline jpeg is a Google image search. When we see a full size image from Google image result, we can notice their top to bottom rendering. ######Baseline jpeg [progressivejpeg.jpg from assets folder](http://) Progressive jpegs are really optimized for webpages. Instead of rendering image from top to bottom, progressive jpegs are rendered in multiple passes. In first pass full image is displayed with available data. That’s why we see blurry image initially. After each next pass, image will look sharper. There are many websites, which are using progressive jpeg. One we all may know is facebook. ######Pros There are couple of advantages using progressive jpegs, one is their average size is smaller than baseline jpeg and second is, for slow internet they are really useful because full size blurry image is shown initially. ######Cons The only disadvantage of using progressive jpegs is browser support. Only [some of the modern browsers support progressive jpegs](http://calendar.perfplanet.com/2012/progressive-jpegs-a-new-best-practice/). Fortunately browsers which do not render progressive jpegs, display them when entire image is downloaded. #####Conclusion Baseline jpegs are not going to increase website loading speed, so if you have largeno of images on your webpage then **go for progressive jpeg**. #####References [Progressive jpegs: a new best practice ](http://calendar.perfplanet.com/2012/progressive-jpegs-a-new-best-practice/) [Interesting stats](http://httparchive.org/interesting.php) #####How to create a progressive jpeg ? >If you are using Adobe Photoshop then it is easy to create progressive jpeg. In Adobe Photoshop, when you are saving jpeg, go to File menu -> Save For Web -> Select jpeg from right pane -> tick progressive jpeg -> Click on Save. <file_sep>/code/app/projects/webuis/kailash-parbat/js/script.js $(document).ready(function() { $("#menu li a").hover(function() { $(this).stop(true, true).animate({ 'opacity' : '0.92' }, 300); }, function() { $(this).stop(true, true).animate({ 'opacity' : '0.6' }, 300); }); $(".left-links").hover(function() { if($(this).parent().attr("id")!='active'){ $(this).parent().stop(true, true).animate({ paddingBottom : '10px' }, 300); } }, function() { if($(this).parent().attr("id")!='active'){ $(this).parent().stop(true, true).animate({ paddingBottom : '0px' }, 300); } }); $(".grayscale img:first-child").hover(function() { $(this).css({ "opacity" : "0" }); $(this).next().css({ "opacity" : "1" }); }, function() { $(this).css({ "opacity" : "1" }); $(this).next().css({ "opacity" : "0" }); }); $('.book-table-button').hover(function() { $(this).stop().animate({ 'width' : '200px' }, 500); }, function() { $(this).stop().animate({ 'width' : '66px' }, 500); }); $(window).resize(function() { $(".reveal-modal").css({ "left" : ($(window).width() - $('.reveal-modal').outerWidth()) / 2 + $(document).scrollLeft(), "top" : ($(window).height() - $('.reveal-modal').outerHeight()) / 2 + $(document).scrollTop() }); $('.content-outer').attr('style',' '); // $('.content-outer').css({'max-height':$('.content').height()+44}); }); $(window).resize(); $('.bg').mousedown(function() { return false; }); }); <file_sep>/code/app/projects/recall.html <!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta charset="utf-8"> <title>Recall : Hackathon &ndash; <NAME> </title> <meta name="description" content="Researcher and Designer in practice"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui"> <meta http-equiv="cleartype" content="on"> <meta name="msapplication-tap-highlight" content="no"> <link type="text/plain" rel="author" href="/humans.txt"> <link href="https://fonts.googleapis.com/css?family=Merriweather:300i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400,400i,700" rel="stylesheet"><!-- build:css ../css/beauty.min.css --> <link rel="stylesheet" href="../css/beauty.css"><!-- /build --> <script src="../js/vendor/modernizr-2.7.1.min.js"></script> <script> (function(d) { var config = { //- kitId: 'tcm8vgy', kitId: 'tey3fkw', scriptTimeout: 3000 }, h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+=" wf-loading";tk.src='//use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s) })(document); </script> </head> <body> <main> <div class="l-center-70p wrapper-for-float"> <header id="menu"><a id="home-link" href="/" class="nonstylized-link"><span><NAME></span></a> <nav> <ul> <li><a data-tab-index="0" href="../about">about</a></li> <li class="seperator-menu">/</li> <li><a data-tab-index="1" href="../files/sagar_sutar.pdf">resume</a></li> <li class="seperator-menu">/</li> <li><a data-tab-index="2" href="../archive">archive</a></li> </ul> </nav> </header> </div> <article class="l-center-50p portfolio-article detail-article"> <header> <h3 class="article-title">Recall : Recycle PET bottles</h3> <p class="subheading">Service design, Interface Design </p> </header> <section> <figure> <div class="fluid-width-video-wrapper"><iframe src="https://player.vimeo.com/video/216405180?badge=0&autopause=1&color=cc272d&byline=0&portrait=0&title=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div> </figure> <p> Global Hackathon curated by Ellen MacArthur Foundation, UK and supported by Philips and Cisco. </p> <div class="spacer-20"></div> </section> <section> <h4>Hackathon Topic</h4> <p>Exploring and providing solutions for any major public problems within the space-model of circular economy.</p><strong>Team ORCAS's Problem Statement</strong> <p>How to increase PET container's lifecycle by introducing it's reusability, through structured buisness model.</p> <div class="spacer-20"></div> </section> <section> <h4>Proposed Solution </h4><strong>Recall : A smartphone Application</strong> <P> Recall is smarphone application which is used by the consumer to keep the track of PET bottles and return these bottles after its use-cycle is over. The stakeholders of this service are product manufacturer, supermarkets, consumer, aggregator. Consumer purchases products in PET bottles through supermarkets, after these products are used, she scans the barcode on PET bottles using RECALL app. Once perticular number of bottles are collected, aggregator collects these bottles and returns to product manufacturer for reuse. Once product lifecycle is over, bottles are safely disposed. </P> <div class="spacer-20"></div> <figure> <div class="fluid-width-video-wrapper"><iframe src="https://player.vimeo.com/video/216403717?badge=0&autopause=1&color=cc272d&byline=0&portrait=0&title=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div> </figure> </section> <section> <h4>Process</h4> <figure class="multi-image-wrapper"> <ul class="inline-list"> <li><a href="../img/portfolio/recall/hd/1.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/recall/1.jpg" class="grayscale"></a></li> <li><a href="../img/portfolio/recall/hd/2.jpg" role="lightbox" class="non-text-link"><img alt="Picture" src="../img/bg.png" data-src="../img/portfolio/recall/2.jpg" class="grayscale"></a></li> </ul> </figure> </section> <section> <h4>Prototype</h4> <div class="center-content"><a role="button" href="https://invis.io/4T6G5VSN8#/142477511_App-01" class="button primary"><span>Recall Clickable Prototype</span></a></div> </section> <section> <h4>Credits</h4> <p class="subheading">Team ORCAS: <NAME>, <NAME>, <NAME>, <NAME>, <NAME> </p> </section> <section> <h4>Hackathon Website</h4><a href="https://www.thinkdif.co/hackathon" target="_blank">#thinkdiff</a> <div class="spacer-20"></div> </section> </article> </main><!-- build:js ../js/interactions.min.js --> <script src="../js/interactions.js"></script><!-- /build --> </body> </html>
7ad7fb2993ad655e356e82e8eecdaf9f4655108c
[ "Markdown", "JavaScript", "HTML", "PHP" ]
23
HTML
thesagarsutar/sagar.sutar.in
9d34a8212cd81ae210962e9fb3e2453b3c37d36f
78a76a85c11194bdd1859d88ab3f76369f9c0a11
refs/heads/master
<repo_name>VolcOne/TestTask<file_sep>/ca_testTask/Program.cs using System; using System.Threading.Tasks; using Autofac; using ca_testTask.Handlers; using ca_testTask.Infrastructure; using ca_testTask.Model.Enums; using ca_testTask.Services; namespace ca_testTask { class Program { static void Main(string[] args) { if (args.Length == 0 || args[0] == "?") { Console.WriteLine(GetHelp()); return; } var path = args[0]; var action = (ActionType)Enum.Parse(typeof(ActionType), args.Length > 1 ? args[1] : "all", true); var pathLogFileResult = args.Length == 3 ? args[2] : null; Task.Run(() => StartAsync(path, action, pathLogFileResult)).GetAwaiter().GetResult(); Console.WriteLine("\nProcess finished. For exit press any key"); Console.ReadKey(); } private static async Task StartAsync(string path, ActionType action, string pathLogFileResult) { try { ServicesRegister sReg = new ServicesRegister(pathLogFileResult); using (var scope = sReg.Container.BeginLifetimeScope()) { var runner = scope.Resolve<IRunner>(); runner.Run(); var fileSearcher = scope.ResolveKeyed<IFileSearcher>(action); var result = await fileSearcher.GetFilePaths(path); runner.Logging(result); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); //throw; } } private static string GetHelp() { return @"Usage: testTask <startPath> [<action> <logFile>] <startPath> - will start search files from that folder <action> - [all|cpp|reversed1|reversed2] by default ""all"" <logFile> - name of file for logging by default ""results.txt"""; } } } <file_sep>/ca_testTask/Services/SurfaceScanner.cs using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace ca_testTask.Services { public class SurfaceScanner : ISurfaceScanner { public async Task<IEnumerable<string>> ScanFilesAsync(string startPath, string filter = null) { var files = new List<string>(); DirectoryInfo directory = new DirectoryInfo(startPath); files.AddRange(directory.GetFiles(filter ?? "*.*").Select(f => f.FullName)); var directories = directory.GetDirectories(); var tasks = directories.AsParallel().Select( async directoryInfo => { var fls = await ScanFilesAsync(directoryInfo.FullName, filter); return fls; }).ToList(); var tasksResult = await Task.WhenAll(tasks); foreach (var t in tasksResult) { files.AddRange(t); } return files; } } public interface ISurfaceScanner { Task<IEnumerable<string>> ScanFilesAsync(string startPath, string filter = null); } } <file_sep>/ca_testTask/Handlers/CppFileSearcher.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ca_testTask.Services; namespace ca_testTask.Handlers { public sealed class CppFileSearcher : FileSearcherBase, IFileSearcher { protected override string SearchPattern => "*.cpp"; public CppFileSearcher(ISurfaceScanner surfaceScanner):base(surfaceScanner) { } public async Task<IEnumerable<string>> GetFilePaths(string startPath) { var fileInfos = await GetFileNamesAsync(startPath); return fileInfos.Select(f => CutPath(f, startPath) + " /"); } } }<file_sep>/ca_testTask/Handlers/AllFileSearcher.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ca_testTask.Services; namespace ca_testTask.Handlers { public sealed class AllFileSearcher : FileSearcherBase, IFileSearcher { public AllFileSearcher(ISurfaceScanner surfaceScanner) : base(surfaceScanner) { } public async Task<IEnumerable<string>> GetFilePaths(string startPath) { var fileInfos = await GetFileNamesAsync(startPath); return fileInfos.Select(f => CutPath(f, startPath)); } } }<file_sep>/ca_testTask/Infrastructure/ServicesRegister.cs using Autofac; using ca_testTask.Handlers; using ca_testTask.Model.Enums; using ca_testTask.Services; using NLog; using NLog.Config; using NLog.Targets; namespace ca_testTask.Infrastructure { public sealed class ServicesRegister { public ServicesRegister(string pathLogFileResult = null) : this() { if (pathLogFileResult != null) { ((FileTarget)LogManager.Configuration.AllTargets[0]).FileName = pathLogFileResult; } } public ServicesRegister() { LogManager.Configuration = new XmlLoggingConfiguration("nlog.config", true); Resister(); } public IContainer Container { get; private set; } private void Resister() { var builder = new ContainerBuilder(); builder.RegisterType<Runner>().As<IRunner>(); builder.RegisterType<SurfaceScanner>().As<ISurfaceScanner>(); builder.RegisterType<AllFileSearcher>().Keyed<IFileSearcher>(ActionType.All); builder.RegisterType<CppFileSearcher>().Keyed<IFileSearcher>(ActionType.Cpp); builder.RegisterType<Reversed1FileSearcher>().Keyed<IFileSearcher>(ActionType.Reversed1); builder.RegisterType<Reversed2FileSearcher>().Keyed<IFileSearcher>(ActionType.Reversed2); builder.RegisterInstance(LogManager.GetLogger("console")).As<ILogger>().SingleInstance(); Container = builder.Build(); } } }<file_sep>/ca_testTask/Model/Enums/ActionType.cs namespace ca_testTask.Model.Enums { public enum ActionType : byte { All = 0, Reversed1 = 1, Reversed2 = 2, Cpp = 3, } }<file_sep>/ca_testTask/Handlers/Reversed2FileSearcher.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ca_testTask.Services; namespace ca_testTask.Handlers { public sealed class Reversed2FileSearcher : FileSearcherBase, IFileSearcher { public Reversed2FileSearcher(ISurfaceScanner surfaceScanner) : base(surfaceScanner) { } public async Task<IEnumerable<string>> GetFilePaths(string startPath) { var fileInfos = await GetFileNamesAsync(startPath); return fileInfos.Select(f => new string(CutPath(f, startPath).Reverse().ToArray())); } } }<file_sep>/ca_testTask/Services/Runner.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using NLog; namespace ca_testTask.Services { public class Runner : IRunner, IDisposable { private readonly ILogger _logger; public Runner(ILogger logger) { _logger = logger; } public void Run() { _logger.Debug("Started"); } public void Logging(IEnumerable<string> result) { foreach (var log in result) { _logger.Info(log); } } public void Dispose() { _logger.Debug("Finished"); } } public interface IRunner { void Run(); void Logging(IEnumerable<string> result); } }<file_sep>/ca_testTask/Handlers/FileSearcherBase.cs using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using ca_testTask.Services; namespace ca_testTask.Handlers { public abstract class FileSearcherBase { private readonly ISurfaceScanner _surfaceScanner; protected virtual string SearchPattern => "*.*"; protected FileSearcherBase(ISurfaceScanner surfaceScanner) { _surfaceScanner = surfaceScanner; } protected string CutPath(string fileName, string path) { var indexOf = fileName.IndexOf(path, StringComparison.InvariantCultureIgnoreCase); if (indexOf < 0) { return fileName; } var remainingLength = fileName.Length - path.Length + indexOf; return fileName.Substring(path.Length + indexOf, remainingLength).TrimStart('\\'); } protected async Task<IEnumerable<string>> GetFileNamesAsync(string startPath) { return await _surfaceScanner.ScanFilesAsync(startPath, SearchPattern); } } }<file_sep>/ca_testTask/Handlers/IFileSearcher.cs using System.Collections.Generic; using System.Threading.Tasks; namespace ca_testTask.Handlers { public interface IFileSearcher { Task<IEnumerable<string>> GetFilePaths(string startPath); } }<file_sep>/ca_testTask/Handlers/Reversed1FileSearcher.cs using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ca_testTask.Services; namespace ca_testTask.Handlers { public sealed class Reversed1FileSearcher : FileSearcherBase, IFileSearcher { public Reversed1FileSearcher(ISurfaceScanner surfaceScanner) : base(surfaceScanner) { } public async Task<IEnumerable<string>> GetFilePaths(string startPath) { var fileInfos = await GetFileNamesAsync(startPath); return fileInfos.Select(f => { var cuttedPath = CutPath(f, startPath); var pathItems = cuttedPath.Split('\\'); StringBuilder sb = new StringBuilder(); foreach (var item in pathItems.Reverse()) { sb.AppendFormat("{0}{1}", sb.Length > 0 ? "\\" : "", item); } return sb.ToString(); }); } } }<file_sep>/ca_testTask.Tests/FileSearcherTest.cs using System.Linq; using System.Threading.Tasks; using ca_testTask.Handlers; using ca_testTask.Services; using Moq; using Xunit; namespace ca_testTask.Tests { public sealed class FileSearcherTest { private readonly Mock<ISurfaceScanner> _mock = new Mock<ISurfaceScanner>(MockBehavior.Strict); public FileSearcherTest() { _mock.Setup(s => s.ScanFilesAsync(It.IsAny<string>(), It.IsAny<string>())) .ReturnsAsync(new[] {"c:\\f\\bla\\ra\\t.dat"}); } [Fact] public async Task GetFilePaths_AllAction_ReturnedAsIs() { // Arrange var sut = new AllFileSearcher(_mock.Object); // Act var result = await sut.GetFilePaths("c:\\"); // Assert Assert.Equal(result.First(), "f\\bla\\ra\\t.dat"); } [Fact] public async Task GetFilePaths_CppAction_ReturnedWithNewEnd() { // Arrange var sut = new CppFileSearcher(_mock.Object); // Act var result = await sut.GetFilePaths("c:\\"); // Assert Assert.Equal(result.First(), "f\\bla\\ra\\t.dat /"); } [Fact] public async Task GetFilePaths_Reversed1Action_ReturnedReversed1() { // Arrange var sut = new Reversed1FileSearcher(_mock.Object); // Act var result = await sut.GetFilePaths("c:\\"); // Assert Assert.Equal(result.First(), "t.dat\\ra\\bla\\f"); } [Fact] public async Task GetFilePaths_AllAction_ReturnedReversed2() { // Arrange var sut = new Reversed2FileSearcher(_mock.Object); // Act var result = await sut.GetFilePaths("c:\\"); // Assert Assert.Equal(result.First(), "tad.t\\ar\\alb\\f"); } } }
db013af42e63e449803a0b23908f5e80021ed0d1
[ "C#" ]
12
C#
VolcOne/TestTask
52caabc7e255c07c83b26bd53cda0ecefeeb7198
2d139cf422c981fc6bf36ce48b9c6211eebb293e
refs/heads/main
<file_sep>const todoReducer = (state = [], action) => { if (action.type === "ADD_ITEM") { return [...state, action.payload]; } else if (action.type === "REMOVE_ITEM") { return state.filter((item, index) => index !== action.payload); } else if (action.type === "LOAD_TODO") { return action.payload.slice(0, 5); } /* fetch("https://jsonplaceholder.typicode.com/todos/") .then((res) => res.json()) .then((todos) => { return todos; }); //here fetch is asyn thus code moves to return state, within the time fetch executes, thus well use thunk // return action.payload.slice(0, 5); } */ return state; }; export default todoReducer; <file_sep>//using State hook ,which returns current state of varibles import { useState } from "react"; var Box = () => { var [count, setCount] = useState(0); return ( <div> <button onClick={() => { setCount((count += 1)); }} >{count}</button> </div> ); }; export default Box; <file_sep>import React from "react"; import './index.css'; function App() { return( <div className="App"> <div className="Instructions"> <h3>INSTRUCTIONS</h3> <li>build a container</li> <li>create a seperate function and use it as a component</li> <li>pass props "calory and food" and call it to main component</li> </div> <h1>CALORIE READ ONLY</h1> <div className="container"> <card title= "PIZZA" calorie="150"/> <card title="<NAME>" calorie="250"/> <card title="NOODLES" calorie="120"/> <card title="WAFFLES" calorie="80"/> <card title="MOMOS" calorie="50"/> <card title="CAKES" calorie="180"/> </div> </div> ); } <file_sep>import "./styles.css"; import "tailwindcss/tailwind.css"; export default function App() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>tailwind</h2> <figure class="bg-gray-100 rounded-xl p-8"> <img class="w-32 h-32 rounded-full" src="/sarah-dayan.jpg" alt="" width="384" height="512" /> <div class="pt-6 space-y-4"> <blockquote> <p class="text-lg"> “Tailwind CSS is the only framework that I've seen scale on large teams. It’s easy to customize, adapts to any design, and the build size is tiny.” </p> </blockquote> <figcaption> <div><NAME></div> <div>Staff Engineer, Algolia</div> </figcaption> </div> </figure> </div> ); } <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>resume two</title> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet" /> <style> .wrap { border: 2px solid black; margin: 10px; } .container1 { background-color: peachpuff; height: 210px; padding: 25px; } .left { margin: 9px; float: left; font-family: "Times New Roman", Times, serif; font-size: 20px; } .info { float: right; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 16px; margin: 9px; } #image { height: 120px; width: 190px; margin-bottom: 10px; } .container2 { background-color: linen; padding: 24px; width: ; height: 900px; display: grid; grid-template-areas: "aside box1"; } .aside { font-size: 29px; font-family: "Lobster", cursive; color: coral; float: left; width: 100%; margin: 8px; padding: 5px; /* border:2px solid blue; */ } .box1 { font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif; margin-left: 20px; float: right; width: 75%; border: 2px solid brown; border-radius: 8px; margin: 6px; padding: 18px; margin-left: 190px; } ul { list-style-type: none; /* margin:4px; */ } li a { text-decoration: none; color: black; } a:hover { color: blue; text-shadow: 1em; text-shadow: aqua; } </style> </head> <body> <div class="wrap"> <div class="container1"> <div class="left"> <img id="image" src="images/pascal-bernardon-UHCu3qZ-tSQ-unsplash.jpg" /><br /> <b><NAME></b><br /> <EMAIL> </div> <div class="info"> <ul> <li><a href="<EMAIL>">EMAIL ID</a></li> <li><a href="https://github/rittika">GITHUB</a></li> <li><a href="https://ritikalinkedin.in">LINKEDIN</a></li> <li>contact me- 09364847299<br /></li> </ul> </div> </div> <div class="container2"> <div class="aside"><h3>Profile :</h3></div> <div class="box1"> I am a sophomore doing bachelor in technology - BTech focused in Information Technology Engineering. I have always been fascinated by science and technology. This led me to purse technology. I am a keen learner with basic knowledge of object oriented programming, front end development and coding. </div> <div class="aside"><h3>Experience :</h3></div> <div class="box1"> hehh Lorem ipsum dolor sit amet consectetur adilorem20 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolor corporis veritatis facilis voluptate fug Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia quasi omnis doloremque qui minima dolores atque cumque, excepturi error.it dolorum ipsa. pisicing elit. Illum, sunt!he </div> <div class="aside"><h3>Skills :</h3></div> <div class="box1"> <h4>Programming Languages</h4> C++,Python,HTML,CSS,JS <h4>Software</h4> Microsoft office,Wordpress,Git </div> <div class="aside"><h3>Education :</h3></div> <div class="box1"> <h4>High School:</h4> I did my high school from CBSE with aggregate: 9.8 CGPA <h4>College:</h4> I am doing my bachelors focused on Information Technology Engineering. </div> </div> </div> </body> </html> <file_sep>import Black from "./Black-card" import White from "./White-card" function odd(){ return ( <div className="odd"> <White> <Black> <White> <Black> <White> <Black> <White> <Black> </div> ); } export default odd;<file_sep>var card=(props)=>{ return ( <div className="card"> <h1 className="title">{{props.title}}</h1> </br> <h2 className="calorie">you have consumed-{props.calorie} calories today</h2> </div> ); } export default card; <file_sep>import React from "react"; import './App.css'; /* var withourjsx=React.createElement("hi",{ className:"text",} hellow world);*/ var withjsx = <h1>hello worldss</h1>;*/ function App() { /*return withourjsx;*/ return withjsx; } export default App; import React from "react"; import './App.css'; function App() { var a=1; var b=2; var title="page header"; var para="jndiocjnckdjcndi jnicdsjc jncisdcjsdcj"; var page={ title1:"anything", parag="cndijc cijdnc dmc", }; return ( <div> <h2>{title}</h2> <h3>{a}+{b}={a+b}</h3> <p>{para}</p> <h3>{page.title1.}> </div> ); } export default App; <file_sep> var btn=document.querySelector('button'); btn.addEventListener('click',async ()=>{ fetch('https://api.quotable.io/random') .then(res=>res.json()) .then(data=>console.log(data.content)); // return data; // console.log(data.content); // console.log(data); }) var btn2=document.getElementById("second"); btn2.addEventListener('click',async ()=>{ fetch('https://meme-api.herokuapp.com/gimme') .then(res=>res.json()) .then(data=>console.log(data.url)); })<file_sep>import "./styles.css"; import { useState, useEffect } from "react"; const App = () => { const [item, setItem] = useState(""); const [cal, setCal] = useState(""); const [showData, setShowData] = useState(""); const handleSubmit = (event) => { setShowData("show_data"); // setShowData(""); // console.log(`email:${email}`); // event.preventDefault(); }; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <label> <input type="text" value={item} name="item" placeholder="Item-name" onChange={(e) => setItem(e.target.value)} /> </label> <label> <input type="number" value={cal} name="cal" placeholder="Calorie-amount" onChange={(e) => setCal(e.target.value)} /> </label> <br /> <button onClick={(e) => handleSubmit(e)}>Add Item</button> {showData ? ( <div className="show"> {`${item} - you have consumed ${cal} calories`} <button id="del">Delete</button> <button id="ed">Edit</button> </div> ) : ( "" )} </div> ); }; export default App; <file_sep> var my_list = [{ QUESTION: "When did Indian constitution came in effect?", OPTION1: "1950", OPTION2: "1930", OPTION3: "1972", OPTION4: "1949", answer: document.querySelector('.ans1') }, { QUESTION: "Who is the current Minister of Foreign Affairs ?", OPTION1: "<NAME>", OPTION2: "<NAME>", OPTION3: "<NAME>", OPTION4: "<NAME>", answer: document.querySelector('.ans1') }, { QUESTION: "NEP 2020 was launched on?", OPTION1: "July 2020", OPTION2: "April 2020", OPTION3: "January 2021", OPTION4: "November 2019", answer: document.querySelector('.ans1') }, { QUESTION: "Which is highest civilian award in india?", OPTION1: "<NAME>", OPTION2: "<NAME>", OPTION3: "<NAME>", OPTION4: "<NAME>", answer: document.querySelector('.ans4') }, { QUESTION: "Who was India's first female governor?", OPTION1: "<NAME>", OPTION2: "<NAME>", OPTION3: "<NAME>", OPTION4: "<NAME>", answer: document.querySelector('.ans3') }, { QUESTION: "When is India army day celebrated?", OPTION1: "15 august", OPTION2: "15 january", OPTION3: "6 april", OPTION4: "14 october", answer: document.querySelector('.ans2') }, { QUESTION: "Which is largest forest state in india?", OPTION1: "Jharkhand", OPTION2: "Madhya pradesh", OPTION3: "Rajasthan", OPTION4: "Tripura", answer: document.querySelector('.ans2') }, { QUESTION: "India's largest dam is?", OPTION1: "<NAME>", OPTION2: "<NAME>", OPTION3: "<NAME>", OPTION4: "<NAME>", answer: document.querySelector('.ans1') }, { QUESTION: "How many times india won world cup?", OPTION1: "3", OPTION2: "2", OPTION3: "4", OPTION4: "1", answer: document.querySelector('.ans2') }, { QUESTION: "India's first supercomputer is?", OPTION1: "PARAM Siddhi-AI", OPTION2: "<NAME>", OPTION3: "Shivay-II", OPTION4: " Mihir", answer: document.querySelector('.ans2') }, ] var btn = document.querySelectorAll('#select'); var correct = 0; var wrong = 0; var x = 0; // console.log(correct,wrong,x); for (let j = 0; j < 4; j++) { btn[j].addEventListener('click', (stop) => { if (btn[j].innerHTML == my_list[x].answer.innerHTML) { my_list[x].answer.innerHTML = 'CORRECT ANSWER'; my_list[x].answer.style.color = 'green'; correct += 1; } else { btn[j].innerHTML = 'WRONG ANSWER'; btn[j].style.color = 'red'; wrong -= 1; } }); } var next = document.querySelector('.next'); var previous = document.querySelector('.previous'); var question = document.querySelector('.question'); var ans1 = document.querySelector('.ans1'); var ans2 = document.querySelector('.ans2'); var ans3 = document.querySelector('.ans3'); var ans4 = document.querySelector('.ans4'); next.addEventListener('click',()=>{ if(x<10){ x += 1; ans1.style.color = 'white'; ans2.style.color = 'white'; ans3.style.color = 'white'; ans4.style.color = 'white'; question.innerHTML = my_list[x].QUESTION; ans1.innerHTML = my_list[x].OPTION1; ans2.innerHTML = my_list[x].OPTION2; ans3.innerHTML = my_list[x].OPTION3; ans4.innerHTML = my_list[x].OPTION4; } else if(x==10 || x==9){ question.innerHTML = `YOUR TOTAL SCORE ${correct + wrong} out of 10`; ans1.innerHTML = `Total Correct points = ${correct} `; ans2.innerHTML = `Total Wrong points = ${wrong} `; ans4.style.display='none'; ans3.style.display='none'; ans3.style.visibility='hidden'; // quiz.style.width:50%; // document.getElementsByClassName("quiz").style.width="50%"; // document.getElementsByClassName("question").style.backgroundColor="yellow"; // question.style.backgroundColor="yellow"; } }); previous.addEventListener('click',()=>{ if(x>0){ x -= 1; question.innerHTML = my_list[x].QUESTION; ans1.innerHTML = my_list[x].OPTION1; ans2.innerHTML = my_list[x].OPTION2; ans3.innerHTML = my_list[x].OPTION3; ans4.innerHTML = my_list[x].OPTION4; ans3.style.backgroundColor = "black"; ans4.style.backgroundColor = "black"; ans3.style.color = "white"; ans1.style.color = "white"; ans2.style.color = "white"; ans4.style.color = "white"; } else if(x == 0){ window.location = "http://127.0.0.1:5502/Quiz/front.html"; } }); <file_sep># Devsnest uploading daily work here <file_sep>const submit = () => { return ( <div className="box"> <p>hello you1</p> </div> ); // console.log("submmitted"); }; export { submit }; <file_sep>https://github.com/rit-iika/Weather-App <file_sep>import React from "react"; import './index.css'; import card from "./components/card" function App() { var arr=[1,2,3,4,5,6]; return( <div className="App"> /* <card title= "title1"/> <card title= "title2"/> <card title= "title3"/> <card title= "title4"/> <card title= "title5"/> <ul> { arr.map((item,index)= <li key={index}>{item}</li> ) /*here a key is used bcoz virtual dom will compare elemnts } </ul> */ { arr.length>4? arr.map((item,index)=> <card key={index} title={item}/> ): <h1>this list is too small to display </h1> } </div> ); } export default App; <file_sep>var inpt=document.querySelector('input') var btn=document.querySelector('button') var list=document.querySelector('.todolist') var todos=[ { title:"homework", disc:"work work" }, { title:"mumma help", disc:"lets do it" } ] function loadTodo(){ todos.map(todo => { console.log(todo.title); console.log(todo); }) } loadTodo(); btn.addEventListener('click',()=>{ var newT=document.createElement('div'); newT.innerHTML=inpt.value; list.appendChild(newT) inpt.value="" // console.log(inpt.value); }) localStorage.setItem('todo',todos);<file_sep>// import React, { useState, useEffect } from "react"; const Card = ({ title, id, value, desc, deleteCard, cal }) => { return ( <div className="Card"> <div> <h2>Calories</h2> <h3>Item - {title}</h3> <p> {desc} is {value} cals </p> <button onClick={() => deleteCard(id)}>Delete</button> </div> </div> ); }; export default Card; <file_sep>import "bootstrap/dist/css/bootstrap.min.css"; import "./styles.css"; import { useState, useEffect } from "react"; export default function App() { const [place, setPlace] = useState(""); const [placeData, setPlaceData] = useState({}); const updatePlaceData = () => { fetch( `https://api.weatherapi.com/v1/forecast.json?key=b20b056187ad4060ac1181923210608&q=${place}` ) .then((res) => res.json()) .then((data) => { console.log(data); setPlaceData(data); }); }; return ( <div className="App"> <div className="container"> <h2>weather check</h2> <h5>enter your place and know the weather !</h5> <div className="row"> <div className="col-12 form"> <input type="text" placeholder="enter your place" value={place} onChange={(e) => setPlace(e.target.value)} /> <br /> <button className="btn btn-primary" onClick={updatePlaceData}> click here </button> </div> <div className="offset-md-4 col-10 col-md-4 weather"> <div className="card"> {/* <h3>place not found</h3>*/} {placeData.location ? ( <div className="city"> <img src={placeData.current.condition.icon} alt="" /> <div className="temp">{placeData.current.temp_c}°</div> {placeData.current.condition.text} <h2>{placeData.location.name}</h2> {/* <h2>{placeData.location.region}</h2> */} {/* <h2>{placeData.location.country}</h2> */} <div className="container"> <div className="row"> <div className="col"> <div className="title">humidity</div> <div className="data"> {placeData.current.humidity} <span className="unit">KMS</span> </div> </div> <div className="col"> <div className="title">wind speed</div> <div className="data"> {placeData.current.wind_kph} <span className="unit">%</span> </div> </div> <div className="col"> <div className="title">precipitation</div> <div className="data"> {placeData.current.precip_in} <span className="unit">%</span> </div> </div> </div> </div> </div> ) : ( <h2>place not found</h2> )} </div> </div> </div> </div> </div> ); } <file_sep>created a todo-list using REACT with middlewares like logger and thunk. link : https://5rfwu.csb.app/ <file_sep>var Image=()=>{ return ( <img src="react-meme1_(1).png"/> ) } var Card=()=>{ return( <div className="card" > <h2> this is a card </h2> <Image/> <p>this is card</p> </div> ); } export default Card;
59bc077cff70c8544237be6aac4b24b12ccaa0fc
[ "JavaScript", "HTML", "Markdown" ]
20
JavaScript
rit-iika/Devsnest-FrontEnd
2becef5c3d63d30e21db563467a7ba85f0b956c9
4bdd7fd6324cb279ed88d3a57989d45edb8272df
refs/heads/master
<file_sep>public class ShiftPro { protected int[][] grid; private int gridDimension; private int points = 0; int flag = 0; private boolean hasshift = false; public ShiftPro(int[][] grid, int gridDimension) { this.gridDimension = gridDimension; this.grid = grid; } public static void main(String args[]) { System.out.println("HEllo"); int before[][] = { {2, 2, 0, 4}, {5, 5, 0, 8,}, {9, 5, 9, 9,}, {0, 0, 0, 16,}, }; ShiftPro me = new ShiftPro(before, 4); // me.pusher(); // printTable(me.pusher()); System.out.println("Flag" + me.can_move()); me.mymovtedown(); // printTable(me.Left(before)); printTable(me.grid); } public static void printTable(int[][] table) { for (int i = 0; i < table.length; i++) { for (int j = 0; j < table.length; j++) { System.out.print(String.format("%4s", table[i][j])); } System.out.println(); } } /** * this method will move the tiles into left * <p> * take note that: * <ul> * <li>if there is a 0 tile skip it</li> * <li>if the grid cell can move, move them into left</li> * <li>after moving if two grid cell stay after each other and have different value, just stop moving</li> * <li>if two tile have the same value, merge them and add point</li> * </ul> * </p> * * @return return the grid after normalization */ public void movetoright() { rotateLeft(); rotateLeft(); pusher(); rotateRight(); rotateRight(); } public void movedown() { rotateRight(); pusher(); rotateLeft(); } public final int[][] pusher() { //from right to left check none value zero for pushing to next cell for (int row = 0; row < gridDimension; ++row) { for (int col = 1; col < gridDimension; ++col) { int currentCellValue = grid[row][col]; if (currentCellValue == 0) { continue; } //start to the left if its not the first cell value and one cell left has 0 value int preCellPosition = col - 1; int lastMergePosition = 0; for (; preCellPosition > lastMergePosition && grid[row][preCellPosition] == 0; ) { --preCellPosition; } int preCellValue = grid[row][preCellPosition]; if (preCellPosition == col) { } else if (preCellValue == 0) { grid[row][preCellPosition] = currentCellValue; grid[row][col] = 0; } else if (preCellValue == currentCellValue) { mergeColumns(row, col, preCellPosition); } else if (preCellValue != currentCellValue && preCellPosition + 1 != col) { grid[row][preCellPosition + 1] = grid[row][col]; grid[row][col] = 0; } } } return grid; } /** * if two cell are the same and there is a movement toward them * they merge and the acquired point is added to the system * * @param row * @param col * @param previousPosition */ private void mergeColumns(int row, int col, int previousPosition) { //The user's score is incremented whenever two tiles combine, by the //value of the new tile. grid[row][previousPosition] *= 2; grid[row][col] = 0; points += grid[row][previousPosition]; } /** * provide new acquired point * * @return */ public int getPoints() { return points; } public int getflag() { return this.flag; } /** * can get call * to return the new acquired grid * * @return */ public int[][] newGrid() { return grid; } /** * This method will iterate over the grid and * rotate the whole grid into the right by 90 degrees * * @return */ public int[][] rotateRight() { int[][] rotatedBoard = new int[gridDimension][gridDimension]; for (int i = 0; i < gridDimension; ++i) { for (int j = 0; j < gridDimension; ++j) { rotatedBoard[i][j] = grid[gridDimension - j - 1][i]; } } grid = rotatedBoard; return grid; } /** * This method will iterate over the grid and * rotate the whole grid into the left by 90 degrees * * @return */ public int[][] rotateLeft() { int[][] rotatedBoard = new int[gridDimension][gridDimension]; for (int i = 0; i < gridDimension; ++i) { for (int j = 0; j < gridDimension; ++j) { rotatedBoard[gridDimension - j - 1][i] = grid[i][j]; } } grid = rotatedBoard; return grid; } ////////////my left public int[][] Left(int[][] grid) { for (int y = 1; y <= grid[0].length - 1; y++) { for (int x = 0; x >= grid.length; x++) { while (true) { //When two number match if (grid[x][y] == grid[x][y - 1]) { grid[x][y - 1] = grid[x][y] + grid[x][y - 1]; grid[x][y] = 0; break; } //isLineFull full=new isLineFull(); if (grid[x][y - 1] == 0) { grid[x][y - 1] = grid[x][y]; grid[x][y] = 0; } break; } } } return grid; } ///////////////////////////////// //C implementnation //////////////////////////// public boolean is_outside(int x, int y) { return (x < 0 || x >= grid.length || y < 0 || y >= this.grid[0].length); } ////////////// my down shift ////////// public void myDownShift() { for (int x = 0; x < grid.length; ++x) { for (int y = grid[0].length-1 ; y >= 0; --y) { // Empty slots dont move if (grid[y][x] == 0) { // continue; } int newY = y; int nextY = y + 1; while (grid[nextY][x] == 0 && !is_outside(x, nextY)) { newY = nextY; ++nextY; } if (newY != y) { hasshift = true; } int value = grid[y][x]; grid[y][x] = 0; grid[newY][x] = value; } } } public void mymovedown() { //first for loop is for shifting all the elements down //for each element on the gameboard apart from the top row for (int i = 1; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { // if the element isn't 0 then if (grid[i][j] != 0) { // for every element above the current element starting from the top for (int k = 0; k < i; k++) { //if the element is 0 then if (grid[k][j] == 0) { //move the current element to the position of the 0 element above it grid[k][j] = grid[i][j]; grid[i][j] = 0; } } } } } //second for loop is for combining numbers //for each element in the array apart from the top row for (int i = 1; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { // if the current element is the same as the one above it if (grid[i][j] == grid[i - 1][j]) { //combine the two grid[i - 1][j] = grid[i][j] * 2; //for all other elements below it for (int k = i; k < grid.length; k++) { //if it is the bottom row if (k == grid.length - 1) { //add a zero to the bottom row grid[k][j] = 0; } else { //otherwise shift the other elements to the position above grid[k][j] = grid[k + 1][j]; grid[k + 1][j] = 0; } } } } } } public void moveUPward(){ //first for loop is for shifting all the elements down //for each element on the gameboard apart from the left column for(int i = 0; i < grid.length; i++){ for(int j = 1; j < grid[0].length; j++){ // if the element is 0 then move to the next one if(grid[i][j] != 0){ // for every element to the right of the current element starting from the left for (int k = 0; k < j; k++){ //if the element is 0 then if (grid[i][k] == 0){ //move the current element to the position of the 0 element to the left of it grid[i][k] = grid[i][j]; grid[i][j] = 0; } } } } } //second for loop is for combining numbers //for each element in the array apart from the top row for(int i = 0; i < grid.length; i++){ for (int j = 1; j < grid[0].length; j++){ //if the current element is equal to the element on the left if (grid[i][j] == grid[i][j-1]){ //combine the elements grid[i][j-1] = grid[i][j] * 2; //for each element to the right of current element for (int k = j; k < grid[0].length; k++){ //if the far right element if (k == grid[0].length - 1){ //set equal to 0 grid[i][k] = 0; }else{ //if not the far right element set equal to the element on the right grid[i][k] = grid[i][k+1]; //and set the element on the right equal to 0 grid[i][k+1] = 0; } } } } } } public void mymovtedown(){ //first for loop is for shifting all the elements down //for each element on the gameboard apart from the bottom row for(int i = this.grid.length-2; i >=0; i--){ for(int j = 0; j < this.grid[0].length; j++){ // if the element isn't 0 then if(grid[i][j] != 0){ // for every element below the current element starting from the bottom for (int k = this.grid.length-1; k >= i; k--){ //if the element is 0 then if (grid[k][j] == 0){ //move the current element to the position of the 0 element below it grid[k][j] = grid[i][j]; grid[i][j] = 0; } } } } } //second for loop is for combining numbers //for each element in the array apart from the bottom row for(int i = this.grid.length-2; i >= 0; i--){ for (int j = 0; j < this.grid[0].length; j++){ // if the current element is the same as the one below it if (grid[i][j] == grid[i+1][j]){ //combine the two grid[i+1][j] = grid[i][j] * 2; //for all other elements above it for (int k = i; k >= 0; k--){ //if it is the top row if (k == 0){ //add a zero to the top row grid[k][j] = 0; }else{ //otherwise shift the other elements to the position below grid[k][j] = grid[k-1][j]; grid[k-1][j] = 0; } } } } } } public void movetorigth(){ //first for loop is for shifting all the elements down //for each element on the gameboard apart from the right column for(int i = 0; i < this.grid.length; i++){ for(int j = this.grid[0].length - 2; j >= 0; j--){ // if the element is 0 then move to the next one if(this.grid[i][j] != 0){ // for every element to the right of the current element starting from the right for (int k = this.grid[0].length-1; k > j; k--){ //if the element is 0 then if (this.grid[i][k] == 0){ //move the current element to the position of the 0 element to the right of it this.grid[i][k] = this.grid[i][j]; this.grid[i][j] = 0; } } } } } //second for loop is for combining numbers //for each element in the array apart from the right column for(int i = 0; i < this.grid.length; i++){ for (int j = this.grid[0].length-2; j >= 0; j--){ //if the current element is equal to the element on the right if (this.grid[i][j] == this.grid[i][j+1]){ //combine the elements this.grid[i][j+1] = this.grid[i][j] * 2; //for each element to the left of current element for (int k = j; k >= 0; k--){ //if the far left element if (k == 0){ //set equal to 0 this.grid[i][k] = 0; }else{ //if not the far left element set equal to the element on the left this.grid[i][k] = this.grid[i][k-1]; //and set the element on the left equal to 0 this.grid[i][k-1] = 0; } } } } } } boolean can_move() { for(int x = 0; x < this.grid.length; ++x) { for(int y = 0; y < this.grid[0].length; ++y) { // Only need 1 empty space to move if(this.grid[y][x] == 0) { return true; } // Neighbor check int value = this.grid[y][x]; int north = get(x, y - 1); if(value == north) { return true; } int south = get(x, y + 1); if(value == south) { return true; } int east = get(x - 1, y); if(value == east) { return true; } int west = get(x + 1, y); if(value == west) { return true; } } } // If we made it through, there are no empty slots or // slots with equal values next to it return false; } int get(int x, int y) { if(is_outside(x, y)) { return -1; } return this.grid[y][x]; } }
9255533908bcec3e4a2386cb500757cdba0eb84a
[ "Java" ]
1
Java
boatengfrankenstein/ShiftPro
685b39e3e2d5c9fd46a2d3de78478c6146a4fc83
720460e74b8c186eda50a43ab0152cae2914428a
refs/heads/master
<file_sep>package com.hatiolab.blecalculator.widget; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.hatiolab.blecalculator.MainActivity; import com.hatiolab.blecalculator.Util; import com.hatiolab.blecalculator.MainActivity.ViewHolder; import com.hatiolab.blecalculator.model.Beacon; import com.hatiolab.blecalculator.model.Position; import com.hatiolab.blecalculator.model.Scene; public class BleList extends BaseAdapter{ private ArrayList<BluetoothDevice> devices; // private ArrayList<Integer> RSSIs; private LayoutInflater inflater; private ArrayList<Beacon> beaconSetting; private HashMap<String, Double> standardDeviation = new HashMap<String, Double>(); private TextView txtLocation; private SceneFirebase sceneFirebase; private ArrayList<HashMap<String, ArrayList<Double>>> beaconRssi; public BleList(Context mContext, TextView location, SceneFirebase firebase) { super(); devices = new ArrayList<BluetoothDevice>(); // RSSIs = new ArrayList<Integer>(); beaconSetting = new ArrayList<Beacon>(); beaconRssi = new ArrayList<HashMap<String, ArrayList<Double>>>(); inflater = ((Activity) mContext).getLayoutInflater(); txtLocation = location; sceneFirebase = firebase; } public BleList(Context mContext, SceneFirebase firebase) { super(); devices = new ArrayList<BluetoothDevice>(); // RSSIs = new ArrayList<Integer>(); beaconSetting = new ArrayList<Beacon>(); beaconRssi = new ArrayList<HashMap<String, ArrayList<Double>>>(); inflater = ((Activity) mContext).getLayoutInflater(); sceneFirebase = firebase; } public void addDevice(BluetoothDevice device, int rssi, byte[] scanRecord, ArrayList<Scene> sceneBeacon, Long now, Long rssiUpdate) { Beacon beacon; if(now - rssiUpdate < 10000) { if (!devices.contains(device)) { int avgRssi = Util.avgFilter(1, 0, rssi); beacon = Util.recordParser(device, avgRssi, scanRecord, sceneBeacon); if(beacon != null) { beacon.setRssiCount(2); devices.add(device); beaconSetting.add(beacon); } } else { int avgRssi = Util.avgFilter(beaconSetting.get(devices.indexOf(device)).getRssiCount(), beaconSetting.get(devices.indexOf(device)).getRssi(), rssi); beacon = Util.recordParser(device, avgRssi, scanRecord, sceneBeacon); if(beacon != null) { beacon.setRssiCount(beaconSetting.get(devices.indexOf(device)).getRssiCount() + 1); beaconSetting.set(devices.indexOf(device), beacon); } } } else { if (!devices.contains(device)) { int lpfRssi = Util.lpfilter(0.9, 0, rssi); beacon = Util.recordParser(device, lpfRssi, scanRecord, sceneBeacon); if(beacon != null) { devices.add(device); beaconSetting.add(beacon); } } else { int lpfRssi = Util.lpfilter(0.9, beaconSetting.get(devices.indexOf(device)).getRssi(), rssi); beacon = Util.recordParser(device, lpfRssi, scanRecord, sceneBeacon); if(beacon != null) { beacon.setRssiCount(beaconSetting.get(devices.indexOf(device)).getRssiCount()); beaconSetting.set(devices.indexOf(device), beacon); } } } } public void clear() { devices.clear(); } @Override public int getCount() { return devices.size(); } @Override public Object getItem(int position) { return devices.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); convertView = inflater.inflate( android.R.layout.two_line_list_item, null); viewHolder.deviceName = (TextView) convertView .findViewById(android.R.id.text1); viewHolder.deviceRssi = (TextView) convertView .findViewById(android.R.id.text2); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String deviceAddress = devices.get(position).getAddress(); String deviceName = devices.get(position).getName(); int rssi = beaconSetting.get(position).getRssi(); int txPower = beaconSetting.get(position).getTxPower(); ArrayList<Double> rssiValue = new ArrayList<Double>(); HashMap<String, ArrayList<Double>> addressToRssi = new HashMap<>(); rssiValue.add((double) rssi); boolean bool = true; if(beaconRssi.size() > 0) { for(int i = 0 ; i < beaconRssi.size() ; i++) { if(beaconRssi.get(i).containsKey(deviceAddress)) { beaconRssi.get(i).get(deviceAddress).add((double) rssi); bool = false; break; } } if(bool) { addressToRssi.put(deviceAddress, rssiValue); beaconRssi.add(addressToRssi); } } else { addressToRssi.put(deviceAddress, rssiValue); beaconRssi.add(addressToRssi); } // descendingSort(); // Beacon[] test = new Beacon[4]; // if(beaconSetting.size() >= 4) { // test[0] = beaconSetting.get(0); // test[1] = beaconSetting.get(1); // test[2] = beaconSetting.get(2); // test[3] = beaconSetting.get(3); // // int k = 3; // sequence length // // combination(test, k); // } if(beaconRssi.get(position).get(deviceAddress).size() > 500) { double result = Util.standardDeviation(beaconRssi.get(position).get(deviceAddress)); standardDeviation.put(deviceAddress, result); double avg = Util.mean(beaconRssi.get(position).get(deviceAddress)); double distance = Util.calculateDistance(txPower, avg); sceneFirebase.setStandardDeviation(deviceAddress, avg, distance, result); beaconRssi.get(position).get(deviceAddress).clear(); } String deviceInfo = deviceAddress + " / Distance : " + Util.decimalScale(String.valueOf(Util.calculateDistance(txPower, rssi)), 3) + " / beaconSetting Distance : " + Util.decimalScale(String.valueOf(Util.calculateDistance(beaconSetting.get(position).getTxPower(), beaconSetting.get(position).getRssi())), 3) + " / count : " + beaconSetting.get(position).getRssiCount() + " / txPower : " + txPower + " / SRSSI : " + beaconSetting.get(position).getRssi(); viewHolder.deviceName.setText(deviceAddress != null && deviceAddress.length() > 0 ? deviceInfo : "알 수 없는 장치"); viewHolder.deviceRssi.setText(String.valueOf(rssi)); return convertView; } } <file_sep>package com.hatiolab.blecalculator; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import org.apache.commons.math3.fitting.leastsquares.LeastSquaresOptimizer.Optimum; import org.apache.commons.math3.fitting.leastsquares.LevenbergMarquardtOptimizer; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.apache.commons.math3.linear.SingularMatrixException; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.telephony.TelephonyManager; import android.view.View; import android.view.animation.Animation; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.androidplot.xy.SimpleXYSeries; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.hatiolab.blecalculator.kalman.jkalman.JKalman; import com.hatiolab.blecalculator.madgwickAHRS.MadgwickAHRS; import com.hatiolab.blecalculator.model.Beacon; import com.hatiolab.blecalculator.model.Position; import com.hatiolab.blecalculator.model.Scene; import com.hatiolab.blecalculator.trilateration.LinearLeastSquaresSolver; import com.hatiolab.blecalculator.trilateration.NonLinearLeastSquaresSolver; import com.hatiolab.blecalculator.trilateration.TrilaterationFunction; import com.hatiolab.blecalculator.widget.BleList; import com.hatiolab.blecalculator.widget.CustomProgressDialog; import com.hatiolab.blecalculator.widget.SceneFirebase; public class MainActivity extends Activity implements SensorEventListener { boolean scanning = false; private static final int REQUEST_ENABLE_BT = 1; private BluetoothManager bluetoothManager; // 블루투스 매니저 // 블루트스 기능을 총괄적으로 관리함. private BluetoothAdapter bluetoothAdapter; // 블루투스 연결자 // 블루투스를 스켄하거나, 페어링된장치목록을 읽어들일 수 있습니다. // 이를 바탕으로 블루투스와의 연결을 시도할 수 있습니다. private SensorManager mSensorManager; private Sensor accSensor, gyroSensor, magSensor; private long lastUpdate; private long rssiUpdate; SimpleXYSeries seriesAccx; SimpleXYSeries seriesAccy; SimpleXYSeries seriesAccz; private static final int HISTORY_SIZE = 500; private float[] gyro = new float[3]; private float[] magnet = new float[3]; private float[] accel = new float[3]; DecimalFormat m_format; private float[] gravity_data = new float[3]; private float[] linear_acceleration = new float[3]; MadgwickAHRS madgwickAHRS = new MadgwickAHRS(0.01f, 0.041f); private Timer madgwickTimer = new Timer(); double lpPitch=0,lpRpll=0,lpYaw=0; private SceneFirebase sceneFirebase; private String phoneUUid = ""; public static class ViewHolder { public TextView deviceName; public TextView deviceRssi; } Button button;// 버튼 TextView location;//, accelerometer, uuid, madgPitch, madgRoll, madgYaw, tvStandardDeviation, gravity; ListView listView;// 리스트뷰 객체 BleList bleList = null;// 리스트 어댑터 private ArrayList<BluetoothDevice> devices; private ArrayList<Beacon> beaconSetting; private Position avgPosition = new Position(); private ArrayList<Scene> sceneBeacon = new ArrayList<Scene>(); private Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Firebase.setAndroidContext(this); dialog = CustomProgressDialog.initDialog(this, R.style.CustomProgressDialog, "", R.string.loading); devices = new ArrayList<BluetoothDevice>(); beaconSetting = new ArrayList<Beacon>(); ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.BLUETOOTH }, 1); bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) { // 블루투스를 지원하지 않거나 켜져있지 않으면 장치를끈다. // Toast.makeText(this, "블루투스를 켜주세요", Toast.LENGTH_SHORT).show(); // finish(); on(); } //센서 매니저 얻기 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //자이로스코프 센서(회전) gyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); //엑셀러로미터 센서(가속) accSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); magSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mSensorManager.registerListener(this, accSensor, 0);//every 5ms mSensorManager.registerListener(this, gyroSensor, 0); mSensorManager.registerListener(this, magSensor, 0); m_format = new DecimalFormat(); m_format.applyLocalizedPattern("0.##"); location = (TextView) findViewById(R.id.location); // accelerometer = (TextView) findViewById(R.id.accelerometer); // gravity = (TextView) findViewById(R.id.gravity); // tvStandardDeviation = (TextView) findViewById(R.id.standardDeviation); // uuid = (TextView) findViewById(R.id.uuid); // madgPitch = (TextView) findViewById(R.id.madgPitch); // madgRoll = (TextView) findViewById(R.id.madgRoll); // madgYaw = (TextView) findViewById(R.id.madgYaw); sceneFirebase = new SceneFirebase("260"); getScene(sceneFirebase.getFirebase()); // 리스트뷰 설정 bleList = new BleList(MainActivity.this, location, sceneFirebase); bleList = new BleList(MainActivity.this, sceneFirebase); listView = (ListView) findViewById(R.id.listView); listView.setAdapter(bleList); // 버튼설정 button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!scanning) { bluetoothAdapter.startLeScan(leScanCallback); lastUpdate = System.currentTimeMillis(); rssiUpdate = System.currentTimeMillis(); madgwickTimer.scheduleAtFixedRate(new DoMadgwick(), 1000, 1000); } else { madgwickTimer.notify(); bluetoothAdapter.stopLeScan(leScanCallback); bleList.clear(); bleList.notifyDataSetChanged(); } scanning = !scanning; } }); seriesAccx = new SimpleXYSeries("accx"); seriesAccx.useImplicitXVals(); seriesAccy = new SimpleXYSeries("accy"); seriesAccy.useImplicitXVals(); seriesAccz = new SimpleXYSeries("accz"); seriesAccz.useImplicitXVals(); phoneUUid = getDevicesUUID(this); } //정확도에 대한 메소드 호출 (사용안함) public void onAccuracyChanged(Sensor sensor, int accuracy) { } //센서값 얻어오기 public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { System.arraycopy(sensorEvent.values, 0, accel, 0, 3); } else if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) { System.arraycopy(sensorEvent.values, 0, gyro, 0, 3); } else if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { System.arraycopy(sensorEvent.values, 0, magnet, 0, 3); } } // 주기 설명 // SENSOR_DELAY_UI 갱신에 필요한 정도 주기 // SENSOR_DELAY_NORMAL 화면 방향 전환 등의 일상적인 주기 // SENSOR_DELAY_GAME 게임에 적합한 주기 // SENSOR_DELAY_FASTEST 최대한의 빠른 주기 //리스너 등록 protected void onResume() { super.onResume(); mSensorManager.registerListener(this, gyroSensor,SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, accSensor,SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, magSensor,SensorManager.SENSOR_DELAY_GAME); } //리스너 해제 protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } // 스켄 이후 장치 발견 이벤트 private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { Beacon beacon; Long now = System.currentTimeMillis(); bleList.addDevice(device, rssi, scanRecord, sceneBeacon, now, rssiUpdate); bleList.notifyDataSetChanged(); if(now - rssiUpdate < 10000) { if (!devices.contains(device)) { int avgRssi = Util.avgFilter(1, 0, rssi); beacon = Util.recordParser(device, avgRssi, scanRecord, sceneBeacon); if(beacon != null) { beacon.setRssiCount(2); devices.add(device); beaconSetting.add(beacon); } } else { int avgRssi = Util.avgFilter(beaconSetting.get(devices.indexOf(device)).getRssiCount(), beaconSetting.get(devices.indexOf(device)).getRssi(), rssi); beacon = Util.recordParser(device, avgRssi, scanRecord, sceneBeacon); if(beacon != null) { beacon.setRssiCount(beaconSetting.get(devices.indexOf(device)).getRssiCount() + 1); beaconSetting.set(devices.indexOf(device), beacon); } } } else { if (!devices.contains(device)) { int lpfRssi = Util.lpfilter(0.9, 0, rssi); beacon = Util.recordParser(device, lpfRssi, scanRecord, sceneBeacon); if(beacon != null) { devices.add(device); beaconSetting.add(beacon); } } else { int lpfRssi = Util.lpfilter(0.9, beaconSetting.get(devices.indexOf(device)).getRssi(), rssi); beacon = Util.recordParser(device, lpfRssi, scanRecord, sceneBeacon); if(beacon != null) beaconSetting.set(devices.indexOf(device), beacon); } } } }; public void on() { if (!bluetoothAdapter.isEnabled()) { Intent turnOnIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT); Toast.makeText(getApplicationContext(), "Bluetooth turned on", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Bluetooth is already on", Toast.LENGTH_LONG).show(); } } private String getDevicesUUID(Context mContext){ final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final String tmDevice, tmSerial, androidId; tmDevice = "" + tm.getDeviceId(); tmSerial = "" + tm.getSimSerialNumber(); androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode()); String deviceId = deviceUuid.toString(); return deviceId; } class DoMadgwick extends TimerTask { public void run() { Long now = System.currentTimeMillis(); madgwickAHRS.SamplePeriod = (now - lastUpdate) / 1000.0f; lastUpdate = now; madgwickAHRS.Update(gyro[0], gyro[1], gyro[2], accel[0], accel[1], accel[2], magnet[0], magnet[1], magnet[2]); if (seriesAccx.size() > HISTORY_SIZE) { seriesAccx.removeFirst(); seriesAccy.removeFirst(); seriesAccz.removeFirst(); } // add the latest history sample: lpPitch = lpPitch * 0.2 + madgwickAHRS.MadgPitch * 0.8; lpRpll = lpRpll * 0.2 + madgwickAHRS.MadgRoll * 0.8; lpYaw = lpYaw * 0.2 + madgwickAHRS.MadgYaw * 0.8; seriesAccx.addLast(null, lpPitch); seriesAccy.addLast(null, lpRpll); seriesAccz.addLast(null, lpYaw); ArrayList<Beacon> beaconsPosition = new ArrayList<Beacon>(); beaconsPosition.addAll( beaconSetting ); beaconsPosition = Util.descendingSort(beaconsPosition); if(beaconsPosition.size() >= 4) { double[][] positions = new double[][] { { beaconsPosition.get(0).getBeaconX() / 100, beaconsPosition.get(0).getBeaconY() / 100 }, { beaconsPosition.get(1).getBeaconX() / 100, beaconsPosition.get(1).getBeaconY() / 100 }, { beaconsPosition.get(2).getBeaconX() / 100, beaconsPosition.get(2).getBeaconY() / 100 }, { beaconsPosition.get(3).getBeaconX() / 100, beaconsPosition.get(3).getBeaconY() / 100 } }; double[] distances = new double[] { Util.calculateDistance(beaconsPosition.get(0).getTxPower(), beaconsPosition.get(0).getRssi()), Util.calculateDistance(beaconsPosition.get(1).getTxPower(), beaconsPosition.get(1).getRssi()), Util.calculateDistance(beaconsPosition.get(2).getTxPower(), beaconsPosition.get(2).getRssi()), Util.calculateDistance(beaconsPosition.get(3).getTxPower(), beaconsPosition.get(3).getRssi()) }; NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(new TrilaterationFunction(positions, distances), new LevenbergMarquardtOptimizer()); Optimum optimum = solver.solve(); // the answer double[] centroid = optimum.getPoint().toArray(); avgPosition.setCenterX(centroid[0] * 100); avgPosition.setCenterY(centroid[1] * 100); // testResults(expectedPosition, 0.01, optimum, x); } try { runOnUiThread(new Runnable() { public void run() { final float alpha = (float) 0.8; gravity_data[0] = alpha * gravity_data[0] + (1 - alpha) * accel[0]; gravity_data[1] = alpha * gravity_data[1] + (1 - alpha) * accel[1]; gravity_data[2] = alpha * gravity_data[2] + (1 - alpha) * accel[2]; linear_acceleration[0] = accel[0] - gravity_data[0]; linear_acceleration[1] = accel[1] - gravity_data[1]; linear_acceleration[2] = accel[2] - gravity_data[2]; // gravity.setText("X : " + m_format.format(linear_acceleration[0]) + " / Y : " + m_format.format(linear_acceleration[1]) + " / Z : " + m_format.format(linear_acceleration[2])); // accelerometer.setText("X : " + m_format.format(accel[0]) + " / Y : " + m_format.format(accel[1]) + " / Z : " + m_format.format(accel[2])); location.setText("X : " + avgPosition.getCenterX() + " / Y : " + avgPosition.getCenterY()); } }); sceneFirebase.setPosition(avgPosition.getCenterX(), avgPosition.getCenterY(), Math.toRadians(madgwickAHRS.MadgPitch), Math.toRadians(madgwickAHRS.MadgRoll), Math.toRadians(madgwickAHRS.MadgYaw), phoneUUid); } catch (Exception e) { } } } public void getScene(Firebase myFirebaseRef) { myFirebaseRef.child("260").child("beacons").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { if(snapshot.getValue() != null) { for (DataSnapshot postSnapshot: snapshot.getChildren()) { Scene post = postSnapshot.getValue(Scene.class); post.setBeaconId(postSnapshot.getKey()); sceneBeacon.add(post); } } dialog.dismiss(); } @Override public void onCancelled(FirebaseError error) { } }); } private void testResults(double[] expectedPosition, final double delta, Optimum optimum, RealVector x) { double[] calculatedPosition = optimum.getPoint().toArray(); int numberOfIterations = optimum.getIterations(); int numberOfEvaluations = optimum.getEvaluations(); StringBuilder output = new StringBuilder("expectedPosition: "); for (int i = 0; i < expectedPosition.length; i++) { output.append(expectedPosition[i]).append(" "); } output.append("\n"); output.append("linear calculatedPosition: "); double[] linearCalculatedPosition = x.toArray(); for (int i = 0; i < linearCalculatedPosition.length; i++) { output.append(linearCalculatedPosition[i]).append(" "); } output.append("\n"); output.append("non-linear calculatedPosition: "); for (int i = 0; i < calculatedPosition.length; i++) { output.append(calculatedPosition[i]).append(" "); } output.append("\n"); output.append("numberOfIterations: ").append(numberOfIterations).append("\n"); output.append("numberOfEvaluations: ").append(numberOfEvaluations).append("\n"); try { RealVector standardDeviation = optimum.getSigma(0); output.append("standardDeviation: ").append(standardDeviation).append("\n"); RealMatrix covarianceMatrix = optimum.getCovariances(0); output.append("covarianceMatrix: ").append(covarianceMatrix).append("\n"); } catch (SingularMatrixException e) { System.err.println(e.getMessage()); } System.out.println(output.toString()); // expected == calculated? for (int i = 0; i < calculatedPosition.length; i++) { // assertEquals(expectedPosition[i], calculatedPosition[i], delta); } } }
f4548f82e158dc02d2c382ef533f0db11c569d60
[ "Java" ]
2
Java
jyp220/blecalculator
5f5be810f5f1be9886ad31231363e06685c9b81d
60456d1e3846bd03b4c26e53f037219c43c050da
refs/heads/master
<file_sep>from django.urls import path from .views import HomeView , EntryView urlpatterns=[ path('home/',HomeView.as_view(),name='blog-home'), path('entry/<int:pk>/',EntryView.as_view(),name="entry-detail") ]<file_sep># Blog- A Simple Blog with Django <file_sep>from django.shortcuts import render from django.views.generic import ListView , DetailView from .models import Entry class HomeView(ListView): model=Entry template_name="entries/index.html" context_object_name="blog_entries" class EntryView(DetailView): model=Entry template_name="entries/entry_details.html" class CreateEntryView(object): model=Entry template_name="entries/create_entry.html" fields=['title','text']
685a1904ea1502059f1f71de2202e8008092052e
[ "Markdown", "Python" ]
3
Python
nirajandata/Blog-
31507766a02392a23e29a4d6b7c53f4e6beedfa8
af300de6e09c8674f970021f50d968a6cda33b17
refs/heads/master
<repo_name>orioltf/urslides<file_sep>/index.php <?php define ("APP_PATH", dirname(__FILE__)); define ("SLIDES_PATH", APP_PATH . "/slides/"); function populateArryOfFiles($dirName, &$filesArray) { if ( !is_dir($dirName) ) return false; $dirHandle = opendir($dirName); while ( ($incFile = readdir($dirHandle)) !== false ) { if ( preg_match("!^.+\.html$!i", $incFile) && is_file("$dirName/$incFile") ) $filesArray[] = preg_replace("!\.html$!i", "", $incFile); } closedir($dirHandle); natcasesort($filesArray); $filesArray = array_values($filesArray); return true; } $filesArray = array(); if ( populateArryOfFiles(SLIDES_PATH, $filesArray) ) include_once 'tenslide.html'; else echo "ERROR LOADING SLIDES"; ?>
fe74dcdd3d894a84ea1f55e6daefb53416194af0
[ "PHP" ]
1
PHP
orioltf/urslides
ed98160919e8122c1d91d3bbf0f49ca77090c3c7
9355a46c3651ebe42b5f2f8a8f1873df77e53b56
refs/heads/master
<repo_name>uturkdogan/skeleton-sp18<file_sep>/proj1b/OffByN.java public class OffByN implements CharacterComparator { private int N; /** Creates a character comparator that checks if the chars are off by N. * absolute value is used. * @param n */ public OffByN(int n) { N = Math.abs(n); } @Override public boolean equalChars(char x, char y) { return Math.abs(y - x) == N; } } <file_sep>/proj1a/LinkedListDeque.java /** Implementation of double list deque. * This implementation will use circular sentinel node. */ public class LinkedListDeque<T> { /** Node Class for Deck use. * Uses Generic type, double linked. */ private class Node { private Node next; private Node previous; private T value; /** Creates a new Node with given generic type `NodeT` * * @param previous, previous node * @param value, value of node * @param next, next node. */ Node(Node previous, T value, Node next) { this.previous = previous; this.value = value; this.next = next; } /** Creates an empty node. * */ Node() { } } /* Fields */ private int size = 0; private Node sentinel; /** Creates an empty Deque. * */ LinkedListDeque() { sentinel = new Node(); sentinel.next = sentinel; sentinel.previous = sentinel; } /** Returns the value of `i`th item. * * @param i, index of item. */ public T get(int i) { // TODO: check if the index closer to end go reverse. // Check if i >= size, which is `indexoutofbounds` error. Return null; if (i >= size) { return null; } Node current = sentinel; for (int index = 0; index <= i; index++) { current = current.next; } return current.value; } /** Recursive helper for get method. * if i == 0, return current value, * if not return i-1th element starting from next * @param n, start node * @param i, offset * @return */ private T getRecursiveHelper(Node n, int i) { if (i == 0) { return n.value; } if (n == sentinel) { return null; } return getRecursiveHelper(n.next, i - 1); } /** Returns the value of `i`th item recursively. * * @param i, index of item. */ public T getRecursive(int i) { // TODO: check if the index closer to end go reverse. Node current = sentinel.next; return getRecursiveHelper(current, i); } /** Adds an item to the beginning of the list. * Sets the sentinels next and next item's previous to the new item. * @param item to be added. */ public void addFirst(T item) { Node newItem = new Node(sentinel, item, sentinel.next); sentinel.next = newItem; newItem.next.previous = newItem; size += 1; } /** Adds an item to the end of the list, append. * Sets sentinels previous and previous item's next to the new item. * @param item to be appended. */ public void addLast(T item) { Node newItem = new Node(sentinel.previous, item, sentinel); sentinel.previous = newItem; newItem.previous.next = newItem; size += 1; } /** Removes the given item, * Sets `itemToRemove`s previous to its next and `itemToRemove`s next to its previous. * @param itemToRemove */ private void removeItem(Node itemToRemove) { itemToRemove.previous.next = itemToRemove.next; itemToRemove.next.previous = itemToRemove.previous; size -= 1; } /** Removes the first item, * (which is sentinel's next.) */ public T removeFirst() { Node itemToRemove = sentinel.next; if (itemToRemove == sentinel) { return null; } removeItem(itemToRemove); return itemToRemove.value; } /** Removes the last item, * (which is sentinel's last.) */ public T removeLast() { Node itemToRemove = sentinel.previous; if (itemToRemove == sentinel) { return null; } removeItem(itemToRemove); return itemToRemove.value; } /** Prints the list. * */ public void printDeque() { System.out.println(this); } /** Returns the list as a string * */ public String toString() { StringBuilder s = new StringBuilder(); Node current = sentinel.next; while (current != sentinel) { if (s.length() != 0) { s.append(" "); } s.append(current.value); current = current.next; } return s.toString(); } /** Returns the size of the list. * */ public int size() { return size; } /** Checks if the list is empty. * */ public boolean isEmpty() { return size == 0; } } <file_sep>/proj2/byog/Core/Room.java package byog.Core; import java.util.ArrayList; import java.util.List; class Room { public Position getPosition() { return position; } public int getWidth() { return width; } public int getHeight() { return height; } public Position getMiddlePoint() { return new Position(this.position.getxPosition() + this.width / 2, this.position.getyPosition() + this.height / 2); } private final Position position; private final int width; private final int height; private List<Room> connectedTo; public Room(Position position, int width, int height) { this.position = position; this.width = width; this.height = height; connectedTo = new ArrayList<Room>(); } /** * Checks collision between two rooms * @param r2 * @return */ public boolean collidesTo(Room r2) { return this.position.getxPosition() < r2.position.getxPosition() + r2.width && this.position.getxPosition() + this.width > r2.position.getxPosition() && this.position.getyPosition() < r2.position.getyPosition() + r2.height && this.position.getyPosition() + this.height > r2.position.getyPosition(); } } <file_sep>/proj2/byog/Core/WorldTest.java package byog.Core; import org.junit.Test; import static org.junit.Assert.*; public class WorldTest { public static void main( String[] args ) { World w = new World(80, 30, 8888); // for (int i = 0; i < 20; i++) { // w.drawRandomRoom(); // } w.initRenderer(); w.generateWorld(); w.render(); } } <file_sep>/hw1/synthesizer/TestArrayRingBuffer.java package synthesizer; import org.junit.Test; import static org.junit.Assert.*; /** Tests the ArrayRingBuffer class. * @author <NAME> */ public class TestArrayRingBuffer { @Test public void enqueu() { ArrayRingBuffer arb = new ArrayRingBuffer(10); arb.enqueue(10); assertEquals(1, arb.fillCount()); } @Test public void dequeue() { ArrayRingBuffer arb = new ArrayRingBuffer(10); arb.enqueue(10); arb.enqueue(15); assertEquals(10, arb.dequeue()); } @Test public void peek() { ArrayRingBuffer arb = new ArrayRingBuffer(10); arb.enqueue(10); arb.enqueue(15); arb.dequeue(); arb.enqueue(20); assertEquals(15, arb.peek()); } @Test(expected = RuntimeException.class) public void underflow() { ArrayRingBuffer arb = new ArrayRingBuffer(10); arb.dequeue(); } /** Calls tests for ArrayRingBuffer. */ public static void main(String[] args) { jh61b.junit.textui.runClasses(TestArrayRingBuffer.class); } } <file_sep>/proj1b/Palindrome.java public class Palindrome { /** Converts a given word into a ArrayDeque. */ public Deque<Character> wordToDeque(String word) { Deque<Character> d = new ArrayDeque<>(); for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); d.addLast(c); } return d; } /** Checks if a word is Palindrome iteratively. * Palindrome is defined as a word that is the same whether it is read forwards or backwards */ public boolean isPalindromeIterative(String word) { Deque<Character> d = wordToDeque(word); boolean result = true; while (d.size() > 1) { if (d.removeFirst() != d.removeLast()) { result = false; } } return result; } private boolean isPalindromeHelper(Deque d) { if (d.size() <= 1) { return true; } return (d.removeFirst() == d.removeLast()) && isPalindromeHelper(d); } /** Checks if a word is Palindrome recursively. * Palindrome is defined as a word that is the same whether it is read forwards or backwards */ public boolean isPalindrome(String word) { Deque<Character> d = wordToDeque(word); return isPalindromeHelper(d); } private boolean isPalindromeHelper(Deque<Character> d, CharacterComparator cc) { if (d.size() <= 1) { return true; } return cc.equalChars(d.removeFirst(), d.removeLast()) && isPalindromeHelper(d, cc); } /** Checks if a word is Palindrome using a custom comparator */ public boolean isPalindrome(String word, CharacterComparator cc) { Deque<Character> d = wordToDeque(word); return isPalindromeHelper(d, cc); } } <file_sep>/proj2/byog/Core/Position.java package byog.Core; public class Position { private final double xPosition; private final double yPosition; public double getxPosition() { return xPosition; } public double getyPosition() { return yPosition; } /** * Creates a point in 2D space, bottom left is 0,0 * @param xPosition, X axis * @param yPosition, Y axis */ public Position(double xPosition, double yPosition) { this.xPosition = xPosition; this.yPosition = yPosition; } /** * Creates a new position with x offset. * @param offset * @return */ public Position offsetX(double offset) { return this.offset(offset, 0); } /** * Creates a new position with y offset. * @param offset * @return */ public Position offsetY(double offset) { return this.offset(0, offset); } /** * Creates a new position with given offset. * @param xOffset * @param yOffset * @return */ public Position offset(double xOffset, double yOffset) { return new Position(xPosition + xOffset, yPosition + yOffset); } /** * Calculates euclidean distance between two positions * @param p1 * @param p2 * @return */ public static double distanceBetween(Position p1, Position p2) { return Math.sqrt( Math.pow(p1.xPosition - p2.xPosition, 2) + Math.pow(p1.yPosition - p2.yPosition, 2) ); } /** * Returns integer x location * @return */ public int getxLocation(){ return (int) xPosition; } /** * Returns integer y location * @return */ public int getyLocation(){ return (int) yPosition; } }
d91cfe6d6d9818f1e3f356db953aa67db742b9d8
[ "Java" ]
7
Java
uturkdogan/skeleton-sp18
06b10e90771765e3713c0c87c0d966e36e0d9ec7
1ca97afbf7ba9c1af527daaa34a5f3a40ddf3542
refs/heads/master
<repo_name>Nayananga/HarmonyUiKit<file_sep>/HarmonyUiKit/ViewController.swift // // ViewController.swift // HarmonyUiKit // // Created by <NAME> on 12/1/18. // Copyright © 2018 nexgenits. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK: Outlets @IBOutlet weak var loginButtonView: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // self.loginButtonSetup() } // func loginButtonSetup(){ // self.loginButtonView.layer.shadowColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha:0.9).cgColor // self.loginButtonView.layer.shadowRadius = 3.0 // self.loginButtonView.layer.shadowOpacity = 0.2 // self.loginButtonView.layer.shadowOffset = CGSize(width: 0.0, height: 12.0) // self.loginButtonView.layer.cornerRadius = self.loginButtonView.bounds.size.height/2 // // } } <file_sep>/HarmonyUiKit/controllers/homeViewController.swift // // tableViewController.swift // HarmonyUiKit // // Created by <NAME> on 12/3/18. // Copyright © 2018 nexgenits. All rights reserved. // import UIKit class homeViewController: ViewController { // @IBOutlet weak var loginButtonView: UIButton! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.tableView.register(UINib(nibName: "homeTableViewCell", bundle: nil), forCellReuseIdentifier: "homeTableViewCell") self.tableView.rowHeight = UITableView.automaticDimension self.tableView.estimatedRowHeight = 100 self.tableView.delegate = self self.tableView.dataSource = self } } extension homeViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "homeTableViewCell") as! homeTableViewCell return cell } }
6d860e54fbc50de8e34006a6047ed116cd9549a8
[ "Swift" ]
2
Swift
Nayananga/HarmonyUiKit
64e8a6cc102690182c8c16f5fd15628c5cbc26c3
1f56f090d6b02b8f84df423add1387c6de95843b
refs/heads/master
<file_sep>logPath=${catalina.home} tempPath=download jdbc.url=jdbc:mysql://localhost:3306/importTool?useUnicode=true&amp;characterEncoding=UTF8 jdbc.username=root jdbc.password=CCH jdbc.driver=com.mysql.jdbc.Driver <file_sep>package cch.importTool.disruptor.authication; import com.lmax.disruptor.ExceptionHandler; public class AuthEventExceptionHandler implements ExceptionHandler{ @Override public void handleEventException(Throwable arg0, long arg1, Object arg2) { // TODO Auto-generated method stub arg0.printStackTrace(); } @Override public void handleOnShutdownException(Throwable arg0) { // TODO Auto-generated method stub arg0.printStackTrace(); } @Override public void handleOnStartException(Throwable arg0) { // TODO Auto-generated method stub arg0.printStackTrace(); } } <file_sep>package cch.importTool.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.UUID; public class CommonUtils { public static final String generateGUID(){ UUID uuid=UUID.randomUUID(); return uuid.toString(); } public static Properties getCfg() throws FileNotFoundException{ InputStream inputStream = CommonUtils.class.getClassLoader().getResourceAsStream("config.properties"); if(inputStream==null){ return null; } Properties p = new Properties(); try { p.load(inputStream); } catch (IOException e1) { e1.printStackTrace(); } return p; } } <file_sep>drop table if exists LegalPerson; drop table if exists Person; /*==============================================================*/ /* Table: LegalPerson */ /*==============================================================*/ create table LegalPerson ( Id varchar(36) not null comment '序列号', PersonName varchar(64) comment '法人姓名', PersonIdCardNum varchar(36) comment '法人身份证', Mobile varchar(36) comment '移动电话', Password varchar(36) comment '密码', CompanyName varchar(256) comment '公司名称', CompanyIdNum varchar(36) comment '公司统一社会信用代码', CompanyType varchar(36) comment '公司类型', ImportTag varchar(128) comment '导入标记', ImportTime datetime comment '导入时间', Result varchar(36) comment '导入结果', UpdateTime datetime comment '更新时间', primary key (Id) ); /*==============================================================*/ /* Table: Person */ /*==============================================================*/ create table Person ( Id varchar(36) not null comment '序列号', Name varchar(64) comment '姓名', IdCardNum varchar(36) comment '身份证', Mobile varchar(36) comment '移动电话', Password varchar(36) comment '密码', ImportTag varchar(128) comment '导入标注', ImportTime datetime comment '导入时间', Result varchar(36) comment '导入结果', UpdateTime datetime comment '更新时间', ResultFlag tinyint comment '业务标志', primary key (Id) ); <file_sep>package cch.importTool.disruptor.authication; public class AuthEvent { private String id; private String type; private String personName; private String personIdCardNum; private String mobile; private String legalPersonName; private String legalPersonIdCardNum; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public String getPersonIdCardNum() { return personIdCardNum; } public void setPersonIdCardNum(String personIdCardNum) { this.personIdCardNum = personIdCardNum; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getLegalPersonName() { return legalPersonName; } public void setLegalPersonName(String legalPersonName) { this.legalPersonName = legalPersonName; } public String getLegalPersonIdCardNum() { return legalPersonIdCardNum; } public void setLegalPersonIdCardNum(String legalPersonIdCardNum) { this.legalPersonIdCardNum = legalPersonIdCardNum; } } <file_sep>package cch.importTool.dao; import cch.importTool.model.Person; import cch.importTool.model.PersonExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface PersonMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int countByExample(PersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int deleteByExample(PersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int deleteByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int insert(Person record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int insertSelective(Person record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ List<Person> selectByExample(PersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ Person selectByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int updateByExampleSelective(@Param("record") Person record, @Param("example") PersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int updateByExample(@Param("record") Person record, @Param("example") PersonExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int updateByPrimaryKeySelective(Person record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table Person * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ int updateByPrimaryKey(Person record); }<file_sep>package cch.importTool.model; import java.util.Date; public class LegalPerson { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.Id * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.PersonName * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String personName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.PersonIdCardNum * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String personIdCardNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.Mobile * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String mobile; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.Password * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String password; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.CompanyName * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String companyName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.CompanyIdNum * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String companyIdNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.CompanyType * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String companyType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.ImportTag * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String importTag; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.ImportTime * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private Date importTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.Result * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private String result; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column LegalPerson.UpdateTime * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ private Date updateTime; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.Id * * @return the value of LegalPerson.Id * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.Id * * @param id the value for LegalPerson.Id * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setId(String id) { this.id = id == null ? null : id.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.PersonName * * @return the value of LegalPerson.PersonName * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getPersonName() { return personName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.PersonName * * @param personName the value for LegalPerson.PersonName * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setPersonName(String personName) { this.personName = personName == null ? null : personName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.PersonIdCardNum * * @return the value of LegalPerson.PersonIdCardNum * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getPersonIdCardNum() { return personIdCardNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.PersonIdCardNum * * @param personIdCardNum the value for LegalPerson.PersonIdCardNum * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setPersonIdCardNum(String personIdCardNum) { this.personIdCardNum = personIdCardNum == null ? null : personIdCardNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.Mobile * * @return the value of LegalPerson.Mobile * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getMobile() { return mobile; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.Mobile * * @param mobile the value for LegalPerson.Mobile * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setMobile(String mobile) { this.mobile = mobile == null ? null : mobile.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.Password * * @return the value of LegalPerson.Password * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getPassword() { return password; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.Password * * @param password the value for LegalPerson.Password * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setPassword(String password) { this.password = password == null ? null : password.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.CompanyName * * @return the value of LegalPerson.CompanyName * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getCompanyName() { return companyName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.CompanyName * * @param companyName the value for LegalPerson.CompanyName * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setCompanyName(String companyName) { this.companyName = companyName == null ? null : companyName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.CompanyIdNum * * @return the value of LegalPerson.CompanyIdNum * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getCompanyIdNum() { return companyIdNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.CompanyIdNum * * @param companyIdNum the value for LegalPerson.CompanyIdNum * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setCompanyIdNum(String companyIdNum) { this.companyIdNum = companyIdNum == null ? null : companyIdNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.CompanyType * * @return the value of LegalPerson.CompanyType * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getCompanyType() { return companyType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.CompanyType * * @param companyType the value for LegalPerson.CompanyType * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setCompanyType(String companyType) { this.companyType = companyType == null ? null : companyType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.ImportTag * * @return the value of LegalPerson.ImportTag * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getImportTag() { return importTag; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.ImportTag * * @param importTag the value for LegalPerson.ImportTag * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setImportTag(String importTag) { this.importTag = importTag == null ? null : importTag.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.ImportTime * * @return the value of LegalPerson.ImportTime * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public Date getImportTime() { return importTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.ImportTime * * @param importTime the value for LegalPerson.ImportTime * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setImportTime(Date importTime) { this.importTime = importTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.Result * * @return the value of LegalPerson.Result * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public String getResult() { return result; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.Result * * @param result the value for LegalPerson.Result * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setResult(String result) { this.result = result == null ? null : result.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column LegalPerson.UpdateTime * * @return the value of LegalPerson.UpdateTime * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public Date getUpdateTime() { return updateTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column LegalPerson.UpdateTime * * @param updateTime the value for LegalPerson.UpdateTime * * @mbggenerated Sun Dec 02 15:36:57 CST 2018 */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
c0cb8a8ee71d23f4637ad80ec3e62782a8f0fd63
[ "Java", "SQL", "INI" ]
7
INI
c5487614/importtool
8712d138eb32765e5959ba3649734d4b0ee770db
aeb6850353b138dad9eb104480a254acac4fe061
refs/heads/main
<file_sep>import styles from './header.module.css'; import mealsPicture from '../../assets/meals.jpg'; import HeaderCartButton from './header-cart-button'; const Header = (props) => { return ( <> <header className={styles.header}> <h1>React Guide Meals Order</h1> <HeaderCartButton onClick={props.onCartClick}>Cart</HeaderCartButton> </header> <div className={styles["main-image"]}> <img src={mealsPicture} alt="food table"/> </div> </> ); } export default Header;<file_sep>import React, { useReducer } from "react"; const CartContext = React.createContext({ meals: [], totalAmount: 0, addMeal: (meal) => {}, removeMeal: (meal) => {}, }); //reduce must be pure //its called twice const cartReducer = (state, action) => { switch (action.type) { case "add": const totalAmount = state.totalAmount + action.payload.amount * action.payload.price; const existingMealIndex = state.meals.findIndex( (item) => item.id === action.payload.id ); const existingMealItem = state.meals[existingMealIndex]; let updatedItems; if (existingMealItem) { const updatedItem = { ...existingMealItem, amount: existingMealItem.amount + action.payload.amount, }; updatedItems = [...state.meals]; updatedItems[existingMealIndex] = updatedItem; } else { updatedItems = state.meals.concat(action.payload); } return { meals: updatedItems, totalAmount: totalAmount, }; case "remove": { let updatedMeals = []; const existingMealIndex = state.meals.findIndex( (item) => item.id === action.payload.id ); const existingMealItem = state.meals[existingMealIndex]; if (existingMealItem) { const updatedItem = { ...existingMealItem, amount: existingMealItem.amount - 1, }; if (updatedItem.amount === 0) { updatedMeals = state.meals.filter( (meal) => meal.id !== action.payload.id ); } else { updatedMeals = [...state.meals]; updatedMeals[existingMealIndex] = updatedItem; } } const totalAmount = updatedMeals.reduce( (aktVal, curVal) => aktVal + curVal.amount * curVal.price, 0 ); return { meals: updatedMeals, totalAmount: totalAmount, }; } } }; export const CartContextProviver = (props) => { const [cartState, cartStateDispatch] = useReducer(cartReducer, { meals: [], totalAmount: 0, }); const addMealHandler = (meal) => { cartStateDispatch({ type: "add", payload: meal }); }; const removeMealHandler = (meal) => { cartStateDispatch({ type: "remove", payload: meal }); }; return ( <CartContext.Provider value={{ meals: cartState.meals, addMeal: addMealHandler, removeMeal: removeMealHandler, totalAmount: cartState.totalAmount, }} > {props.children} </CartContext.Provider> ); }; export default CartContext; <file_sep>import { useContext, useEffect, useState } from "react"; import CartContext from "../../context/cartContext"; import CartIcon from "../cart/cart-icon"; import styles from "./header-cart-button.module.css"; const HeaderCartButton = (props) => { const cartContext = useContext(CartContext); const [btnHighlight, setBtnHighlight] = useState(false); const { meals } = cartContext; const btnStyles = `${styles.button} ${btnHighlight ? styles.bump : ""}`; useEffect(() => { if (meals.length === 0) { return; } setBtnHighlight(true); const timer = setTimeout(() => { setBtnHighlight(false); }, 300); return () => { clearTimeout(timer); }; }, [meals]); return ( <button onClick={props.onClick} className={btnStyles}> <span className={styles.icon}> <CartIcon /> </span> <span>Your Cart</span> <span className={styles.badge}>{cartContext.totalAmount.toFixed(2)}</span> </button> ); }; export default HeaderCartButton; <file_sep># Learning React project Project uses: **Hooks** - useState - useEffect - with setTimeout - useContext - useReducer - useRef **React Context API** **CSS modules** **Modal** <file_sep>import { useRef, useState } from 'react'; import Input from '../../ui/input'; import styles from './mealForm.module.css'; const MealForm = (props) => { const [amountValid, setamountValid] = useState(true); const amountInputRef = useRef(); const onSubmitHandler = (event) => { event.preventDefault(); const enteredAmount = amountInputRef.current.value; const enteredAmountNumber =+enteredAmount; if(enteredAmount.trim().length === 0 || enteredAmountNumber < 1 || enteredAmountNumber > 5){ setamountValid(false); return; } setamountValid(true); props.onSubmit(enteredAmountNumber); }; return ( <form className={styles.form} onSubmit={onSubmitHandler}> <Input title="Amount" ref={amountInputRef} input={{ id:"amount_" + props.id, type:"number", step:"1", defaultValue:"0", min:"1", max:"5" }} /> <button type="submit">Add</button> {!amountValid && <p>Please eneter a valid amount.</p>} </form> ); }; export default MealForm;<file_sep>import styles from "./Cart.module.css"; import Modal from "../ui/modal"; import { useContext } from "react"; import CartContext from "../../context/cartContext"; import CartItem from './CartItem'; const Cart = (props) => { const cartContext = useContext(CartContext); const addItemHandler = (item) => { cartContext.addMeal({ ...item, amount: 1, }); }; const removeItemHandler = (item) => { cartContext.removeMeal(item); }; const cartitems = ( <ul className={styles["cart-items"]}> {cartContext.meals.map((item) => ( <CartItem key={item.id} name={item.name} price={item.price} amount={item.amount} onAdd={addItemHandler.bind(null, item)} onRemove={removeItemHandler.bind(null, item)}/> ))} </ul> ); const totalAmount = `${cartContext.totalAmount.toFixed(2)} CZK`; const hasItems = cartContext.meals.length > 0; return ( <Modal onClick={props.onClose}> {cartitems} <div className={styles.total}> <span>Total Amount</span> <span>{totalAmount}</span> </div> <div className={styles.actions}> <button className={styles["button--alt"]} onClick={props.onClose}> Close </button> {hasItems && <button className={styles.button}>Order</button>} </div> </Modal> ); }; export default Cart;
0004dab05e97d8ff777e1b89cc780ce2b44fd8a2
[ "JavaScript", "Markdown" ]
6
JavaScript
Gramli/react-food-order-guide
45b1d0539ce49721a150f3ad91da7de36393bc58
fcf22cb4ead9a2159be2e61e486fe8d410cf4def
refs/heads/main
<file_sep>'use strict'; let mainWindow; const { app, BrowserWindow, ipcMain } = require('electron'); const path = require('path'); const createWindow = () => { // Create the browser window. const info = { frame: false, fullscreen: true, webPreferences: { contextIsolation: true, preload: path.join(__dirname, 'preload.js'), backgroundThrottling: false }, icon: path.join(__dirname, 'icons', 'icon.png'), show: false }; mainWindow = new BrowserWindow(info); mainWindow.on("ready-to-show", () => { mainWindow.show(); }); mainWindow.loadFile(path.join(__dirname, "index.html")); }; // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow); // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and import them here. ipcMain.on("quit", () => { app.quit(); }); <file_sep>'use strict'; const {ipcRenderer, contextBridge} = require("electron"); const path = require("path"); const fs = require("fs-extra"); const url = require("url"); const os = require("os"); const child_process = require("child_process"); function readIfExist(fPath){ return fs.existsSync(fPath) ? fs.readJSONSync(fPath) : {}; } const settings = readIfExist(path.join(os.homedir(), "raspi-music-config.json")); let autoReloadWatcher = fs.watch(path.join(os.homedir(), "raspi-music")); contextBridge.exposeInMainWorld("miscHelper", { registerReloader: (fn) => { autoReloadWatcher.on('change', (type) => { if(type === "rename"){ fn(); } }); }, quit: () => { autoReloadWatcher.close(); if(settings.customQuit){ document.querySelector("#shutdownImg").src = url.pathToFileURL(settings.quitImage).href; document.querySelector("#shutdownImg").style.display = "block"; child_process.exec(settings.quitScript); }else{ ipcRenderer.send("quit"); } }, getAlbumInfo: (albumSrc) => { let info = {}; info.img = fs.existsSync(path.join(albumSrc, "cover.png")) ? url.pathToFileURL(path.join(albumSrc, "cover.png")).href : "albumDefaultImg.png"; info.name = readIfExist(path.join(albumSrc, "album.json")).name; if(!info.name){ info.name = path.parse(albumSrc).name; } return info; }, scanTitles: (albumSrc) => { const titles = fs.readdirSync(albumSrc).filter(el => {console.log(el);return el != "cover.png" && el != "album.json" && el != "desktop.ini"}); const info = readIfExist(path.join(albumSrc, "album.json")); return([titles.map(el => { return url.pathToFileURL(path.join(albumSrc, el)).href; }), titles.map(el => { return info[el] ? info[el] : el; })]); }, scanAlbums: () => { return fs.readdirSync(path.join(os.homedir(), "raspi-music"), { withFileTypes: true }).filter(dirent => {return dirent.isDirectory()}).map(dirent => {return path.join(os.homedir(), "raspi-music", dirent.name)}) }, useCustomScroll: !!settings.useCustomScroll }); <file_sep># raspi-music ## Was ist das raspi-music läuft auf dem Raspberry Pi. Mit raspi-music kannst du den Raspberry Pi zu einem einfachen Musikplayer machen. ## Installation 1. Raspberry Pi OS installieren (du findest Anleitungen im Internet) 2. Node JS installieren (Anleitung von https://github.com/nodesource/distributions/blob/master/README.md#deb) 1. Im Terminal: `sudo curl -fsSL https://deb.nodesource.com/setup_15.x | bash -` 2. Auch im Terminal: `sudo apt-get install -y nodejs` 3. Desktopbild ändern 4. Splashscreen ändern: 1. Bild auf den Raspberry Pi laden 2. Bild als splash.png zu /usr/share/plymouth/themes/pix laden 5. Bootinfo entfernen: `#` vor diesen Zeilen in der Datei /usr/share/plymouth/themes/pix/pix.script einfügen: `message_sprite = Sprite();`, `message_sprite.SetPosition(screen_width * 0.1, screen_height * 0.9, 10000);`, `my_image = Image.Text(text, 1, 1, 1);` und `message_sprite.SetImage(my_image);` 4. Programm einrichten 1. Im Ordner /home/pi `git clone --depth 1 https://github.com/Git-J219/raspi-music rm` ausführen 2. Im Ordner /home/pi die Datei raspi-music-config.json mit diesem Inhalt erstellen: `{ "useCustomScroll": false, "customQuit": true, "quitScript": "shutdown -h now" }` 3. Im Ordner /home/pi den Ordner raspi-music erstellen 4. Autostart einrichten: 1. In der Datei /etc/xdg/lxsession/LXDE-pi/autostart die Zeilen `@lxpanel --profile LXDE-pi` und `@xscreensaver -no-splash` entfernen 2. Im Ordner /home/pi die Datei rmstart.sh mit diesem Inhalt erstellen: `npm start --prefix /home/pi/rm` `lxpanel --profile LXDE-pi` 3. Im Ordner /etc/xdg/autostart die Datei rm.desktop mit diesem Inhalt erstellen: `[Desktop Entry]` `Type=Application` `Exec=/home/pi/rmstart.sh` ## Albumformat Im /home/pi/raspi-music Ordner machst du Alben rein. Ein Album ist so aufgebaut: Albumname ├─ album.json (siehe weiter unten) ├─ cover.png └─ Titel 1.mp3 album.json ist so aufgebaut: {"name": \<Hier der Name des Albums\>, \<Beliebiger Titel\>: \<Name des Titels\>}
fe2f68aa651b95cc4658ee9bc16152661b5095c3
[ "JavaScript", "Markdown" ]
3
JavaScript
Git-J219/raspi-music
0ec8c8a9c8fafe4fa8b0ceec86a0c4cde65daad3
d8aa542decca73fb69c4cb92ea586a87bcbb0ff3
refs/heads/main
<repo_name>symuns95/react-eCommerce-template<file_sep>/src/components/Hero/hero.js import React from "react"; import "./hero.scss"; import SliderHero from "./SliderHero"; const Hero = () => { return ( <section className="section-hero-main"> <SliderHero /> </section> ); }; export default Hero; <file_sep>/src/components/Categories/categories.js import React from "react"; import SectionHeading from "../SectionHeading/SectionHeading"; import "./categories.scss"; const Categories = () => { const categories = [ { style: "bg-green-200 mobile", name: "Mobile", img: "" }, { style: "bg-pink-200 ", name: "Tablate", img: "" }, { style: "bg-red-200 ", name: "Laptop", img: "" }, { style: "bg-purple-200 ", name: "Headphone", img: "" }, { style: "bg-blue-200 ", name: "TV", img: "" }, ]; return ( <div> <section className="categories-main"> <div className="categories-container container"> <SectionHeading heading1="Popular" heading2="Categories" categoryName="all" /> <div className="categories"> {categories.map((category) => { return ( <div className={`category ${category.style}`}> <h3>{category.name}</h3> </div> ); })} </div> </div> </section> </div> ); }; export default Categories; <file_sep>/src/pages/SingleProductPage/SingleProductPage.js import React from "react"; const SingleProductPage = () => { return ( <div> <h1>Single Product Page</h1> </div> ); }; export default SingleProductPage; <file_sep>/src/components/Header/headerBottom.js import React from "react"; const headerBottom = () => { return ( <div> <h1>header bottom</h1> </div> ); }; export default headerBottom; <file_sep>/src/App.js import React from "react"; import router from "./router/routes"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import "./styles/main.scss"; import HeaderMain from "./components/Header/headerMain"; const App = () => { return ( <Router> <HeaderMain /> <Switch> {router.map((route, i) => { return <Route key={i} exact={route.exact} path={route.path} component={route.component} />; })} </Switch> </Router> ); }; export default App; <file_sep>/src/components/Header/headerTop.js import React from "react"; import { NavLink } from "react-router-dom"; const HeaderTop = () => { const navTopItems = [ { name: "About", path: "/about", style: "" }, { name: "Contact", path: "/contact", style: "px-3 lg:px-4" }, { name: "Delivery", path: "/delivery", style: "px-3 lg:px-4" }, { name: "Payment", path: "/payment", style: "px-3 lg:px-4" } ]; return ( <> <div className=" flex flex-wrap justify-between header-top-main"> <ul className="header-top-ul flex items-center"> {navTopItems.map((item, i) => { const { name, path, style } = item; return ( <li className=" text-center 2xl:text-xl" key={i}> <NavLink exact activeClassName="text-gray-400 " className={style} to={path} > {name} </NavLink> </li> ); })} </ul> <div className="header-top-brand text-2xl"> My <span className="inline-block text-blue-500">Store</span> </div> <div className="header-top-contact-no text-xl">+023 2594 844</div> </div> </> ); }; export default HeaderTop; <file_sep>/src/components/Header/headerMiddle.js import SearchIcon from "@mui/icons-material/Search"; import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown"; import { Box, TextField } from "@mui/material"; import React from "react"; import { FiShoppingCart, FiHeart } from "react-icons/fi"; import { FaBars } from "react-icons/fa"; import { Link } from "react-router-dom"; const HeaderMiddle = () => { return ( <div className="header-middle-main flex items-center justify-between py-4"> <div className="header-middel-brand lg:w-2/12 "> <Link to="/" className="header-middel-brand-name text-2xl font-bold"> My <span className="text-blue-500 ">Store</span> </Link> </div> <div className="header-middle-src-box lg:w-6/12 pl-3 "> <Box sx={{ display: "flex", alignItems: "flex-end" }}> <label htmlFor="standard-search"> <SearchIcon sx={{ color: "action.active", mr: 2, my: 0.5 }} /> </label> <TextField fullWidth={true} id="standard-search" label="Search field" type="search" variant="standard" /> </Box> </div> <div className="header-middle-icons-account flex items-center justify-center lg:w-4/12 "> <div className="icon-wish px-2 text-xl"> <FiHeart /> </div> <div className="icon-cart px-2 text-2xl flex items-center text-blue-500 font-bold"> <FiShoppingCart /> <div className="amount-cart flex flex-col text-lg pl-3"> <span>MY CART</span> <span> 0 ITEMS <span className="inline-block"> <ArrowDropDownIcon sx={{ margin: "-3px", fontSize: "1.6rem" }} /> </span> </span> </div> </div> <div className="acount-login-signin flex items-center justify-center"> <button className="btn-log-in px-2">Login</button> <span className="inline-block">or</span> <button className="btn-sign-in px-2">Register</button> </div> </div> <button className="btn-menu text-xl"> <FaBars /> </button> </div> ); }; export default HeaderMiddle; <file_sep>/src/components/Hero/SliderHero.js import React from "react"; // Import Swiper React components import { Swiper, SwiperSlide } from "swiper/react"; // Import Swiper styles import "swiper/swiper.min.css"; import "swiper/components/pagination/pagination.min.css"; // import Swiper core and required modules import SwiperCore, { Pagination, Autoplay } from "swiper/core"; // animation import AOS from "aos"; import "aos/dist/aos.css"; // install Swiper modules SwiperCore.use([Pagination, Autoplay]); AOS.init({ duration: 1200, }); const sliderInfo = [ { image: "macbook-1.jpeg", subHeading: "Say Hello The future.", heading: "Mackbook Pro", btn: "Buy Now" }, { image: "phone.jpeg", subHeading: "Say Hello The future.", heading: "IPhone XS", btn: "Buy Now" }, ]; function SliderHero() { // const [sliderIndex, setSliderIndex] = useState(0); // const [changeIndex, setChangeIndex] = useState(2); // console.log(sliderIndex); // console.log(changeIndex); return ( <> <Swiper // onSwiper={setSliderIndex} // onSlideChange={() => setChangeIndex(sliderIndex)} // grabCursor={true} centeredSlides={true} pagination={true} loop={true} // autoplay={{ // delay: 5000, // disableOnInteraction: false, // }} className="slider-hero-main" > {sliderInfo.map((item, i) => { const { image, subHeading, heading, btn } = item; return ( <SwiperSlide key={i} style={{ backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.4),rgba(0, 0, 0, 0.3)) ,url("/images/${image}")`, }} className="slider-hero" > <div className="section-hero-container container" data-aos="fade-right"> <div className="row row-section-hero "> <div className="section-hero-info text-center md:text-left"> <h2 className="section-hero-sub-heading text-gray-300 font-semibold md:mb-5 text-2xl ">{subHeading}</h2> <h1 className="section-hero-heading text-white xl:text-7xl md:mb-5 mb-3 font-bold "> {heading}</h1> <div className="section-hero-btn px-8 py-3 text-white">{btn}</div> </div> </div> </div> </SwiperSlide> ); })} </Swiper> </> ); } export default SliderHero; <file_sep>/src/components/Header/headerMain.js import React from "react"; import "./header.scss"; import HeaderMiddle from "./headerMiddle"; import HeaderTop from "./headerTop"; const HeaderMain = () => { return ( <header className="section-header-main bg-white p-3"> <div className="container-header-main container mx-auto"> <HeaderTop /> <HeaderMiddle /> </div> </header> ); }; export default HeaderMain;
dcca68b026a7cb73408cfbf26331f45eecc1ce1f
[ "JavaScript" ]
9
JavaScript
symuns95/react-eCommerce-template
9718463cdba9913c886afcc123f1c731043cd73a
76c6eafaae1be6908a5d1358c342319ee690ed8d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QBR_Calculator { class ncaa { private double comp; private double att; private double yds; private double tds; private double ints; private double rating; private double a; private double b; private double c; private double d; public void setComp(string completions) { comp = double.Parse(completions); } public void setAtt(string attemtps) { att = double.Parse(attemtps); } public void setYards(string yards) { yds = double.Parse(yards); } public void setTD(string touchdowns) { tds = double.Parse(touchdowns); } public void setInt(string interceptions) { ints = double.Parse(interceptions); } public double getRating() { a = (comp/att) * 100; b = (tds/att) * 100; c = (ints/att) * 100; d = yds / att; rating = a + (3.3 * b) - (2 * c) + (8.4 * d); rating = Math.Round(rating, 2); return rating; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QBR_Calculator { public partial class Main : Form { public Main() { InitializeComponent(); } private void resetButton_Click(object sender, EventArgs e) { completionsBox.Text = ""; attemptsBox.Text = ""; yardsBox.Text = ""; touchdownsBox.Text = ""; interceptionsBox.Text = ""; nflResult.Text = ""; ncaaResult.Text = ""; } private void Main_Load(object sender, EventArgs e) { } private void calculateButton_Click(object sender, EventArgs e) { nfl nflRating = new nfl(); nflRating.setComp(completionsBox.Text); nflRating.setAtt(attemptsBox.Text); nflRating.setYards(yardsBox.Text); nflRating.setTD(touchdownsBox.Text); nflRating.setInt(interceptionsBox.Text); nflResult.Text = nflRating.getRating().ToString(); ncaa ncaaRating = new ncaa(); ncaaRating.setComp(completionsBox.Text); ncaaRating.setAtt(attemptsBox.Text); ncaaRating.setYards(yardsBox.Text); ncaaRating.setTD(touchdownsBox.Text); ncaaRating.setInt(interceptionsBox.Text); ncaaResult.Text = ncaaRating.getRating().ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QBR_Calculator { class nfl { private double comp; private double att; private double yds; private double tds; private double ints; private double rating; private double a; private double b; private double c; private double d; public void setComp(string completions) { comp = double.Parse(completions); } public void setAtt(string attemtps) { att = double.Parse(attemtps); } public void setYards(string yards) { yds = double.Parse(yards); } public void setTD(string touchdowns) { tds = double.Parse(touchdowns); } public void setInt(string interceptions) { ints = double.Parse(interceptions); } public double getRating() { a = (((comp/att) * 100) - 30) / 20; b = ((tds/att) * 100) / 5; c = (9.5 - ((ints/att) * 100)) / 4; d = ((yds/att) - 3) / 4; if (a > 2.375) { a = 2.375; }; if (b > 2.375) { b = 2.375; }; if (c > 2.375) { c = 2.375; }; if (d > 2.375) { d = 2.375; }; if (0 > a) { a = 0; }; if (0 > b) { b = 0; }; if (0 > c) { c = 0; }; if (0 > d) { d = 0; }; rating = (a + b + c + d) / .06; rating = Math.Round(rating, 2); return rating; } } } <file_sep># QBR-Calculator-Windows NFL and NCAA Quarterback Rating Calculator for Windows using C#.
33bdddb4fc7605c654a3735977fb15a05d4b59ea
[ "Markdown", "C#" ]
4
C#
DCribbs/QBR-Calculator-Windows
c1b452ffe221d3f9cb130f3bce9ef4436edc569c
738e41c464752ceb5a3e32f9f2c81ad068e0fde2
refs/heads/master
<repo_name>Zar21/Ev3<file_sep>/ev3_linefollower/src/EV3FirstLineFollower.java //import org.lejos.ev3.sample.sensorfilter.SensorAndFilterSample.autoAdjustFilter; import lejos.hardware.Button; import lejos.hardware.lcd.LCD; //import lejos.hardware.motor.Motor; import lejos.hardware.port.MotorPort; import lejos.robotics.RegulatedMotor; import lejos.robotics.EncoderMotor; import lejos.robotics.SampleProvider; import lejos.hardware.motor.EV3LargeRegulatedMotor; //import lejos.hardware.motor.NXTMotor import lejos.hardware.motor.UnregulatedMotor; import lejos.utility.Delay; import lejos.hardware.sensor.EV3ColorSensor; import lejos.hardware.Brick; import lejos.hardware.BrickFinder; import lejos.hardware.Key; import lejos.hardware.port.Port; import lejos.robotics.SampleProvider; import lejos.robotics.filter.AbstractFilter; public class EV3FirstLineFollower { //static RegulatedMotor leftMotor = new EV3LargeRegulatedMotor(MotorPort.A); //static RegulatedMotor rightMotor = new EV3LargeRegulatedMotor(MotorPort.D); static int max_speed=50; static int k_proportional=4; static int k_derivative=30; static float umbral_negre=0.2f; static int out_count=0; //Number of times we are out of track static int aux_count=0; //Number of times w static EncoderMotor leftMotor = new UnregulatedMotor(MotorPort.A); static EncoderMotor rightMotor = new UnregulatedMotor(MotorPort.C); static private EV3ColorSensor sensor_left; static private EV3ColorSensor sensor_middle; static private EV3ColorSensor sensor_right; static private SampleProvider reflectedLight_left; static private SampleProvider reflectedLight_middle; static private SampleProvider reflectedLight_right; static float[] sample_left; static float[] sample_middle; static float[] sample_right; static Brick brick; static private int last_sensor_location=0; //Last Color sensor on black line static private int prev_last_sensor_location=0; //Previous to Last Color sensor on black line public EV3FirstLineFollower(){ //Class constructor brick = BrickFinder.getDefault(); Port s1 = brick.getPort("S1"); Port s2 = brick.getPort("S2"); Port s3 = brick.getPort("S3"); sensor_left = new EV3ColorSensor(s1); sensor_middle = new EV3ColorSensor(s2); sensor_right = new EV3ColorSensor(s3); SampleProvider redMode_sensor_left = sensor_left.getRedMode(); SampleProvider redMode_sensor_middle = sensor_middle.getRedMode(); SampleProvider redMode_sensor_right = sensor_right.getRedMode(); reflectedLight_left = new autoAdjustFilter(redMode_sensor_left); reflectedLight_middle = new autoAdjustFilter(redMode_sensor_middle); reflectedLight_right = new autoAdjustFilter(redMode_sensor_right); int sampleSize_left = reflectedLight_left.sampleSize(); sample_left = new float[sampleSize_left]; int sampleSize_middle = reflectedLight_middle.sampleSize(); sample_middle = new float[sampleSize_middle]; int sampleSize_right = reflectedLight_right.sampleSize(); sample_right = new float[sampleSize_right]; LCD.clear(); Key left_key = brick.getKey("Left"); //for (int x=0;x<100;x++) { while (!left_key.isDown()) { /* * Get a fresh sample from the filter. (The filter gets it from its * source, the redMode) */ reflectedLight_left.fetchSample(sample_left, 0); /* Display individual values in the sample. */ for (int i = 0; i < sampleSize_left; i++) { LCD.drawString("L="+ sample_left[i] + " ", 0, 1); //System.out.print("L="+ sample_left[i] + " "); } reflectedLight_middle.fetchSample(sample_middle, 0); /* Display individual values in the sample. */ for (int i = 0; i < sampleSize_middle; i++) { LCD.drawString("M="+ sample_middle[i] + " ", 0, 2); //System.out.print("M="+sample_middle[i] + " "); } reflectedLight_right.fetchSample(sample_right, 0); /* Display individual values in the sample. */ for (int i = 0; i < sampleSize_right; i++) { LCD.drawString("R="+ sample_right[i] + " ", 0, 3); //System.out.print("R="+sample_right[i] + " "); } LCD.drawString("sampleSize="+ sampleSize_right + " ", 0, 4); int sample_=read_sensors(); /*if (sample_==2){ set_motors(25,25); }else if (sample_==1 || sample_==0){ set_motors(15,25); }else if (sample_==3 || sample_==4){ set_motors(25,15); }*/ LCD.drawString("Read Sensors="+ sample_ + " ", 0, 5); LCD.drawString("Last="+ last_sensor_location + " Prev="+prev_last_sensor_location+"-", 0, 6); //LCD.drawString(String.valueOf(read_sensors())+" MP="+leftMotor.getPower(), 0, 5); System.out.println(); Delay.msDelay(50); } set_motors(1,1,3); Key right_key = brick.getKey("Right"); Key up_key = brick.getKey("Up"); Key down_key = brick.getKey("Down"); LCD.clear(); while (!right_key.isDown()) { LCD.refresh(); LCD.drawString("KP="+EV3FirstLineFollower.k_proportional+":::", 0, 2); if (up_key.isDown()){ EV3FirstLineFollower.k_proportional+=1; Delay.msDelay(600); } if (down_key.isDown()){ EV3FirstLineFollower.k_proportional-=1; Delay.msDelay(600); } } follow_line(); } // 0*value0 + 1000*value1 + 2000*value2 + ... // -------------------------------------------- // value0 + value1 + value2 + ... /*static private int read_sensors(){ reflectedLight_left.fetchSample(sample_left, 0); reflectedLight_middle.fetchSample(sample_middle, 0); reflectedLight_right.fetchSample(sample_right, 0); int calcul=Math.round(((sample_right[0]*0) + (100*sample_middle[0])+(200*sample_left[0]))/(sample_right[0]+sample_middle[0]+sample_left[0])); float value=sample_right[0]+sample_left[0]+sample_middle[0]; if (value<2.5f){ //We are on line last_sensor_location=calcul; return calcul; }else{ if(last_sensor_location < 100) return 0; // If it last read to the right of center, return the max. else return 200; } }*/ // De 0 a 12 with 3 sensors in arrow shape static private int read_sensors(){ reflectedLight_left.fetchSample(sample_left, 0); reflectedLight_middle.fetchSample(sample_middle, 0); reflectedLight_right.fetchSample(sample_right, 0); if (sample_middle[0]<(umbral_negre*2)){ out_count=0; if (sample_left[0]<(umbral_negre*3)){ last_sensor_location=4; return 4; }else if(sample_right[0]<(umbral_negre*3)){ last_sensor_location=8; return 8; }else{ last_sensor_location=6; return 6; } }else if (sample_left[0]<(umbral_negre*2)){ out_count=0; last_sensor_location=2; return 2; }else if (sample_right[0]<(umbral_negre*2)){ out_count=0; last_sensor_location=10; return 10; }else{ //Si no estem sobre cap sensor out_count+=1; if (last_sensor_location<6){ last_sensor_location=0; return 0; }else{ last_sensor_location=12; return 12; } } } static private void setup_motors(){ /*leftMotor.setSpeed(700); rightMotor.setSpeed(700); leftMotor.forward(); rightMotor.forward(); Delay.msDelay(1500); leftMotor.backward(); rightMotor.backward(); Delay.msDelay(1500); leftMotor.stop(); rightMotor.stop(); */ } static public void set_motors(float speed_leftMotor, float speed_rightMotor,int last_prop_reading) { /* LCD.refresh(); LCD.drawString("Left", 0, 1); LCD.drawString(String.valueOf(Math.round(speed_leftMotor))+";",9,1); LCD.drawString("Right", 0, 3); LCD.drawString(String.valueOf(Math.round(speed_rightMotor))+";",9,3); */ if (speed_leftMotor > 0) { //Pep 12-11-14 //leftMotor.forward(); leftMotor.backward(); //leftMotor.setSpeed(Math.round(speed_leftMotor)); leftMotor.setPower(Math.round(speed_leftMotor)); } else if(speed_leftMotor == 0){ //When speed equals 0 //leftMotor.forward(); //leftMotor.setSpeed(0); if (out_count>500) { //leftMotor.backward(); leftMotor.forward(); leftMotor.setPower(20); }else{ //leftMotor.forward(); leftMotor.backward(); leftMotor.setPower(20); } } if (speed_rightMotor > 0) { //rightMotor.forward(); rightMotor.backward(); //rightMotor.setSpeed(Math.round(speed_leftMotor)); rightMotor.setPower(Math.round(speed_rightMotor)); } else if(speed_rightMotor==0){ //When speed equals 0 //rightMotor.forward(); //rightMotor.setSpeed(0); if (out_count>500) { //rightMotor.backward(); rightMotor.forward(); rightMotor.setPower(20); }else{ //rightMotor.forward(); rightMotor.backward(); rightMotor.setPower(20); } } } static public void follow_line() { float last_proportional = 0; //int max = 90; int bar_sensors; float proportional; float derivative; float power_difference; leftMotor.forward(); rightMotor.forward(); //Key enter = brick.getKey("ENTER"); //while (!enter.isDown()) { //Key escape = brick.getKey("Escape"); LCD.clear(); while (!Button.ESCAPE.isDown()) { //for(;;){ bar_sensors = read_sensors(); //System.out.print("bar_sensors="+bar_sensors+"\n"); proportional = bar_sensors - 6; derivative = proportional - last_proportional; //LCD.drawString("Der "+String.valueOf(derivative), 0, 5); //LCD.drawString("lp OLD "+String.valueOf(last_proportional), 0, 6); last_proportional = proportional; //LCD.drawString("lp NEW "+String.valueOf(last_proportional), 0, 8); //power_difference = proportional * 100 + derivative * 150; //Amb piles NiMh 7,4v 150 i 2500 //power_difference = proportional * 20 + derivative * 100; power_difference = (proportional * k_proportional) + (derivative * k_derivative); if (bar_sensors==0) power_difference=-max_speed; else if (bar_sensors==12) power_difference=max_speed; //LCD.drawString("Der "+String.valueOf(derivative), 0, 5); if (power_difference > max_speed){ power_difference = max_speed; } if (power_difference < -max_speed){ power_difference = -max_speed; } if (power_difference == 0) { set_motors(max_speed, max_speed,bar_sensors); } else if (power_difference < 0) {//si es negatiu set_motors(max_speed, max_speed + power_difference,bar_sensors); } else { set_motors(max_speed - power_difference, max_speed,bar_sensors); } //LCD.clear(); aux_count+=1; Delay.usDelay(200); while(Button.ESCAPE.isDown()){ //set_motors(0,0,0); Delay.msDelay(1000); System.out.println("ESCAPE pressed \n"+aux_count); //Delay.msDelay(10000); break; } } } public static void main(String[] args) { LCD.clear(); LCD.drawString(" IES L'Estacio", 0, 2); LCD.drawString("Desafiament robot", 0, 4); LCD.drawString(" 2015", 0, 5); //EV3FirstLineFollower.setup_motors(); //EV3FirstLineFollower.setup_motors(); EV3FirstLineFollower lf=new EV3FirstLineFollower(); //set_motors(max_speed,max_speed); LCD.clear(); LCD.refresh(); Key escape = brick.getKey("Escape"); while (!escape.isDown()) { LCD.drawString("Read sensors", 0, 1); LCD.drawString(String.valueOf(read_sensors()), 0, 2); Delay.msDelay(1200); } } /** * This filter dynamicaly adjust the samples value to a range of 0-1. The * purpose of this filter is to autocalibrate a light Sensor to return values * between 0 and 1 no matter what the light conditions. Once the light sensor * has "seen" both white and black it is calibrated and ready for use. * * The filter could be used in a line following robot. The robot could rotate * to calibrate the sensor. * * @author Aswin * */ public class autoAdjustFilter extends AbstractFilter { /* These arrays hold the smallest and biggest values that have been "seen: */ private float[] minimum; private float[] maximum; public autoAdjustFilter(SampleProvider source) { super(source); /* Now the source and sampleSize are known. The arrays can be initialized */ minimum = new float[sampleSize]; maximum = new float[sampleSize]; reset(); } public void reset() { /* Set the arrays to their initial value */ for (int i = 0; i < sampleSize; i++) { minimum[i] = Float.POSITIVE_INFINITY; maximum[i] = Float.NEGATIVE_INFINITY; } } /* * To create a filter one overwrites the fetchSample method. A sample must * first be fetched from the source (a sensor or other filter). Then it is * processed according to the function of the filter */ public void fetchSample(float[] sample, int offset) { super.fetchSample(sample, offset); for (int i = 0; i < sampleSize; i++) { if (minimum[i] > sample[offset + i]) minimum[i] = sample[offset + i]; if (maximum[i] < sample[offset + i]) maximum[i] = sample[offset + i]; sample[offset + i] = (sample[offset + i] - minimum[i]) / (maximum[i] - minimum[i]); } } }//End autoAdjustFilter class } //End EV3FirstLineFollower <file_sep>/ev3_rescue_pots/build.properties source.dir=src lib.dir=${env.EV3_HOME}/lib/ev3 class.dir=build jar.dir=dist main-class=EV3RescuePots lejos.home=${env.EV3_HOME} ev3.host=10.0.1.1
7e295d4aa9d69165802145b4f3bcc4266f0d477b
[ "Java", "INI" ]
2
Java
Zar21/Ev3
3ba9f70b1346b5cfbb4e0391a5fb2dafe6edbbbb
eb381760851206074786f90f5c3bb1e53fbdf41f
refs/heads/main
<file_sep># Tetrad Builder An interactive tool for applying [<NAME>'s](https://www.jesseschell.com/) game design tetrad <file_sep>/** @jsxImportSource theme-ui */ import React, { useContext, useEffect, useState } from 'react' import { Cards, Data } from '../data/Store' import theme from '../theme' import useRAFSize from '../hooks/useRAFWindowSize' import firebase from 'firebase' import { useDrop } from 'react-dnd' import { DraggableTypes } from '../dndConsts' import Tag from './Tag' export default function ElementContent({ type, portrait, setVisible }) { const data = useContext(Data) const items = data[type] const size = useRAFSize() const [top, setTop] = useState() const [left, setLeft] = useState() const cards = useContext(Cards) const open = Object.keys(cards).length > 0 ? true : false useEffect(() => { const aspect = size.width/size.height if (portrait) { setLeft(`${(100-(36/aspect))/2}vw`) return } setTop(`${(100-(aspect*35))/2}vh`) }, [size, portrait, open]) const save = (el, card) => { const uid = firebase.database().ref(`/tetrads/${data.uid}/${el}`) .push() .getKey() firebase.database().ref(`/tetrads/${data.uid}/${el}/${uid}`) .set(card, err => { if (err) { alert('We had an issue connecting to the database. Sorry about that! Please try again.') return } }) } const [{ isOver }, drop] = useDrop({ accept: DraggableTypes.CARD, drop: (monitor) => { firebase.database().ref(`tetrads/${data.uid}/cards/${monitor.uid}`).remove() save(type, cards[monitor.uid]) }, collect: (monitor) => ({ isOver: !!monitor.isOver() }) }) return ( <div ref={drop} onClick={e => e.stopPropagation()} sx={{ bg:`${theme.colors[type]}CC`, height:portrait ? '35vh' : '35vw', width:portrait ? '35vh' : '35vw', position:'absolute', top:portrait ? open ? '24vh' : '34vh' : top, left:portrait ? left : open ? '30vw' : '32.5vw', filter:`drop-shadow(0 0 1rem ${theme.colors.Grey})`, p:'max(1vw, 20px)', display:'flex', flexWrap:'wrap', justifyContent:'space-between', alignContent:'flex-start', zIndex:1000, transition:'height .5s ease-in, width .5s ease-in, top .5s ease-in, left .5s ease-in' }}> {Object.keys(items).map((item, i) => <Tag item={items[item]} id={item} key={item} i={i} el={type} uid={data.uid}/>)} </div> ) } <file_sep>import firebase from 'firebase' export default function tetradSave(data, action) { switch (action.type) { case 'RESET': return { uid:null, name:null, mech:[], tech:[], story:[], aesth:[], } case 'CREATE': const uid = firebase.database().ref(`/tetrads`) .push() .getKey() firebase.database().ref(`/tetrads/${uid}`) .set({name:action.name,aesth:true,mech:true,story:true,tech:true}, err => { if (err) { alert('We had an issue connecting to the database. Sorry about that! Please try again.') return } }) return {...data, uid:uid, name:action.name} case 'OPEN': return {...data, uid:action.uid, name:action.name} case 'STORY': return {...data, story:action.update} case 'AESTH': return {...data, aesth:action.update} case 'MECH': return {...data, mech:action.update} case 'TECH': return {...data, tech:action.update} default: alert('Error updating game data') } } <file_sep>/** @jsxImportSource theme-ui */ import React, { useState, useContext, useEffect, useRef } from 'react' import CardsList from './CardsList' import { TetradSave, Data } from '../data/Store' import firebase from 'firebase' import { Select, Input } from 'theme-ui' export default function Inputs({ portrait, fbInstance }) { const [cardInput, setCardInput] = useState('') const [nameInput, setNameInput] = useState('') const [nameSelect, setNameSelect] = useState('') // const cards = useContext(Cards) // const updateCards = useContext(UpdateCards) const save = useContext(TetradSave) const data = useContext(Data) const [tetradList, setList] = useState([]) const x = useRef(null) const y = useRef(null) const [credits, setCredits] = useState('none') const createCard = e => { const uid = firebase.database().ref(`/tetrads/${data.uid}/cards`) .push() .getKey() firebase.database().ref(`/tetrads/${data.uid}/cards/${uid}`) .set(cardInput, err => { if (err) { alert('We had an issue connecting to the database. Sorry about that! Please try again.') return } }) setCardInput('') } const addToDB = () => { if (nameSelect) { const find = tetradList.filter(item => item.uid === nameSelect)[0] save({type:'OPEN',uid:nameSelect,name:find.name}) return } save({type:'CREATE',name:nameInput}) setNameInput('') } useEffect(() => { if (!data.uid && fbInstance) { firebase.database().ref(`/tetrads`).once('value', snapshot => { const list = snapshot.val() ? snapshot.val() : null if (list) { const options = Object.keys(list).map(item => ({uid:item,name:list[item].name})) setList(options) } }) } }, [data.uid, fbInstance]) const showCredits = e => { x.current = e.clientX y.current = e.clientY setCredits('visible') } return ( <div sx={{ position:'absolute', top:'3vh', left:'3vw', zIndex:1000, width:portrait? '35vw' : '25vw' }}> <div sx={{ display:'flex', flexDirection:'column', width:'100%', pl:portrait ? 0 : '10%', }}> {!data.uid && <> <h2 sx={{ fontSize:'medium', fontFamily:'tetrad', color:'Grey', mt:portrait ? 0 : '.83em', mb:0, lineHeight:'3vmin', }} > The Tetrad<span onMouseEnter={showCredits} onMouseLeave={() => setCredits('none')}>*</span> </h2> <div sx={{ position:'fixed', display:credits, top:y.current, left:x.current, color:'light', bg:'story', p:'10px', width:'15vw', fontFamily:'body', fontWeight:'heading' }}> From <NAME>'s <em>The Art of Game Design: A Book of Lenses</em> </div> </> } {!data.uid && <> <h2 sx={{ fontSize:'tiny', fontFamily:'tetrad', fontWeight:'bold', color:'aesth', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > Choose a game or class to explore </h2> <Select value={nameSelect} onChange={e=>{setNameSelect(e.target.value);setNameInput('')}} sx={{ width:'min(90%, 400px)', fontSize:'teensy', fontFamily:'body', color:'Grey', bg:'light' }}> <option value={''}>select...</option> {tetradList.map((item, i) => <option value={item.uid} key={i}>{item.name}</option>)} </Select> <h2 sx={{ fontSize:'tiny', fontFamily:'tetrad', fontWeight:'bold', color:'aesth', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > ...or add a new one </h2> <Input type='text' maxLength='50' placeholder='' value={nameInput} onChange={e=>{setNameInput(e.target.value);setNameSelect('')}} sx={{ width:'min(90%, 400px)', fontSize:'teensy', fontFamily:'body', bg:'light', color:'Grey' }}/> <button onClick={addToDB} sx={{ borderRadius:'1vmin', border:'none', bg:'aesth', color:'light', fontSize:'teensy', fontFamily:'body', width:portrait ? '50%' : 'min(30%, 135px)', height:'4vmin', mt:[2,3,4], cursor:'pointer' }} > start </button> </> } {data.uid && <> <h2 sx={{ fontSize:'medium', fontFamily:'tetrad', fontWeight:'bold', color:'aesth', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > {data.name} </h2> <h2 sx={{ fontSize:'teensy', fontFamily:'body', color:'Grey', fontWeight:'normal', mt:0, mb:'1em' }} > Create cards and drag and drop to fill out the tetrad </h2> <Input type='text' maxLength='50' placeholder='Create a new card...' value={cardInput} onChange={e=>setCardInput(e.target.value)} sx={{ width:'min(90%, 400px)', fontSize:'teensy', fontFamily:'body', bg:'light', color:'Grey' }}/> <button onClick={createCard} sx={{ borderRadius:'1vmin', border:'none', bg:'aesth', color:'light', fontSize:'teensy', fontFamily:'body', width:portrait ? '50%' : 'min(30%, 135px)', height:'4vmin', mt:[2,3,4], cursor:'pointer' }} > create </button> </> } </div> </div> ) } <file_sep>/** @jsxImportSource theme-ui */ import React, { useContext } from 'react' import { useDrop } from 'react-dnd' import { DraggableTypes } from '../dndConsts' import { Cards, Data } from '../data/Store' import firebase from 'firebase' export default function Element(props) { const { fill, cx, cy, type, showContent } = props const cards = useContext(Cards) const data = useContext(Data) const save = (el, card) => { const uid = firebase.database().ref(`/tetrads/${data.uid}/${el}`) .push() .getKey() firebase.database().ref(`/tetrads/${data.uid}/${el}/${uid}`) .set(card, err => { if (err) { alert('We had an issue connecting to the database. Sorry about that! Please try again.') return } }) } const onDropCard = monitor => { firebase.database().ref(`tetrads/${data.uid}/cards/${monitor.uid}`).remove() save(type, cards[monitor.uid]) } const onDropTag = monitor => { save(type, data[monitor.el][monitor.uid]) firebase.database().ref(`tetrads/${data.uid}/${monitor.el}/${monitor.uid}`).remove() } const [{ isOver }, drop] = useDrop({ accept: [DraggableTypes.CARD, DraggableTypes.TAG], drop: (monitor) => { if (monitor.type === 'card') { onDropCard(monitor) return } onDropTag(monitor) }, collect: (monitor) => ({ isOver: !!monitor.isOver() }) }) const handleClick = e => { e.stopPropagation() showContent(prevContent => { if (prevContent.type === type) { return {visible:!prevContent.visible,type:type} } return {visible:true,type:type} }) } return ( <> <g ref={drop} sx={{cursor:'pointer'}} onClick={handleClick} > <circle cx={cx} cy={cy} r={isOver? 80 : 70.3} fill={fill} opacity={isOver? .8 : 1} /> {type === 'aesth' && <text transform="translate(241.37 74.22)" letterSpacing=".09em" fontWeight={700} fontFamily="KohinoorDevanagari-Bold,Kohinoor Devanagari" fontSize={12} fill="#fff" > {"A"} <tspan x={8.39} y={0} letterSpacing=".1em"> {"E"} </tspan> <tspan x={15.45} y={0} letterSpacing=".1em"> {"S"} </tspan> <tspan letterSpacing=".1em" x={22.58} y={0}> {"T"} </tspan> <tspan x={29.73} y={0}> {"H"} </tspan> <tspan x={38.69} y={0} letterSpacing=".11em"> {"E"} </tspan> <tspan x={45.93} y={0} letterSpacing=".1em"> {"T"} </tspan> <tspan x={53.07} y={0} letterSpacing=".1em"> {"I"} </tspan> <tspan letterSpacing=".1em" x={57.09} y={0}> {"C"} </tspan> <tspan letterSpacing=".1em" x={65.24} y={0}> {"S"} </tspan> </text> } {type === 'mech' && <text transform="translate(32.49 281.44)" fontFamily="KohinoorDevanagari-Bold,Kohinoor Devanagari" fontWeight={600} letterSpacing=".09em" fontSize={12} fill="#fff" > {"M"} <tspan x={11.67} y={0} letterSpacing=".08em"> {"E"} </tspan> <tspan x={19.18} y={0} letterSpacing=".1em"> {"C"} </tspan> <tspan x={27.32} y={0} letterSpacing=".1em"> {"H"} </tspan> <tspan x={37.07} y={0} letterSpacing=".1em"> {"A"} </tspan> <tspan x={45.95} y={0}> {"N"} </tspan> <tspan x={55.62} y={0}> {"I"} </tspan> <tspan x={60.48} y={0} letterSpacing=".12em"> {"C"} </tspan> <tspan letterSpacing=".1em" x={68.94} y={0}> {"S"} </tspan> </text> } {type === 'tech' && <text transform="translate(234.23 487.75)" fontFamily="KohinoorDevanagari-Bold,Kohinoor Devanagari" letterSpacing=".1em" fontWeight={700} fontSize={12} fill="#fff" > {"T"} <tspan x={7.33} y={0} letterSpacing=".08em"> {"E"} </tspan> <tspan letterSpacing=".1em" x={15.07} y={0}> {"C"} </tspan> <tspan x={23.33} y={0} letterSpacing=".09em"> {"H"} </tspan> <tspan x={33.1} y={0}> {"N"} </tspan> <tspan x={43.02} y={0} letterSpacing=".09em"> {"O"} </tspan> <tspan letterSpacing=".1em" x={52.24} y={0}> {"L"} </tspan> <tspan letterSpacing=".1em" x={59.5} y={0}> {"O"} </tspan> <tspan x={68.78} y={0}> {"G"} </tspan> <tspan letterSpacing=".1em" x={77.91} y={0}> {"Y"} </tspan> </text> } {type === 'story' && <text transform="translate(464.93 280.86)" letterSpacing=".1em" fontWeight={700} fontFamily="KohinoorDevanagari-Bold,Kohinoor Devanagari" fontSize={12} fill="#fff" > {"S"} <tspan x={7.13} y={0} letterSpacing=".08em"> {"T"} </tspan> <tspan letterSpacing=".1em" x={14} y={0}> {"O"} </tspan> <tspan x={22.14} y={0} letterSpacing=".08em"> {"R"} </tspan> <tspan letterSpacing=".1em" x={30.81} y={0}> {"Y"} </tspan> </text> } </g> </> ) } <file_sep>export const firebaseConfig = { apiKey: "<KEY>", authDomain: "lets-play-seminar.firebaseapp.com", databaseURL: "https://lets-play-seminar-default-rtdb.firebaseio.com", projectId: "lets-play-seminar", storageBucket: "lets-play-seminar.appspot.com", messagingSenderId: "258039209716", appId: "1:258039209716:web:56248e7a2099933ed308a1", measurementId: "G-5EC302KFXK" } <file_sep>/** @jsxImportSource theme-ui */ import React, { useState, useContext, useEffect } from 'react' import CardsList from './CardsList' import { Cards, UpdateCards, TetradSave, Data } from '../src/data/Store' import firebase from 'firebase' import { Select, Input } from 'theme-ui' export default function Sidebar({ portrait, fbInstance }) { const [cardInput, setCardInput] = useState('') const [nameInput, setNameInput] = useState('') const [nameSelect, setNameSelect] = useState('') const cards = useContext(Cards) const updateCards = useContext(UpdateCards) const save = useContext(TetradSave) const data = useContext(Data) const [tetradList, setList] = useState([]) const createCard = e => { updateCards([...cards, cardInput]) setCardInput('') } const addToDB = () => { if (nameSelect) { const find = tetradList.filter(item => item.uid === nameSelect)[0] save({type:'OPEN',uid:nameSelect,name:find.name}) return } save({type:'CREATE',name:nameInput}) setNameInput('') } useEffect(() => { if (!data.uid && fbInstance) { firebase.database().ref(`/tetrads`).once('value', snapshot => { const list = snapshot.val() ? snapshot.val() : null if (list) { const options = Object.keys(list).map(item => ({uid:item,name:list[item].name})) setList(options) } }) } }, [data.uid, fbInstance]) return ( <div sx={{ height:portrait ? '40vh' : '100vh', width:portrait ? '100vw' : '40vw', bg:'Grey', display:'flex', flexDirection:portrait ? 'row' : 'column', p:[3,4,5] }}> <div sx={{ display:'flex', flexDirection:'column', width:portrait ? '30%' : '100%', pl:portrait ? 0 : '10%', }}> <h2 sx={{ fontSize:'medium', fontFamily:'tetrad', fontWeight:'bold', color:'light', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > The Tetrad </h2> {!data.uid && <> <h2 sx={{ fontSize:'tiny', fontFamily:'tetrad', fontWeight:'bold', color:'aesth', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > Choose a game or class to explore </h2> <Select value={nameSelect} onChange={e=>{setNameSelect(e.target.value);setNameInput('')}} sx={{ width:'90%', fontSize:'teensy', fontFamily:'tetrad', bg:'light' }}> <option value={''}>select...</option> {tetradList.map((item, i) => <option value={item.uid} key={i}>{item.name}</option>)} </Select> <h2 sx={{ fontSize:'tiny', fontFamily:'tetrad', fontWeight:'bold', color:'aesth', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > ...or add a new one </h2> <Input type='text' maxLength='50' placeholder='' value={nameInput} onChange={e=>{setNameInput(e.target.value);setNameSelect('')}} sx={{ width:'90%', fontSize:'teensy', fontFamily:'tetrad', bg:'light' }}/> <button onClick={addToDB} sx={{ borderRadius:'1vmin', border:'none', bg:'aesth', color:'light', fontSize:'teensy', fontFamily:'body', width:portrait ? '50%' : '20%', mt:[2,3,4] }} > start </button> </> } {data.uid && <> <h2 sx={{ fontSize:'medium', fontFamily:'tetrad', fontWeight:'bold', color:'aesth', mt:portrait ? 0 : '.83em', lineHeight:'3vmin', }} > {data.name} </h2> <h2 sx={{ fontSize:'teensy', fontFamily:'body', color:'DarkGrey1', fontWeight:'normal', mt:0, mb:'1em' }} > Create cards and drag and drop to fill out the tetrad </h2> <Input type='text' maxLength='50' placeholder='Create a new card...' value={cardInput} onChange={e=>setCardInput(e.target.value)} sx={{ width:'80%', fontSize:'teensy', fontFamily:'tetrad', bg:'light' }}/> <button onClick={createCard} sx={{ borderRadius:'1vmin', border:'none', bg:'aesth', color:'light', fontSize:'teensy', fontFamily:'body', width:portrait ? '50%' : '20%', mt:[2,3,4] }} > create </button> </> } </div> {data.uid && <div sx={{ display:'flex', flexDirection:'column', width:portrait ? '70%' : '100%', pl:portrait ? '3%' : 0 }}> {!portrait && <> <h3 sx={{ fontSize:'small', fontFamily:'tetrad', fontWeight:'bold', color:'light', mt:portrait ? 0 : '7vmin', mb:0, }}> Available Cards </h3> <p sx={{ fontSize:'miniscule', fontFamily:'body', color:'DarkGrey2', mt:'1vmin' }} > Drag to add to tetrad </p> </> } {portrait && <> <div sx={{ display:'flex', justifyContent:'flex-start', alignItems:'flex-end', }}> <h3 sx={{ fontSize:'small', fontFamily:'tetrad', fontWeight:'bold', color:'light', m:0, lineHeight:'3vmin' }} > Available Cards <span sx={{ fontSize:'miniscule', fontFamily:'body', fontWeight:'normal', color:'DarkGrey2', m:0, pl:'1em' }} > (Drag to add to tetrad) </span> </h3> </div> </> } <CardsList cards={cards} portrait={portrait} /> </div> } </div> ) } <file_sep>/** @jsxImportSource theme-ui */ import React from 'react' import { useDrag } from 'react-dnd' import { DraggableTypes } from '../dndConsts' const Card = ({ text, num, portrait, uid }) => { const [{ isDragging }, drag] = useDrag({ item: { type: DraggableTypes.CARD, uid: uid }, collect: (monitor) => ({ isDragging: !!monitor.isDragging() }) }) return ( <div ref={drag} sx={{ width:portrait ? '17vw' : '13vw', height:portrait ? '10vw' : '8vw', background:'linear-gradient(to right bottom, #62c4d6,#a3509f,#db742b,#e0c73a)', fontFamily:'body', fontSize:'miniscule', color:'DarkGrey1', mt:'2vmin', mr:'1vw', p:'10px', textAlign:'center', display:'flex', flexDirection:'column', justifyContent:'center', opacity: isDragging ? 0.5 : 1, ':hover': {border: !isDragging ? '2px solid white' : ''} }} > {text} </div> ) } export default function CardsList({ cards, portrait }){ return ( <div sx={{ display:'flex', flexDirection:portrait? 'row' : 'column', justifyContent:'flex-start', flexWrap:'wrap' }} > {Object.keys(cards).map((card, i) => <Card key={card} uid={card} num={i+1} text={cards[card]} portrait={portrait}/>)} </div> ) } <file_sep>/** @jsxImportSource theme-ui */ import React, { useState, useEffect, useContext, useMemo, useReducer } from 'react' import TetradSVG from './Svgr' import Content from './ElementContent' import { Cards } from '../data/Store' export default function Tetrad({ portrait }) { const [content, setContent] = useState({visible:false,type:''}) const cards = useContext(Cards) const open = Object.keys(cards).length > 0 ? true : false const viewBox = portrait ? `-10 -25 580 580` : `-10 -10 580 580` const closeContentPane = () => { if (content.visible) { setContent({visible:false,type:''}) } } return ( <div onClick={closeContentPane} sx={{ height:portrait ? open ? '80vh' : '100vh' : '100vh', width:portrait ? '100vw' : open ? '95vw' : '100vw', display:'flex', justifyContent:'center', alignItems:'center', p:[3,4,5], bg:'light', transition:'width .5s ease-in, height .5s ease-in' }} > <TetradSVG viewBox={viewBox} showContent={setContent}/> {content.visible && <Content type={content.type} portrait={portrait} setVisible={setContent} /> } </div> ) } <file_sep>/** @jsxImportSource theme-ui */ import React, { useContext, useEffect, } from 'react' import Tetrad from './Tetrad' import useMediaQueries from '../hooks/useMediaQueries' import { Data, TetradSave, UpdateCards } from '../data/Store' import firebase from 'firebase' import CardTray from './CardTray' import Inputs from './Inputs' export default function TetradLayout({ fbInstance }) { const mQs = {portrait:'(orientation: portrait)'} const mediaVals = useMediaQueries(mQs) const data = useContext(Data) const save = useContext(TetradSave) const updateCards = useContext(UpdateCards) useEffect(() => { if (data.uid) { firebase.database().ref(`/tetrads/${data.uid}/story`).on('value', snapshot => { const update = snapshot.val() ? snapshot.val() : [] save({type:'STORY',update:update}) }) firebase.database().ref(`/tetrads/${data.uid}/aesth`).on('value', snapshot => { const update = snapshot.val() ? snapshot.val() : [] save({type:'AESTH',update:update}) }) firebase.database().ref(`/tetrads/${data.uid}/mech`).on('value', snapshot => { const update = snapshot.val() ? snapshot.val() : [] save({type:'MECH',update:update}) }) firebase.database().ref(`/tetrads/${data.uid}/tech`).on('value', snapshot => { const update = snapshot.val() ? snapshot.val() : [] save({type:'TECH',update:update}) }) firebase.database().ref(`/tetrads/${data.uid}/cards`).on('value', snapshot => { const update = snapshot.val() ? snapshot.val() : [] updateCards(update) }) return () => { firebase.database().ref(`/tetrads/${data.uid}/story`).off() firebase.database().ref(`/tetrads/${data.uid}/aesth`).off() firebase.database().ref(`/tetrads/${data.uid}/mech`).off() firebase.database().ref(`/tetrads/${data.uid}/tech`).off() firebase.database().ref(`/tetrads/${data.uid}/cards`).off() } } }, [data.uid, save, updateCards]) return ( <main sx={{ display:'flex', flexDirection:mediaVals.portrait ? 'column' : 'row', justifyContent:'flex-start', height:'100vh', width:'100vw', bg:'none' }} > <Inputs portrait={mediaVals.portrait} fbInstance={fbInstance}/> <CardTray portrait={mediaVals.portrait}/> <Tetrad portrait={mediaVals.portrait}/> </main> ) } <file_sep>import React from 'react' import { BrowserRouter as Router, Switch, Route } from 'react-router-dom' import TetradLayout from './views/TetradLayout' import { DndProvider } from 'react-dnd' import { HTML5Backend } from 'react-dnd-html5-backend' export default function AppRouter({ fbInstance }) { return ( <Router> <Switch> <Route exact path='/'> <DndProvider backend={HTML5Backend}> <TetradLayout fbInstance={fbInstance}/> </DndProvider> </Route> </Switch> </Router> ) } <file_sep>/** @jsxImportSource theme-ui */ import React from 'react' import firebase from 'firebase' import { useDrag } from 'react-dnd' import { DraggableTypes } from '../dndConsts' import theme from '../theme' export default function Tag({ item, id, i, el, uid }) { const [{ isDragging }, drag] = useDrag({ item: { type:DraggableTypes.TAG, i:i, uid:id, el:el }, collect: (monitor) => ({ isDragging: !!monitor.isDragging() }) }) const remove = e => id => { firebase.database().ref(`tetrads/${uid}/${el}/${id}`).remove() e.stopPropagation() } return ( <div ref={drag} sx={{ bg:'light', height:'3vmin', width:'48%', // border:`2px solid ${theme.colors.Grey}`, textAlign:'left', pl:'1%', pr:'1%', mb:'max(1vw, 20px)', filter:`drop-shadow(0 0 .25rem ${theme.colors.light})`, display:'flex', justifyContent:'space-between', alignItems:'center', }}> <div sx={{ overflow:'scroll', width:'80%' }}> <p key={i} sx={{ fontSize:'miniscule', lineHeight:'3vmin', fontFamily:'body', color:'Grey', m:0, p:0, whiteSpace:'nowrap' }}> {item} </p> </div> <button id='delete' onClick={e => remove(e)(id)} sx={{ display:'flex', justifyContent:'center', alignItems:'center', height:'2vmin', width:'2vmin', fontSize:'miniscule', p:0, m:0, border:'none', bg:'none', cursor:'pointer' }}> 🚫 </button> </div> ) } <file_sep>import React from 'react' import Element from './Element' export default function TetradSVG({ viewBox, showContent }) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox={viewBox} width='100%' height='100%' > <g data-name="Layer 1"> <path fill='none' stroke='#000' strokeMiterlimit='10' transform="rotate(45 276.94 276.742)" d="M130.73 130.53h292.42v292.42H130.73z" /> <path fill='none' stroke='#000' strokeMiterlimit='10' d="M276.94 70.3v413.28M483.58 276.94H70.3" /> <Element cx={276.94} cy={70.3} r={70.3} fill="#a3509f" type='aesth' showContent={showContent} /> <Element cx={276.94} cy={483.58} r={70.3} fill="#62c4d6" type='tech' showContent={showContent} /> <Element cx={483.58} cy={276.94} r={70.3} fill="#db742b" type='story' showContent={showContent} /> <Element cx={70.3} cy={276.94} r={70.3} fill="#e0c73a" type='mech' showContent={showContent} /> </g> </svg> ); }
90cbdf41847cb68dd4477631d536fc1c8680db92
[ "Markdown", "JavaScript" ]
13
Markdown
1aurend/interactive-tetrad
864eb24fe538fa5cdc32ae4899879918da225973
bc0dbce67b783cec6c901e808ca1010fb5c1c286
refs/heads/master
<file_sep>import models_partc from sklearn.model_selection import ShuffleSplit, KFold from numpy import mean from sklearn.metrics import * import utils import numpy as np # USE THE GIVEN FUNCTION NAME, DO NOT CHANGE IT # USE THIS RANDOM STATE FOR ALL OF YOUR CROSS VALIDATION TESTS, OR THE TESTS WILL NEVER PASS RANDOM_STATE = 545510477 #input: training data and corresponding labels #output: accuracy, auc def get_acc_auc_kfold(X,Y,k=5): #TODO:First get the train indices and test indices for each iteration #Then train the classifier accordingly #Report the mean accuracy and mean auc of all the folds kfolds = KFold(n_splits=k, shuffle=False, random_state=RANDOM_STATE) acc_auc_array = [] for train, test in kfolds.split(X): X_train, Y_train = (X[train, :], Y[train]) X_test, Y_test = (X[test, :], Y[test]) Y_pred = models_partc.logistic_regression_pred(X_train, Y_train, X_test) acc, auc, _, _, _ = models_partc.classification_metrics(Y_pred, Y_test) acc_auc_array.append([acc, auc]) acc_auc_array = np.array(acc_auc_array) return np.mean(acc_auc_array[:, 0]), np.mean(acc_auc_array[:, 1]) #input: training data and corresponding labels #output: accuracy, auc def get_acc_auc_randomisedCV(X,Y,iterNo=5,test_size=0.2): #TODO: First get the train indices and test indices for each iteration #Then train the classifier accordingly #Report the mean accuracy and mean auc of all the iterations random_acc_auc_array = [] kfolds = ShuffleSplit(n_splits=iterNo, test_size=test_size) for train, test in kfolds.split(X): X_train, Y_train = (X[train, :], Y[train]) X_test, Y_test = (X[test, :], Y[test]) Y_pred = models_partc.logistic_regression_pred(X_train, Y_train, X_test) acc, auc, _, _, _ = models_partc.classification_metrics(Y_pred, Y_test) random_acc_auc_array.append([acc, auc]) random_acc_auc_array = np.array(random_acc_auc_array) return np.mean(random_acc_auc_array[:, 0]), np.mean(random_acc_auc_array[:, 1]) def main(): X,Y = utils.get_data_from_svmlight("../deliverables/features_svmlight.train") print("Classifier: Logistic Regression__________") acc_k,auc_k = get_acc_auc_kfold(X,Y) print(("Average Accuracy in KFold CV: "+str(acc_k))) print(("Average AUC in KFold CV: "+str(auc_k))) acc_r,auc_r = get_acc_auc_randomisedCV(X,Y) print(("Average Accuracy in Randomised CV: "+str(acc_r))) print(("Average AUC in Randomised CV: "+str(auc_r))) if __name__ == "__main__": main() <file_sep>import time import pandas as pd import numpy as np # PLEASE USE THE GIVEN FUNCTION NAME, DO NOT CHANGE IT def read_csv(filepath): ''' TODO : This function needs to be completed. Read the events.csv and mortality_events.csv files. Variables returned from this function are passed as input to the metric functions. ''' events = pd.read_csv(filepath + 'events.csv', parse_dates=['timestamp']) events = events.sort_values('timestamp') mortality = pd.read_csv(filepath + 'mortality_events.csv', parse_dates=['timestamp']) mortality = mortality.sort_values('timestamp') return events, mortality def event_count_metrics(events, mortality): ''' TODO : Implement this function to return the event count metrics. Event count is defined as the number of events recorded for a given patient. ''' patient_ids = events.patient_id.unique() dead_ids = mortality.patient_id alive_ids = pd.Series(list(set(patient_ids).difference(set(dead_ids)))) dead_events = events[events.patient_id.isin(dead_ids)] alive_events = events[events.patient_id.isin(alive_ids)] dead_group = dead_events.groupby('patient_id') alive_group = alive_events.groupby('patient_id') dead_count = dead_group.event_id.count() alive_count = alive_group.event_id.count() avg_dead_event_count = dead_count.mean() max_dead_event_count = dead_count.max() min_dead_event_count = dead_count.min() avg_alive_event_count = alive_count.mean() max_alive_event_count = alive_count.max() min_alive_event_count = alive_count.min() return min_dead_event_count, max_dead_event_count, avg_dead_event_count, min_alive_event_count, max_alive_event_count, avg_alive_event_count def encounter_count_metrics(events, mortality): ''' TODO : Implement this function to return the encounter count metrics. Encounter count is defined as the count of unique dates on which a given patient visited the ICU. ''' encounter_label = ['DIAG', 'DRUG', 'LAB'] patient_ids = events.patient_id.unique() dead_ids = mortality.patient_id alive_ids = pd.Series(list(set(patient_ids).difference(set(dead_ids)))) dead_events = events[events.patient_id.isin(dead_ids)] alive_events = events[events.patient_id.isin(alive_ids)] encounter_dead = dead_events[pd.Series(np.any([dead_events.event_id.str.contains(x) for x in encounter_label]), index=dead_events.index)] encounter_alive = alive_events[pd.Series(np.any([alive_events.event_id.str.contains(x) for x in encounter_label]), index=alive_events.index)] dead_group = encounter_dead.groupby('patient_id') alive_group = encounter_alive.groupby('patient_id') dead_counts = dead_group.apply(lambda x: x.timestamp.unique().size) alive_counts = alive_group.apply(lambda x: x.timestamp.unique().size) avg_dead_encounter_count = dead_counts.mean() max_dead_encounter_count = dead_counts.max() min_dead_encounter_count = dead_counts.min() avg_alive_encounter_count = alive_counts.mean() max_alive_encounter_count = alive_counts.max() min_alive_encounter_count = alive_counts.min() return min_dead_encounter_count, max_dead_encounter_count, avg_dead_encounter_count, min_alive_encounter_count, max_alive_encounter_count, avg_alive_encounter_count def record_length_metrics(events, mortality): ''' TODO: Implement this function to return the record length metrics. Record length is the duration between the first event and the last event for a given patient. ''' patient_ids = events.patient_id.unique() dead_ids = mortality.patient_id alive_ids = pd.Series(list(set(patient_ids).difference(set(dead_ids)))) dead_events = events[events.patient_id.isin(dead_ids)] alive_events = events[events.patient_id.isin(alive_ids)] dead_group = dead_events.groupby('patient_id') alive_group = alive_events.groupby('patient_id') dead_len = dead_group.apply(lambda x: (x.timestamp.iloc[-1] - x.timestamp.iloc[0]).days) alive_len = alive_group.apply(lambda x: (x.timestamp.iloc[-1] - x.timestamp.iloc[0]).days) avg_dead_rec_len = dead_len.mean() max_dead_rec_len = dead_len.max() min_dead_rec_len = dead_len.min() avg_alive_rec_len = alive_len.mean() max_alive_rec_len = alive_len.max() min_alive_rec_len = alive_len.min() return min_dead_rec_len, max_dead_rec_len, avg_dead_rec_len, min_alive_rec_len, max_alive_rec_len, avg_alive_rec_len def main(): ''' DO NOT MODIFY THIS FUNCTION. ''' # You may change the following path variable in coding but switch it back when submission. train_path = '../data/train/' # DO NOT CHANGE ANYTHING BELOW THIS ---------------------------- events, mortality = read_csv(train_path) #Compute the event count metrics start_time = time.time() event_count = event_count_metrics(events, mortality) end_time = time.time() print(("Time to compute event count metrics: " + str(end_time - start_time) + "s")) print(event_count) #Compute the encounter count metrics start_time = time.time() encounter_count = encounter_count_metrics(events, mortality) end_time = time.time() print(("Time to compute encounter count metrics: " + str(end_time - start_time) + "s")) print(encounter_count) #Compute record length metrics start_time = time.time() record_length = record_length_metrics(events, mortality) end_time = time.time() print(("Time to compute record length metrics: " + str(end_time - start_time) + "s")) print(record_length) if __name__ == "__main__": main() <file_sep>import utils import pandas as pd import numpy as np import etl import time from sklearn import preprocessing from sklearn.pipeline import Pipeline from sklearn import feature_selection from sklearn.model_selection import GridSearchCV from sklearn .feature_extraction.text import CountVectorizer from sklearn.svm import LinearSVC, LinearSVR, SVC, SVR from sklearn.ensemble import GradientBoostingClassifier ,BaggingClassifier, ExtraTreesClassifier, RandomForestClassifier from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.linear_model import LarsCV, LassoCV, LogisticRegressionCV,ElasticNetCV, RidgeClassifierCV, OrthogonalMatchingPursuitCV, LassoLarsCV, MultiTaskElasticNetCV #Note: You can reuse code that you wrote in etl.py and models.py and cross.py over here. It might help. # PLEASE USE THE GIVEN FUNCTION NAME, DO NOT CHANGE IT ''' You may generate your own features over here. Note that for the test data, all events are already filtered such that they fall in the observation window of their respective patients. Thus, if you were to generate features similar to those you constructed in code/etl.py for the test data, all you have to do is aggregate events for each patient. IMPORTANT: Store your test data features in a file called "test_features.txt" where each line has the patient_id followed by a space and the corresponding feature in sparse format. Eg of a line: 60 971:1.000000 988:1.000000 1648:1.000000 1717:1.000000 2798:0.364078 3005:0.367953 3049:0.013514 Here, 60 is the patient id and 971:1.000000 988:1.000000 1648:1.000000 1717:1.000000 2798:0.364078 3005:0.367953 3049:0.013514 is the feature for the patient with id 60. Save the file as "test_features.txt" and save it inside the folder deliverables input: output: X_train,Y_train,X_test ''' def my_features(): #TODO: complete this train_events, train_mortality, feature_map = read_from_csv('../data/train/') entire_feature_set = set(feature_map.idx.unique()) test_events, _, _ = read_from_csv('../data/test/') train_events = process_training_data(train_events.iloc[:, :], train_mortality) train_features, test_features = process_features(train_events, test_events) patient_id_series = pd.Series(train_features.index, index=train_features.index) dead_ids_list = list(train_mortality.patient_id) train_labels = np.array([id in dead_ids_list for id in list(patient_id_series)]) X_train = train_features Y_train = train_labels X_test = test_features.sort_index() test_features.index.name = 'patient_id' test_features_long = pd.melt(test_features.reset_index(), id_vars=['patient_id']) test_features_long.columns = ['patient_id', 'feature_id', 'feature_value'] test_features_long = test_features_long.sort_values('patient_id') tuple_temp = test_features_long.groupby('patient_id').apply(lambda x: list(x.sort_values('feature_id').apply(lambda y: (y.feature_id, y.feature_value), axis=1))) patient_features_dict = tuple_temp.to_dict() deliverable1 = open('../deliverables/test_features.txt', 'wb') for patient in sorted(patient_features_dict.keys()): deliverable1.write(bytes("{} {} \n".format(patient, utils.bag_to_svmlight(patient_features_dict[patient])),'UTF-8')) return X_train,Y_train,X_test ''' You can use any model you wish. input: X_train, Y_train, X_test output: Y_pred ''' def my_classifier_predictions(X_train,Y_train,X_test): #TODO: complete this model = train_model(X_train, Y_train) model_train_pred = model.predict_proba(X_train) model_test_pred = model.predict_proba(X_test) utils.generate_submission("../deliverables/test_features.txt", model.predict_proba(X_test)[:, 1]) return model.predict(X_test).astype(int) def read_from_csv(filepath): try: events = pd.read_csv(filepath + 'events.csv', parse_dates=['timestamp']) events = events.sort_values('timestamp') except IOError: events = None try: mortality = pd.read_csv(filepath + 'mortality_events.csv', parse_dates=['timestamp']) mortality = mortality.sort_values('timestamp') except IOError: mortality = None try: feature_map = pd.read_csv(filepath + 'event_feature_map.csv') except IOError: events = None return events, mortality, feature_map def process_training_data(train_events, train_mortality): indx_date = etl.calculate_index_date(train_events, train_mortality, '/tmp/') return etl.filter_events(train_events, indx_date, '/tmp/') def process_features(train_df, test_df): train_desc = train_df.groupby('patient_id').event_description.apply(lambda x: x.str.cat(sep = ' ')) test_desc = test_df.groupby('patient_id').event_description.apply(lambda x: x.str.cat(sep =' ')) count_vectorizer = CountVectorizer(ngram_range=(1,2), min_df=0.2, max_df=0.75) train_events = count_vectorizer.fit_transform(train_desc) test_events = count_vectorizer.transform(test_desc) return (pd.DataFrame(train_events.toarray(), index=train_desc.index), pd.DataFrame(test_events.toarray(), index=test_desc.index)) def train_model(X_train, Y_train): model_temp = Pipeline(steps=[('red',preprocessing.MinMaxScaler()), ('model_temp', RandomForestClassifier())]) paramters = dict(model_temp__n_estimators=np.arange(20, 181, 20), model_temp__min_samples_split=np.arange(5, 101, 40), model_temp__min_samples_leaf=np.arange(1,11,3)) model_temp = GridSearchCV(model_temp, paramters, n_jobs=30, scoring='roc_auc', verbose=0, cv=5) model_temp.fit(X_train,Y_train) best_model_temp = model_temp.best_estimator_ return best_model_temp def main(): X_train, Y_train, X_test = my_features() Y_pred = my_classifier_predictions(X_train,Y_train,X_test) utils.generate_submission("../deliverables/test_features.txt",Y_pred) #The above function will generate a csv file of (patient_id,predicted label) and will be saved as "my_predictions.csv" in the deliverables folder. if __name__ == "__main__": main()
2bc001c5cbc07923d2bc60d018463e1e0c70e357
[ "Python" ]
3
Python
shaangill025/healthcare-descriptive-stats-numpy-feat-construction-pandas-ml-sklearn
64665583713c8e2ac0afbe5f56e0ee75c61aa073
7c9b0f78e28192158fccbb2a879fd7401d916c5f
refs/heads/master
<file_sep>package org.csystem.app; import org.csystem.collection.GenericArrayList; public class App { public static void main(String[] args) { //elemenları string olan veri yapısı. GenericArrayList<String> list = new GenericArrayList<>(); list.add("ankara"); } } <file_sep>package org.csystem.collection; //Sen T türünden nesneler tutuyorsun. Seni T ile açıyorum. public class GenericArrayList<T> { private static final int DEFAULT_CAPACITY = 10; private T [] m_elems; private int m_index; private void allocateCapacity(int capacity) { T [] temp = (T[]) new Object[capacity]; for (int i = 0; i < m_index; ++i) temp[i] = m_elems[i]; m_elems = temp; } public GenericArrayList() { this(DEFAULT_CAPACITY); } public GenericArrayList(int initialCapacity) { if (initialCapacity < 0) throw new IllegalArgumentException("invalid initialCapacity values"); m_elems = (T[]) new Object[initialCapacity == 0 ? DEFAULT_CAPACITY : initialCapacity]; } public boolean add(T elem) { //kontrol if (m_index == m_elems.length) this.allocateCapacity(m_elems.length * 2); m_elems[m_index++] = elem; return true; } public T get(int index) { //kontrol if (index < 0 || index >= m_index) throw new ArrayIndexOutOfBoundsException("index < 0 || index >= m_index"); return m_elems[index]; } }
d535b530d2f3ced83d5143c5458f23e9ad0d424e
[ "Java" ]
2
Java
tcelik/GenericArrayList
7582d02aa279689963beeac178d54abc82aa4296
4c0b234b1c5c6aaf943b88ac84477b4dbb5e4cc2
refs/heads/master
<file_sep># load libraries library(dplyr) # get working directory path.folder <- getwd() # set paths to input/output files path.features <- paste(path.folder, "/features.txt", sep = "") path.train.x <- paste(path.folder, "/train/X_train.txt", sep = "") path.train.y <- paste(path.folder, "/train/y_train.txt", sep = "") path.train.subject <- paste(path.folder, "/train/subject_train.txt", sep = "") path.test.x <- paste(path.folder, "/test/X_test.txt", sep = "") path.test.y <- paste(path.folder, "/test/y_test.txt", sep = "") path.test.subject <- paste(path.folder, "/test/subject_test.txt", sep = "") path.activity <- paste(path.folder, "/activity_labels.txt", sep = "") path.tidy.dataset <- paste(path.folder, "/tidy_dataset.txt", sep = "") # load reference files to dataframe features <- read.table(path.features, col.names=c("id", "name"), stringsAsFactors=F) activity <- read.table(path.activity, col.names=c("id", "name")) # clean feature names features$name = tolower(features$name) # to lower case features$name = gsub("\\(\\)", "", features$name) # remove parenthesis () features$name = gsub("-|,", ".", features$name) # replace hyphens - and commas , # load data files to dataframe test.subject <- read.table(path.test.subject, col.names="subject.id") test.y <- read.table(path.test.y, col.names="y.id") test.x <- read.table(path.test.x, col.names=features$name, check.names=F) train.subject <- read.table(path.train.subject, col.names="subject.id") train.y <- read.table(path.train.y, col.names="y.id") train.x <- read.table(path.train.x, col.names=features$name, check.names=F) # gather test dataset test.data <- bind_cols(test.subject, test.y, test.x) # gather training dataset train.data <- bind_cols(train.subject, train.y, train.x) # merge training and test datatsets (task #1) full.data <- bind_rows(train.data, test.data) # filter mean/std variables (task #2) full.data <- select(full.data, 1:2, matches("\\.mean(\\.|$)|\\.std(\\.|$)")) # append activity label by join (task #3) full.data <- merge(full.data, activity, by.x="y.id", by.y="id") # order and rename variables (task #4) full.data <- select(full.data, subject.id, activity.id=y.id, activity.name=name, everything()) # average all measurements by subject and activity (task #5) avg.data <- full.data %>% group_by(subject.id, activity.id, activity.name) %>% summarize_all(mean) # write dataset to file write.table(avg.data, path.tidy.dataset, row.name=FALSE) # write dataset to output print.data.frame(avg.data) <file_sep># Code Book ## Description This file describes the program implemented in [run_analysis.R](./run_analysis.R) file. The goal of this program is to process a complex dataset generated by human activity measurements recorded by the sensors of a smartphone (full information of this dataset in the [Dataset.md](./Dataset.md) file). The output of the program must be a unique, summarized tidy dataset. Files in dataset are fixed-width text files, `read.table` is the method used to load content into dataframes. Most of transformations are operated using `dplyr` package functions. ## Prerequisites This program expects Samsung dataset uncompressed in the working directory. ## Process steps The program is divided into 6 parts, steps of the code are described below. #### I. Set Paths 1. get working directory 2. assigns path of input and output files to variables `path.*` #### II. Load files into dataframes 1. load reference files into dataframes `features` and `activity` 2. clean feature names `features$name` : lowercase and special characters substitution 3. load test data files into dataframes `test.subject`, `test.y` and `test.x` 4. load training data files into dataframes `train.subject`, `train.y` and `train.x` NB : for `*.x` dataframes storing the measures, names of variables are specified using the `features` reference dataframe `col.names=features$name` (where names have bean cleaned in step 2) ; #### III. Gather dataframes 1. bind test.subject, test.y and test.x dataframes together, respectively and column-wise / store resulting dataset in `test.data` 2. bind train.subject, train.y and train.x dataframes together, respectively and column-wise / store resulting dataset in `train.data` 3. merge rows from both `test.data` and `train.data` obtained in previous steps / store resulting dataset in `full.data` NB : column binding used in step 1 & 2 is operated using the `bind_cols` function of `dplyr` package, idem for step 3 with `bind_rows` #### IV. Adjust variables 1. keep only mean/std measures from `full.data` using `select()` and `matches()` from `dplyr` package, reassign result to `full.data` 2. append activity labels to `full.data` using `merge()`, reassign result to `full.data` 3. order and rename variables tidily using `select()` from `dplyr` package, reassign result to `full.data` #### V. Aggregate variables 1. average all measurements of `full.data` order by subject (id) and activity (id and name) using `group_by` and `summarize_all` functions from `dplyr` package 2. store resulting dataframe in `avg.data` #### VI. Write output 1. write `avg.data` to the file `tidy_dataset.txt` in working directory 2. output `avg.data` to console using `data.frame.print` <file_sep>## Dataset information 1. download link : [dataset.zip](https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip) 2. description : [Human Activity Recognition Using Smartphones Data Set](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones) 3. content : - `README.txt` : description of this dataset - `features_info`.txt : information about the selected 561 features and their measurement/calculation methods - `features.txt` : list of the 561 features contained in this dataset (format : fixed-width, one-space separated) - `activity_labels.txt` : list of activities id and label (format : fixed-width, one-space separated) - `train/subject_train.txt` : each row identifies the subject of the training set who performed the activity (range is from 1 to 30) - `train/X_train.txt`(*) : each row contains the 561 measures for the training set (format : fixed-width, one-space separated) - `train/y_train.txt` : each row identifies the activity performed by the subject of the training set (range is from 1 to 6) - `test/subject_test.txt` : each row identifies the subject of the test set who performed the activity (range is from 1 to 30) - `test/X_test.txt`(*) : each row contains the 561 measures for the test set (format : fixed-width, 1 field=16 characters, one-space separated) - `test/y_test.txt` : each row identifies the activity performed by subject of the test set (range is from 1 to 6) (*) the format of X_test.txt and X_train.txt is : - format : fixed-width - 1 field = 16 characters : -- 1st character = space -- 2nd character = space for positive numbers or - (minus) for negative numbers - number format : exponential (ex: -1.7637793e-002) <file_sep>## Coursera - Data Science Specialization #### Course 04 - Getting and Cleaning Data #### Programming Assignment 04 ### PA Description Getting and Cleaning Data Course Project The purpose of this project is to demonstrate your ability to collect, work with, and clean a data set. The goal is to prepare tidy data that can be used for later analysis. You will be graded by your peers on a series of yes/no questions related to the project. You will be required to submit: 1. a tidy data set as described below, 2. a link to a Github repository with your script for performing the analysis, and 3. a code book that describes the variables, the data, and any transformations or work that you performed to clean up the data called CodeBook.md. ### Review criteria 1. The submitted data set is tidy. 2. The Github repo contains the required scripts. 3. GitHub contains a code book that modifies and updates the available codebooks with the data to indicate all the variables and summaries calculated, along with units, and any other relevant information. 4. The README that explains the analysis files is clear and understandable. 5. The work submitted for this project is the work of the student who submitted it. You should also include a README.md in the repo with your scripts. This repo explains how all of the scripts work and how they are connected. ## Content * [CodeBook.md](./CodeBook.md) : desciption of the program * [Dataset.md](./Dataset.md) : information on the Samsung dataset * [README.md](./README.md) : this file * [run_analysis.R](./run_analysis.R) : program of the programming assignment ## Author N.Straw ## License No licence
813f9b9d9e6c2ce52fa24f5851d7e896707718ac
[ "Markdown", "R" ]
4
R
nstraw/Coursera-DSS-PA4
2c28943256b47d5bfc28f3ab62e0c5a37f0d35c7
25b5e414783a6106810c3aa7904854a028f1389f
refs/heads/master
<file_sep>plot4<-function(dat_file){ if(!file.exists(dat_file)) stop("Input file not found ..please check file path") #vector for funtion use date_time<-double() Global_active_power<-double() Global_reactive_power<-double() Voltage<-double() #Global_intensity<-double() Sub_metering_1<-double() Sub_metering_2<-double() Sub_metering_3<-double() #read file one line at a time content <- file(dat_file, open = "r") on.exit(close(content)) line <- readLines(content, n = 1) unlist_data <- unlist((strsplit(line, ";"))) i<-1 print("loadig data.....this can take a few minutes") #load data if it is witn in date range while (length(line <- readLines(content, n = 1)) > 0) { unlist_data <- unlist((strsplit(line, ";"))) date_val<-as.Date(unlist_data[1],"%d/%m/%Y") if(date_val >= "2007-2-1" && date_val < "2007-2-3" && unlist_data[7]!="?" && unlist_data[8]!="?" && unlist_data[9]!="?"){ #date_time[i]<-paste(date_val,unlist_data[2]) date_time[i]=weekdays(date_val) Global_active_power[i]<-as.double(unlist_data[3]) Global_reactive_power[i]<-as.double(unlist_data[4]) Voltage[i]<-as.double(unlist_data[5]) #Global_intensity[i]<-unlist_data[6]war Sub_metering_1[i]<-as.double(unlist_data[7]) Sub_metering_2[i]<-as.double(unlist_data[8]) Sub_metering_3[i]<-as.double(unlist_data[9]) i<-i+1 } #break if it is outside date range if(date_val > "2007-2-2") break; } plot4_data_frame<-data.frame(date_time, Global_active_power, Global_reactive_power, Voltage, #Global_intensity, Sub_metering_1, Sub_metering_2, Sub_metering_3 ) #png device for saving graph png(filename = "figure/plot4.png", width = 480, height = 480,units = "px") #graph setting par(mar=c(6,4,2,1)) par(mfcol=c(2,2)) #graph1 Global Active Power #par(mar=c(2,2,2,2)) plot(plot4_data_frame$Global_active_power,type="n",axes=FALSE,ann=FALSE) #m<-barplot(plot2_data_frame$Global_active_power) lines(plot4_data_frame$Global_active_power) box() axis(1,at=c(1,2880/2,2880),lab=c("Thu","Fri","Sat")) axis(2,at=c(0,2,4,6),lab=c("0","2","4","6")) title(ylab="Global Active Power (kilowatts)") #grap2 plot(plot4_data_frame$Sub_metering_1,type="n",axes=FALSE,ann=FALSE) lines(plot4_data_frame$Sub_metering_1,type="l") lines(plot4_data_frame$Sub_metering_2,type="l",col="Red") lines(plot4_data_frame$Sub_metering_3,type="l",col="Blue") box() axis(1,at=c(1,2880/2,2880),lab=c("Thu","Fri","Sat")) axis(2,at=c(0,10,20,30),lab=c("0","10","20","30")) legend("topright",col=c("Black","Red","Blue"),lty=c(1,1,1),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),cex=.6) title("", ylab="Energy sub metering") #graph 3 Voltage /Day #par(mar=c(2,6,4,1)) plot(plot4_data_frame$Voltage,type="n",axes=FALSE,ann=FALSE) lines(plot4_data_frame$Voltage,type="l") box( col = 'black') axis(1,at=c(1,2880/2,2880),lab=c("Thu","Fri","Sat")) axis(2,at=c(234,238,242,246),lab=c("234","238","242","246")) title(ylab="Voltage",xlab="datetime") #graph4 #par(mar=c(2,6,1,1)) plot(plot4_data_frame$Global_reactive_power,type="n",axes=FALSE,ann=FALSE) lines(plot4_data_frame$Global_reactive_power,type="l") box( col = 'black') axis(1,at=c(1,2880/2,2880),lab=c("Thu","Fri","Sat")) axis(2,at=c(0.0,0.1,0.2,0.3,0.4,0.5),lab=c("0.0","0.1","0.2","0.3","0.4","0.5")) title("", ylab="Global_reactive_power",xlab="datetime") dev.off() print("plot4.png saved in figure sub directory") }<file_sep>plot3<-function(dat_file){ if(!file.exists(dat_file)) stop("Input file not found ..please check file path") #vector for function use date_time<-double() Sub_metering_1<-double() Sub_metering_2<-double() Sub_metering_3<-double() #open file and read one line at a time content <- file(dat_file, open = "r") on.exit(close(content)) line <- readLines(content, n = 1) unlist_data <- unlist((strsplit(line, ";"))) i<-1 print("loadig data.....this can take a few minutes") while (length(line <- readLines(content, n = 1)) > 0) { unlist_data <- unlist((strsplit(line, ";"))) date_val<-as.Date(unlist_data[1],"%d/%m/%Y") #read data if it is within the range if(date_val >= "2007-2-1" && date_val < "2007-2-3" && unlist_data[7]!="?" && unlist_data[8]!="?" && unlist_data[9]!="?"){ #date_time[i]<-paste(date_val,unlist_data[2]) date_time[i]=weekdays(date_val) Sub_metering_1[i]<-as.double(unlist_data[7]) Sub_metering_2[i]<-as.double(unlist_data[8]) Sub_metering_3[i]<-as.double(unlist_data[9]) i<-i+1 } #break while loop is date > max(date_range) if(date_val > "2007-2-2") break; } plot3_data_frame<-data.frame(date_time, #Global_active_power, #Global_reactive_power, #Voltage, #Global_intensity, Sub_metering_1, Sub_metering_2, Sub_metering_3 ) #png device for saving file png(filename = "figure/plot3.png", width = 480, height = 480,units = "px") par(mar=c(6,4,2,1)) #Chart and custom setting plot(plot3_data_frame$Sub_metering_1,type="n",axes=FALSE,ann=FALSE) lines(plot3_data_frame$Sub_metering_1,type="l") lines(plot3_data_frame$Sub_metering_2,type="l",col="Red") lines(plot3_data_frame$Sub_metering_3,type="l",col="Blue") box( col = 'black') axis(1,at=c(1,2880/2,2880),lab=c("Thu","Fri","Sat")) axis(2,at=c(0,10,20,30),lab=c("0","10","20","30")) legend("topright",col=c("Black","Red","Blue"),lty=c(1,1,1),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3")) title("", ylab="Energy sub metering") dev.off() print("plot3.png saved in figure sub directory") }<file_sep>plot2<-function(dat_file){ if(!file.exists(dat_file)) stop("Input file not found ..please check file path") #vectors for function use date_time<-double() Global_active_power<-double() Global_reactive_power<-double() Voltage<-double() Global_intensity<-double() Sub_metering_1<-double() Sub_metering_2<-double() Sub_metering_3<-double() #open file for reading ...close on.exit content <- file(dat_file, open = "r") on.exit(close(content)) line <- readLines(content, n = 1) unlist_data <- unlist((strsplit(line, ";"))) i<-1 print("loadig data.....this can take a few minutes") #read one line at a time if the date range is good store in vector while (length(line <- readLines(content, n = 1)) > 0) { unlist_data <- unlist((strsplit(line, ";"))) date_val<-as.Date(unlist_data[1],"%d/%m/%Y") if(date_val >= "2007-2-1" && date_val < "2007-2-3" && unlist_data[2]!="?"){ #date_time[i]<-paste(weekdays(date_val),unlist_data[2]) date_time[i]=weekdays(date_val) Global_active_power[i]<-as.numeric(unlist_data[3]) i<-i+1 } #Exit if the date > max date of interest if(date_val > "2007-2-2") break; } plot2_data_frame<-data.frame(date_time, Global_active_power ) #Png device png(filename = "figure/plot2.png", width = 480, height = 480,units = "px") #plot(plot2_data_frame$Global_active_power,plot2_data_frame$date_time,type="n",axes=FALSE,ann=FALSE) #margin setup par(mar=c(4,4,2,1)) plot(plot2_data_frame$Global_active_power,type="n",axes=FALSE,ann=FALSE) #m<-barplot(plot2_data_frame$Global_active_power) lines(plot2_data_frame$Global_active_power) box() axis(1,at=c(1,2880/2,2880),lab=c("Thu","Fri","Sat")) axis(2,at=c(0,2,4,6),lab=c("0","2","4","6")) title(ylab="Global Active Power (kilowatts)") #save png and close dvice dev.off() print("plot2.png saved in figure sub directory") }<file_sep>plot1<-function(dat_file){ if(!file.exists(dat_file)) stop("Input file not found ..please check file path") # vectors for storing data date_time<-double() Global_active_power<-double() Global_reactive_power<-double() Voltage<-double() Global_intensity<-double() Sub_metering_1<-double() Sub_metering_2<-double() Sub_metering_3<-double() #open the file for reading content <- file(dat_file, open = "r") #close resource on.exit(close(content)) line <- readLines(content, n = 1) #Skip the header unlist_data <- unlist((strsplit(line, ";"))) i<-1 print("loadig data.....this can take a few minutes") while (length(line <- readLines(content, n = 1)) > 0) { unlist_data <- unlist((strsplit(line, ";"))) date_val<-as.Date(unlist_data[1],"%d/%m/%Y") #check if date range is within our workset if(date_val >= "2007-2-1" && date_val < "2007-2-3"){ date_time[i]<-paste(date_val,unlist_data[2]) Global_active_power[i]<-as.numeric(unlist_data[3]) Global_reactive_power[i]<-unlist_data[4] Voltage[i]<-unlist_data[5] Global_intensity[i]<-unlist_data[6] Sub_metering_1[i]<-unlist_data[7] Sub_metering_2[i]<-unlist_data[8] Sub_metering_3[i]<-unlist_data[9] i<-i+1 } #If the line is beyond our end date break while loop if(date_val > "2007-2-2") break; } #Create a Data frame plot1_data_frame<-data.frame(date_time, Global_active_power, Global_reactive_power, Voltage, Global_intensity, Sub_metering_1, Sub_metering_2, Sub_metering_3 ) #Png device for writing png(filename = "figure/plot1.png", width = 480, height = 480,units = "px") par(mar=c(6,4,2,1)) #graph hist(plot1_data_frame$Global_active_power,col="Red",main="Global Active Power",xlab="Global Active Power (kilowatts)") #close device dev.off() print("plot1.png saved in figure sub directory") }
0fcc4155ec94622f1c7a0081d30210a26c0be115
[ "R" ]
4
R
munkhan/ExData_Plotting1
3a9f1f2bb22688d21f20e7ccbceaeb70ab2d68e9
c789c5a87db8628d280330279125ec2a98349a47
refs/heads/main
<repo_name>pratik181298/Religionapp<file_sep>/app/src/main/java/com/example/myapplication/fragment/Occasion.java package com.example.myapplication.fragment; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ListView; import com.ethanhua.skeleton.Skeleton; import com.ethanhua.skeleton.SkeletonScreen; import com.example.myapplication.Api.GetData; import com.example.myapplication.Festival_item; import com.example.myapplication.R; import java.util.ArrayList; import java.util.List; import java.util.Set; public class Occasion extends Fragment implements AdapterView.OnItemClickListener { String rname; SharedPreferences pref2,occasions; String occ[]; ListView listView; SkeletonScreen skeletonScreen; FrameLayout frameLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_occasion, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // String[] city={"MahaShivratri","RakshaBandhan"}; frameLayout=view.findViewById(R.id.occasionframelayout); skeletonScreen = Skeleton.bind(frameLayout) .load(R.layout.layout_placeholder) .show(); listView=view.findViewById(R.id.lv2); pref2 = getContext().getSharedPreferences("name", 0); new Handler().postDelayed(new Runnable() { @Override public void run() { getoccasions(); callAdapter(); skeletonScreen.hide(); } }, 500 ); listView.setOnItemClickListener(this); } public void callAdapter() { for (int i=0;i<occ.length;i++) { if(occ[i]==null) { occ[i]=""; } } ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,occ); listView.setAdapter(arrayAdapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent =new Intent(getActivity(), Festival_item.class); intent.putExtra("festival",""+listView.getItemAtPosition(position)); SharedPreferences.Editor editor=pref2.edit(); editor.putString("value",listView.getItemAtPosition(position).toString()).commit(); intent.putExtra("festival",""+listView.getItemAtPosition(position)); startActivity(intent); } public void getoccasions() { occasions=getContext().getSharedPreferences("ocaasions",0); Set<String> all=occasions.getStringSet("occasions",null); List<String> list = new ArrayList<String>(all); occ=new String[list.size()]; for(int i=0;i<list.size();i++) { occ[i]=list.get(i); } } }<file_sep>/app/src/main/java/com/example/myapplication/AuthenticationActivities/SignupActivity.java package com.example.myapplication.AuthenticationActivities; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.myapplication.Models.UserModel; import com.example.myapplication.R; public class SignupActivity extends AppCompatActivity implements View.OnClickListener { EditText firstname, lastname, email, phonenumber, password; Button registerbutton, alreadyuser; CheckBox termcondition; SharedPreferences pref; ProgressDialog progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); getSupportActionBar().setTitle("Registration"); pref = getApplicationContext().getSharedPreferences("credentials", 0); // firstname = findViewById(R.id.userFirstname); lastname = findViewById(R.id.userlastName); email = findViewById(R.id.userEmail); phonenumber = findViewById(R.id.userNumber); password = findViewById(R.id.userPassword); registerbutton = findViewById(R.id.registerbutton); termcondition = findViewById(R.id.termcondition); alreadyuser = findViewById(R.id.alreadyuserbutton); alreadyuser.setOnClickListener(this); registerbutton.setOnClickListener(this); } private Boolean validatePhoneNo() { String val = phonenumber.getText().toString(); if (val.isEmpty()) { phonenumber.setError("Field cannot be empty"); return false; } else { phonenumber.setError(null); return true; } } private Boolean validatepassword() { String val = password.getText().toString(); String passwordVal = "^" + //"(?=.*[0-9])" + //at least 1 digit //"(?=.*[a-z])" + //at least 1 lower case letter //"(?=.*[A-Z])" + //at least 1 upper case letter "(?=.*[a-zA-Z])" + //any letter "(?=.*[@#$%^&+=])" + //at least 1 special character "(?=\\S+$)" + //no white spaces ".{4,}" + //at least 4 characters "$"; if (val.isEmpty()) { password.setError("Field cannot be empty"); return false; } else if (!val.matches(passwordVal)) { password.setError("password is <PASSWORD>"); return false; } else { password.setError(null); return true; } } private Boolean validateName() { String val = firstname.getText().toString(); if (val.isEmpty()) { firstname.setError("Field cannot be empty"); return false; } else { firstname.setError(null); return true; } } private Boolean validateEmail() { String val = email.getText().toString(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; if (val.isEmpty()) { email.setError("Field cannot be empty"); return false; } else if (!val.matches(emailPattern)) { email.setError("Invalid email address"); return false; } else { email.setError(null); return true; } } @Override public void onClick(View v) { if(v.getId()==R.id.loginbutton) { SharedPreferences.Editor editor = pref.edit(); String emailvalue = email.getText().toString(); String passwordvalue = password.getText().toString(); String firstnamevalue = firstname.getText().toString(); String lastnamevalue = lastname.getText().toString(); UserModel user = new UserModel(); if (validateName() | validatepassword() | validatePhoneNo() | validateEmail()) { if (termcondition.isChecked()) { user.register(firstnamevalue, lastnamevalue, emailvalue, passwordvalue, getApplicationContext()); new Handler().postDelayed(new Runnable() { @Override public void run() { if (user.getStatus()) { Intent intent = new Intent(SignupActivity.this, LoginActivity.class); startActivity(intent); Toast.makeText(getApplicationContext(), "" + user.getStatus(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(SignupActivity.this, "User already exists", Toast.LENGTH_LONG).show(); } } }, 2000); } else { Toast.makeText(SignupActivity.this, "accept term and condition", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(SignupActivity.this, "Enter Correctly", Toast.LENGTH_LONG).show(); } } if (v.getId() == R.id.alreadyuserbutton) { Intent intent = new Intent(SignupActivity.this, LoginActivity.class); startActivity(intent); } } // private Boolean validateUsername() { // String val = regUsername.getEditText().getText().toString(); // String noWhiteSpace = "\\A\\w{4,20}\\z"; // // if (val.isEmpty()) { // regUsername.setError("Field cannot be empty"); // return false; // } else if (val.length() >= 15) { // regUsername.setError("Username too long"); // return false; // } else if (!val.matches(noWhiteSpace)) { // regUsername.setError("White Spaces are not allowed"); // return false; // } else { // regUsername.setError(null); // regUsername.setErrorEnabled(false); // return true; // } // } }<file_sep>/app/src/main/java/com/example/myapplication/Api/Config.java package com.example.myapplication.Api; public final class Config { private Config() { } public static final String YOUTUBE_API_KEY = "<KEY>"; } <file_sep>/app/src/main/java/com/example/myapplication/AuthenticationActivities/MobileLoginActivity.java package com.example.myapplication.AuthenticationActivities; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.TelephonyManager; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.myapplication.R; public class MobileLoginActivity extends AppCompatActivity implements View.OnClickListener { String CountryZipCode,CountryID ; Spinner spinner; TextView textView; Button getotp; ArrayAdapter<CharSequence> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mobile_login); getotp=findViewById(R.id.otpbutton); spinner = findViewById(R.id.conunty_spinner); adapter = ArrayAdapter.createFromResource(this, R.array.CountryCodes, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); getotp.setOnClickListener(this); TelephonyManager manager = (TelephonyManager) MobileLoginActivity.this.getSystemService(Context.TELEPHONY_SERVICE); CountryID = manager.getSimCountryIso().toUpperCase(); String[] rl = this.getResources().getStringArray(R.array.CountryCodes); for (int i = 0; i < rl.length; i++) { String[] g = rl[i].split(","); if (g[1].trim().equals(CountryID.trim())) { CountryZipCode = g[0]; break; } } getCountryZipcode(); Toast.makeText(MobileLoginActivity.this, CountryZipCode, Toast.LENGTH_LONG).show(); } public void getCountryZipcode() { int index = 0; String[] rl = this.getResources().getStringArray(R.array.CountryCodes); for (int i = 0; i < rl.length; i++) { String[] g = rl[i].split(","); if (g[0].equals(CountryZipCode)) { index = i; Toast.makeText(MobileLoginActivity.this, "" + spinner.getItemAtPosition(i), Toast.LENGTH_LONG).show(); spinner.setSelection(i); } } } @Override public void onClick(View v) { Intent intent =new Intent(MobileLoginActivity.this,GetOtpActivity.class); startActivity(intent); } } <file_sep>/app/src/main/java/com/example/myapplication/ReligionActivity/HinduActivity.java package com.example.myapplication.ReligionActivity; import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.Priority; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import com.example.myapplication.R; import com.example.myapplication.fragment.Festivalfrag; import com.example.myapplication.fragment.Occasion; import com.google.android.material.button.MaterialButtonToggleGroup; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class HinduActivity extends AppCompatActivity implements View.OnTouchListener { final static float STEP = 200; TextView mytv; float mRatio = 1.0f; int mBaseDist; float mBaseRatio; float fontsize = 13; ImageView imageView; SharedPreferences sharedPreferences,pref1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hindu); imageView=findViewById(R.id.relimg); mytv = (TextView) findViewById(R.id.intro); getSupportActionBar().setTitle(getIntent().getStringExtra("tag")); LoadUi(); // getSupportActionBar().hide(); MaterialButtonToggleGroup materialButtonToggleGroup = findViewById(R.id.HindutoggleGroup); mytv.setMovementMethod(new ScrollingMovementMethod()); mytv.setTextSize(mRatio + 17); if ( materialButtonToggleGroup.getCheckedButtonId()== R.id.Hindubtnfestival) { getSupportFragmentManager().beginTransaction().replace(R.id.Hinduframe,new Festivalfrag()).commit(); } materialButtonToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() { @Override public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) { if (isChecked) { if (checkedId == R.id.Hindubtnfestival) { getSupportFragmentManager().beginTransaction().replace(R.id.Hinduframe,new Festivalfrag()).commit(); } if (checkedId == R.id.HindubtnOccasion) { getSupportFragmentManager().beginTransaction().replace(R.id.Hinduframe,new Occasion()).commit(); } } } }); } public void LoadUi() { pref1 = getApplicationContext().getSharedPreferences("rname", 0); sharedPreferences = getApplicationContext().getSharedPreferences("localpref", 0); String value = sharedPreferences.getString("pref_data", ""); String Religion=pref1.getString("Rname",""); // Toast.makeText(getApplicationContext(),""+Religion,Toast.LENGTH_SHORT).show(); try { JSONObject jsonObject = new JSONObject(value); JSONArray jsonArray = jsonObject.getJSONArray("data"); int n = jsonArray.length(); for(int i=0;i<n;i++) { JSONObject JObject = jsonArray.getJSONObject(i); if(JObject.get("religion_name").toString().equals(Religion)) { Glide.with(getApplicationContext()) .load(JObject.get("imageurl")) .into(imageView); mytv.setText(JObject.get("religion_desc").toString()); } } } catch (JSONException ignored) { // Toast.makeText(context,"hello1"+ignored,Toast.LENGTH_LONG).show(); } } public boolean onTouchEvent(MotionEvent event) { if (event.getPointerCount() == 2) { int action = event.getAction(); int pureaction = action & MotionEvent.ACTION_MASK; if (pureaction == MotionEvent.ACTION_POINTER_DOWN) { mBaseDist = getDistance(event); mBaseRatio = mRatio; } else { float delta = (getDistance(event) - mBaseDist) / STEP; float multi = (float) Math.pow(2, delta); mRatio = Math.min(1024.0f, Math.max(0.1f, mBaseRatio * multi)); mytv.setTextSize(mRatio + 13); } } return true; } int getDistance(MotionEvent event) { int dx = (int) (event.getX(0) - event.getX(1)); int dy = (int) (event.getY(0) - event.getY(1)); return (int) (Math.sqrt(dx * dx + dy * dy)); } public boolean onTouch(View v, MotionEvent event) { return false; } }<file_sep>/app/src/main/java/com/example/myapplication/ReligionActivity/JainActivity.java package com.example.myapplication.ReligionActivity; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.example.myapplication.R; import com.example.myapplication.fragment.Festivalfrag; import com.example.myapplication.fragment.Occasion; import com.google.android.material.button.MaterialButtonToggleGroup; public class JainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jain); getSupportActionBar().setTitle(getIntent().getStringExtra("tag")); // MaterialButtonToggleGroup materialButtonToggleGroup = findViewById(R.id.JaintoggleGroup); // if ( materialButtonToggleGroup.getCheckedButtonId()== R.id.btnfestival) { // // getSupportFragmentManager().beginTransaction().replace(R.id.Jainframe,new Festivalfrag()).commit(); // } // materialButtonToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() { // @Override // public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) { // if (isChecked) { // if (checkedId == R.id.btnfestival) { // Toast.makeText(JainActivity.this,"ok",Toast.LENGTH_LONG).show(); // getSupportFragmentManager().beginTransaction().replace(R.id.Jainframe,new Festivalfrag()).commit(); // } // if (checkedId == R.id.btnOccasion) { // // Toast.makeText(JainActivity.this,"ook",Toast.LENGTH_LONG).show(); // getSupportFragmentManager().beginTransaction().replace(R.id.Jainframe,new Occasion()).commit(); // } // } // } // }); } }<file_sep>/app/src/main/java/com/example/myapplication/DrawerActivities/FavouritesActivity.java package com.example.myapplication.DrawerActivities; import android.animation.ArgbEvaluator; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import com.example.myapplication.Adapters.CardAdapter; import com.example.myapplication.Adapters.FavouritesAdapter; import com.example.myapplication.Models.FavouritesModel; import com.example.myapplication.Models.Modelview; import com.example.myapplication.R; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.ramotion.foldingcell.FoldingCell; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class FavouritesActivity extends AppCompatActivity { ViewPager viewPager; FoldingCell fc; TextView step1,step2,step3,step4; FavouritesAdapter adapter; SharedPreferences sharedPreferences; Integer[] colors = null; ArgbEvaluator argbEvaluator = new ArgbEvaluator(); List<FavouritesModel> models=new ArrayList<>(); String desc,imageurl,steps; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_favourites); getSupportActionBar().setTitle("Favourites"); step1=findViewById(R.id.step1_fav); step2=findViewById(R.id.step2_fav); step3=findViewById(R.id.step3_fav); step4=findViewById(R.id.step4_fav); viewPager = findViewById(R.id.viewPager_fav); sharedPreferences = getApplicationContext().getSharedPreferences("fav", 0); Gson gson = new Gson(); String json = sharedPreferences.getString("models", ""); // Toast.makeText(getApplicationContext(),"Added to favourites"+json,Toast.LENGTH_SHORT).show(); Type type = new TypeToken<List<FavouritesModel>>(){}.getType(); models = gson.fromJson(json, type); // models.add(new FavouritesModel("https://images.ctfassets.net/hrltx12pl8hq/3MbF54EhWUhsXunc5Keueb/60774fbbff86e6bf6776f1e17a8016b4/04-nature_721703848.jpg?fit=fill&w=480&h=270", "Sticker", "Sticker is a type of label: a piece of printed paper, plastic, vinyl, or other material with pressure sensitive adhesive on one side")); // models.add(new FavouritesModel("https://image.shutterstock.com/image-photo/mountains-under-mist-morning-amazing-260nw-1725825019.jpg", "Brochure", "Brochure is an informative paper document (often also used for advertising) that can be folded into a template")); adapter = new FavouritesAdapter(models, getApplicationContext()); viewPager.setAdapter(adapter); steps= models.get(0).getSteps(); String stepss[]=steps.split(";"); step1.setText(stepss[0]); step2.setText(stepss[1]); step3.setText(stepss[2]); step4.setText(stepss[3]); viewPager.setPadding(130, 0, 130, 0); Integer[] colors_temp = { getResources().getColor(R.color.color2), getResources().getColor(R.color.color3), getResources().getColor(R.color.color4) }; colors = colors_temp; viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (position < (adapter.getCount() -1) && position < (colors.length - 1)) { viewPager.setBackgroundColor( (Integer) argbEvaluator.evaluate( positionOffset, colors[position], colors[position + 1] ) ); getSupportActionBar().setBackgroundDrawable(new ColorDrawable( (Integer) argbEvaluator.evaluate( positionOffset, colors[position], colors[position + 1]))); changeStatusBarColor((Integer) argbEvaluator.evaluate( positionOffset, colors[position], colors[position + 1])); } else { viewPager.setBackgroundColor(colors[colors.length - 1]); } } @Override public void onPageSelected(int position) { steps= models.get(position).getSteps(); String stepss[]=steps.split(";"); step1.setText(stepss[0]); step2.setText(stepss[1]); step3.setText(stepss[2]); step4.setText(stepss[3]); } @Override public void onPageScrollStateChanged(int state) { } }); fc = (FoldingCell) findViewById(R.id.folding_cell_fav); fc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fc.toggle(false); } }); } private void changeStatusBarColor(int color){ if (Build.VERSION.SDK_INT >= 21) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(color); } } }<file_sep>/app/src/main/java/com/example/myapplication/MainActivity.java package com.example.myapplication; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridLayout; import android.widget.GridView; import android.widget.Toast; import com.example.myapplication.Adapters.GridAdapter; import com.example.myapplication.Api.GetData; import com.example.myapplication.Navigationdrawer.DrawerActivity; import com.example.myapplication.ReligionActivity.HinduActivity; import com.example.myapplication.ReligionActivity.JainActivity; import com.example.myapplication.ReligionActivity.MuslimActivity; import com.example.myapplication.ReligionActivity.SikhimActivity; import com.example.myapplication.fragment.Festivalfrag; import java.util.ArrayList; import java.util.List; import java.util.Set; public class MainActivity extends DrawerActivity implements View.OnClickListener, AdapterView.OnItemClickListener { SharedPreferences pref1; GridView grid; Button button; GridAdapter obj; String array[]; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater=LayoutInflater.from(this); View v=inflater.inflate(R.layout.activity_main,null,false); drawer.addView(v,0); // setContentView(R.layout.activity_main); getSupportActionBar().setTitle("Home"); grid=(GridView)findViewById(R.id.datagrid); pref1 = getApplicationContext().getSharedPreferences("rname", 0); SharedPreferences pref = getApplicationContext().getSharedPreferences("Religionset", 0); // Set<String> fetch = pref.getStringSet("Religion",null); List<String> list = new ArrayList<String>(fetch); array = new String[list.size()]; for(int j =0;j<list.size();j++){ array[j] = list.get(j); } obj=new GridAdapter(this,array); grid.setAdapter(obj); grid.setOnItemClickListener(this); // for(int i = 0 ; i < list.size() ; i++){ //// Toast.makeText( MainActivity.this,list.get(i),Toast.LENGTH_LONG).show(); // addbutton(list.get(i)); // } // SharedPreferences.Editor editor = pref.edit(); // editor.clear(); // editor.commit(); } private void addbutton(String s) { // GridLayout gridLayout=findViewById(R.id.gl); // button = new Button(this); // button.setText(s); // button.setTag(s); // button.setBackground(this.getResources().getDrawable(R.drawable.roundbutton)); // // gridLayout.addView(button); // button.setOnClickListener(this); } @Override public void onClick(View v) { { // String tag= (String) v.getTag(); // switch(tag) { // case "Hinduism": // Intent intent=new Intent(MainActivity.this, HinduActivity.class); // intent.putExtra("tag",tag); // startActivity(intent); // break; // // case "Muslim": // Intent intent1=new Intent(MainActivity.this, MuslimActivity.class); // intent1.putExtra("tag",tag); // startActivity(intent1); // break; // // case "Sikhim": // Intent intent2=new Intent(MainActivity.this, SikhimActivity.class); // intent2.putExtra("tag",tag); // startActivity(intent2); // break; // // case "Jainism": // Intent intent3=new Intent(MainActivity.this, JainActivity.class); // intent3.putExtra("tag",tag); // startActivity(intent3); // break; // // default: break; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String selectedItem=array[position]; // Toast.makeText(getApplicationContext(),selectedItem,Toast.LENGTH_LONG).show(); // GetData obj=new GetData(getApplicationContext()); // obj.executeApi(selectedItem,getApplicationContext()); GetData getData=new GetData(getApplicationContext()); getData.executeApi(selectedItem,getApplicationContext()); SharedPreferences.Editor editor = pref1.edit(); editor.putString("Rname",selectedItem); editor.commit(); Intent intent=new Intent(MainActivity.this,HinduActivity.class); intent.putExtra("tag",selectedItem); startActivity(intent); } } <file_sep>/app/src/main/java/com/example/myapplication/Splashscreen.java package com.example.myapplication; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import com.example.myapplication.Api.GetData; import com.example.myapplication.AuthenticationActivities.LoginActivity; import com.example.myapplication.AuthenticationActivities.SignupActivity; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Handler; import android.view.View; import android.widget.BaseAdapter; public class Splashscreen extends AppCompatActivity { SharedPreferences pref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splashscreen); pref = getApplicationContext().getSharedPreferences("credentials", 0); Handler handler=new Handler(); GetData getData=new GetData(getApplicationContext()); getData.execute(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(Splashscreen.this, Religionselec.class); startActivity(intent); finish(); // if(pref.contains("email")&&pref.contains("password")) // { // Intent intent=new Intent(Splashscreen.this, LoginActivity.class); // startActivity(intent); // finish(); // } // else { // Intent intent = new Intent(Splashscreen.this, SignupActivity.class); // startActivity(intent); // finish(); // } } },3000); } }<file_sep>/app/src/main/java/com/example/myapplication/DrawerActivities/AddActivity.java package com.example.myapplication.DrawerActivities; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.myapplication.Api.Addarticles; import com.example.myapplication.MainActivity; import com.example.myapplication.R; import com.google.android.material.snackbar.Snackbar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Set; public class AddActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener { Spinner Religionspinner,Typespinner; Button approvebutton; EditText typename,desc,step1,step2,step3,step4,imageurl; SharedPreferences sharedPreferences,pref; RelativeLayout relativeLayout; List<String> selectReligion,selectType; public int userid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); getSupportActionBar().setTitle("Add"); getDataFromPref(); Religionspinner=findViewById(R.id.religionspinner); Typespinner=findViewById(R.id.typespinner); approvebutton=findViewById(R.id.approvebutton); relativeLayout=findViewById(R.id.rladdactivity); typename=findViewById(R.id.typename_add); desc=findViewById(R.id.desc_add); step1=findViewById(R.id.step1_add); step2=findViewById(R.id.step2_add); step3=findViewById(R.id.step3_add); step4=findViewById(R.id.step4_add); imageurl=findViewById(R.id.imgurl_add); Religionspinner.setOnItemSelectedListener(this); Typespinner.setOnItemSelectedListener(this); approvebutton.setOnClickListener(this); selectType = new ArrayList<String>(); selectType.add("Festival"); selectType.add("Occasion"); ArrayAdapter<String> RelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, selectReligion); RelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Religionspinner.setAdapter(RelAdapter); ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, selectType); typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Typespinner.setAdapter(typeAdapter); } public void getDataFromPref() { selectReligion= new ArrayList<String>(); // SharedPreferences sharedPreferences = getSharedPreferences("localpref", MODE_PRIVATE); sharedPreferences = getApplicationContext().getSharedPreferences("localpref", 0); String value = sharedPreferences.getString("pref_data", ""); try { JSONObject jsonObject = new JSONObject(value); JSONArray jsonArray = jsonObject.getJSONArray("data"); int n = jsonArray.length(); for(int i=0;i<n;i++) { JSONObject JObject = jsonArray.getJSONObject(i); selectReligion.add(JObject.get("religion_name").toString()); } } catch (JSONException ignored) { // Toast.makeText(context,"hello1"+ignored,Toast.LENGTH_LONG).show(); } pref=getApplicationContext().getSharedPreferences("credentials", 0); userid=pref.getInt("id",0); } @SuppressLint("NewApi") @Override public void onClick(View v) { int i=1; ProgressDialog diag = new ProgressDialog(this); diag.setIndeterminate(true); diag.setTitle("hello"); diag.setMessage("adding data"); diag.setCancelable(false); //here is the trick: // diag.setIndeterminateDrawable(getResources().getDrawable(R.drawable.animfordialog, null)); diag.show(); String step11= step1.getText().toString()+";"; String step12= step2.getText().toString()+";"; String step13= step3.getText().toString()+";"; String step14 = step4.getText().toString()+";"; // step11.concat(";"); // step12.concat(";"); // step13.concat(";"); // step14.concat(";"); String steps=step11.concat(step12.concat(step13.concat(step14))); Addarticles articles=new Addarticles(getApplicationContext()); articles.addArticle(Religionspinner.getSelectedItem().toString(),userid,Typespinner.getSelectedItem().toString(),typename.getText().toString(),desc.getText().toString(),steps,imageurl.getText().toString()); new Handler().postDelayed(new Runnable() { @Override public void run() { if(articles.getSuccess()!=null) { diag.hide(); Snackbar snackbar = Snackbar .make(relativeLayout, "Data will be Validated Soon", Snackbar.LENGTH_LONG) .setAction("Check Status", new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(AddActivity.this, MycontributionActivity.class); startActivity(intent); } }); snackbar.show(); } } }, 3000 ); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { } @Override public void onNothingSelected(AdapterView<?> parent) { } }<file_sep>/app/src/main/java/com/example/myapplication/utils/UserSteps.java package com.example.myapplication.utils; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; import ernestoyaquello.com.verticalstepperform.Step; public class UserSteps extends Step<String> { private TextView userNameView; public UserSteps(String step1) { super(step1); } @Override protected View createStepContentLayout() { // Here we generate the view that will be used by the library as the content of the step. // In this case we do it programmatically, but we could also do it by inflating an XML layout. userNameView = new TextView(getContext()); userNameView.setSingleLine(true); userNameView.setText("sv<PASSWORD>"); userNameView.setHint("<NAME>"); // userNameView.addTextChangedListener(new TextWatcher() { // // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // // Whenever the user updates the user name text, we update the state of the step. // // The step will be marked as completed only if its data is valid, which will be // // checked automatically by the form with a call to isStepDataValid(). // markAsCompletedOrUncompleted(true); // } // // @Override // public void afterTextChanged(Editable s) { // // } // }); // return userNameView; } @Override public String getStepData() { // We get the step's data from the value that the user has typed in the EditText view. String userName = userNameView.getText().toString(); return userName != null ? userName.toString() : ""; } @Override public String getStepDataAsHumanReadableString() { // Because the step's data is already a human-readable string, we don't need to convert it. // However, we return "(Empty)" if the text is empty to avoid not having any text to display. // This string will be displayed in the subtitle of the step whenever the step gets closed. String userName = getStepData(); return !userName.isEmpty() ? userName : "(Empty)"; } @Override protected void onStepOpened(boolean animated) { // This will be called automatically whenever the step gets opened. } @Override protected void onStepClosed(boolean animated) { // This will be called automatically whenever the step gets closed. } @Override protected void onStepMarkedAsCompleted(boolean animated) { // This will be called automatically whenever the step is marked as completed. } @Override protected void onStepMarkedAsUncompleted(boolean animated) { // This will be called automatically whenever the step is marked as uncompleted. } @Override public void restoreStepData(String stepData) { // To restore the step after a configuration change, we restore the text of its EditText view. userNameView.setText(stepData); } @Override protected IsDataValid isStepDataValid(String stepData) { return null; } }<file_sep>/app/src/main/java/com/example/myapplication/SettingsActivity.java package com.example.myapplication; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.Set; public class SettingsActivity extends AppCompatActivity implements View.OnClickListener { SharedPreferences pref; ListView settinglv; Button settingedit; String[] religion={"ss","c3c"}; ArrayAdapter<String> arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); pref = getApplicationContext().getSharedPreferences("Religionset", 0); settinglv = findViewById(R.id.Settinglistview); settingedit=findViewById(R.id.Settingeditbutton); getSupportActionBar().setTitle("Settings"); Set<String> fetch = pref.getStringSet("Religion",null); List<String> list = new ArrayList<String>(fetch); settingedit.setOnClickListener(this); // arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,list ); settinglv.setAdapter(arrayAdapter); for(int i = 0 ; i < list.size() ; i++){ settinglv.setItemChecked(i,true); } settinglv.setEnabled(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.settingmenu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { //Button b=(Button) findViewById(R.id.edit); Intent intent=new Intent(SettingsActivity.this,Religionselec.class); startActivity(intent); return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { Intent intent=new Intent(SettingsActivity.this,Religionselec.class); startActivity(intent); } }<file_sep>/app/src/main/java/com/example/myapplication/Models/Modelview.java package com.example.myapplication.Models; import android.content.Context; import android.widget.Toast; public class Modelview { private String imageUrl; private String steps; private String desc; public Modelview(String imageUrl, String steps, String desc) { this.imageUrl = imageUrl; // Toast.makeText(context,"shvjds",Toast.LENGTH_SHORT).show(); this.steps = steps; this.desc = desc; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String image) { this.imageUrl = imageUrl; } public String getSteps() { return steps; } public void setSteps(String steps) { this.steps = steps; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } } <file_sep>/app/src/main/java/com/example/myapplication/DrawerActivities/MyContibutionFragment/ApprovedFragment.java package com.example.myapplication.DrawerActivities.MyContibutionFragment; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.myapplication.Api.Addarticles; import com.example.myapplication.R; import java.util.ArrayList; import java.util.List; public class ApprovedFragment extends Fragment implements AdapterView.OnItemClickListener { ListView listView; SharedPreferences pref; TextView t; ProgressBar progressBar; FrameLayout frameLayout; List<String> approve=new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_approved, container, false); } @SuppressLint("NewApi") @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String[] city={"Approved","Approved","Approved","Approved"}; listView=view.findViewById(R.id.lvapprove); frameLayout=view.findViewById(R.id.aprrveframelayout); t=view.findViewById(R.id.fetch); progressBar=view.findViewById(R.id.proressapprove); progressBar.setProgress(2000,true); Addarticles addarticles=new Addarticles(getContext()); pref=getContext().getSharedPreferences("credentials", 0); addarticles.showarticlesbyid(pref.getInt("id",0)); approve= addarticles.getApprove(); final SwipeRefreshLayout pullToRefresh = view.findViewById(R.id.swipe_layout); pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if(approve.isEmpty()) { t.setText("Nothing To show"); t.setVisibility(View.VISIBLE); } ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,approve); listView.setAdapter(arrayAdapter); pullToRefresh.setRefreshing(false); } }); new Handler().postDelayed(new Runnable() { @Override public void run() { setaadapter(); } }, 1000 ); listView.setOnItemClickListener(this); } public void setaadapter() { progressBar.setVisibility(View.INVISIBLE); if(approve.isEmpty()) { t.setText("Nothing To show"); t.setVisibility(View.VISIBLE); } ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,approve); listView.setAdapter(arrayAdapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // LayoutInflater inflater = getLayoutInflater(); // View layouttoast = inflater.inflate(R.layout.row,null); // Toast mytoast = new Toast(getContext()); // mytoast.setView(layouttoast); // mytoast.setDuration(Toast.LENGTH_LONG); // mytoast.show(); Toast.makeText(getActivity(),""+listView.getItemAtPosition(position),Toast.LENGTH_LONG).show(); } }<file_sep>/app/src/main/java/com/example/myapplication/CheckArticlesActivity.java package com.example.myapplication; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.myapplication.Api.ValidateArticles; import com.example.myapplication.AuthenticationActivities.LoginActivity; import com.google.android.material.progressindicator.CircularProgressIndicator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static com.example.myapplication.utils.ProgressBarHandler.show; public class CheckArticlesActivity extends AppCompatActivity implements View.OnClickListener { TextView step1, step2, step3, step4, desc; ImageView imgurl; ProgressBar circularProgressIndicator; String steps, imageurl, descrption; int Articleid = 0; int i = 3000; Boolean status; Button approve, reject; TextView toolbartitle, typename; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_check_articles); step1 = findViewById(R.id.step1); step2 = findViewById(R.id.step2); step3 = findViewById(R.id.step3); step4 = findViewById(R.id.step4); desc = findViewById(R.id.desc); imgurl = findViewById(R.id.imgurl); approve = findViewById(R.id.approve); reject = findViewById(R.id.reject); circularProgressIndicator = findViewById(R.id.progressindicator); toolbartitle = findViewById(R.id.toolbar_title); typename = findViewById(R.id.typename_check); approve.setOnClickListener(this); reject.setOnClickListener(this); Articleid = Integer.parseInt(getIntent().getStringExtra("articleid")); loaddata(Articleid); } public void loaddata(int id) { sharedPreferences = getApplicationContext().getSharedPreferences("allArticles", 0); String value = sharedPreferences.getString("article", ""); try { JSONObject jsonObject = new JSONObject(value); JSONArray jsonArray = jsonObject.getJSONArray("Articles"); int n = jsonArray.length(); for (int i = 0; i < n; i++) { JSONObject JObject = jsonArray.getJSONObject(i); if (JObject.get("article_id").equals(id)) { descrption = JObject.get("desc").toString(); steps = JObject.get("procedure").toString(); imageurl = JObject.get("image_url").toString(); toolbartitle.setText(JObject.get("religion_name").toString()); typename.setText(JObject.get("type_name").toString()); Glide.with(getApplicationContext()) .load(imageurl) .into(imgurl); desc.setText(descrption); String stepss[] = steps.split(";"); step1.setText(stepss[0]); step2.setText(stepss[1]); step3.setText(stepss[2]); step4.setText(stepss[3]); } } } catch (JSONException ignored) { Toast.makeText(getApplicationContext(), "hello1" + ignored, Toast.LENGTH_LONG).show(); } } @Override public void onClick(View v) { // circularProgressIndicator.setProgress(100); if (v.getId() == R.id.approve) { circularProgressIndicator.setVisibility(View.VISIBLE); circularProgressIndicator.setProgress(2000); ValidateArticles validateArticles = new ValidateArticles(getApplicationContext()); validateArticles.checkedarticles(Articleid, "Approved"); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { status = validateArticles.getSuccess(); if (validateArticles.getSuccess()!=null) { circularProgressIndicator.setVisibility(View.INVISIBLE); showdialoag(); } else { i = i + 1000; } } }, i); } else { circularProgressIndicator.setVisibility(View.VISIBLE); circularProgressIndicator.setProgress(2000); ValidateArticles validateArticles = new ValidateArticles(getApplicationContext()); validateArticles.checkedarticles(Articleid, "Rejected"); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { status = validateArticles.getSuccess(); if (validateArticles.getSuccess()) { circularProgressIndicator.setVisibility(View.INVISIBLE); showdialoag(); } else { i = i + 1000; } } }, i); } } @SuppressLint("NewApi") public void showdialoag() { AlertDialog.Builder builder = new AlertDialog.Builder(CheckArticlesActivity.this); if (status) { builder.setTitle("Status Updated"); builder.setMessage("Go to Pending Articles"); builder.setIcon(R.drawable.download); builder.setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(CheckArticlesActivity.this, ValidateArticlesActivity.class); startActivity(intent); } }); AlertDialog dialog = builder.create(); // Display the alert dialog on interface dialog.show(); } else { builder.setTitle("Status Cannot Updated"); builder.setMessage("retry"); builder.setIcon(R.drawable.crosssin); builder.setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(CheckArticlesActivity.this, ValidateArticlesActivity.class); startActivity(intent); } }); AlertDialog dialog = builder.create(); // Display the alert dialog on interface dialog.show(); } // Set a title for alert dialog // Ask the final question } } <file_sep>/app/src/main/java/com/example/myapplication/Api/AllApi.java package com.example.myapplication.Api; public class AllApi { public static final String URl="http://192.168.1.100/"; public static final String HOME=URl+"api"; public static final String LOGIN=HOME+"/login"; public static final String Register=HOME+"/register"; public static final String fetchreligion=HOME+"/fetchreligion"; public static final String Showreligions=HOME+"/show"; public static final String addarticles=HOME+"/storearticles"; public static final String showarticlesbyid=HOME+"/showarticlesbyid"; public static final String showallarticles=HOME+"/showallarticles"; public static final String validatearticles=HOME+"/validatearticles"; }
f51640f13f5e07686d363393118fb016fd525649
[ "Java" ]
16
Java
pratik181298/Religionapp
50cb915fb992310f75ded58a4dadac9f033ed34d
67d365dbad5bdc4170640baa79c4d134da9ba55d
refs/heads/master
<file_sep>package com.qiuyuanbaike.numberfour1703.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.qiuyuanbaike.numberfour1703.R; import com.qiuyuanbaike.numberfour1703.ui.MainActivity; import butterknife.ButterKnife; import butterknife.OnClick; /** * A simple {@link Fragment} subclass. */ public class FragmentOne extends Fragment { public FragmentOne() { // Required empty public constructor } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_fragment_one, container, false); ButterKnife.bind(this,view); return view; } @OnClick(R.id.text_one) public void one(View v){ startActivity(new Intent(getActivity(), MainActivity.class)); getActivity().finish(); } } <file_sep>package com.qiuyuanbaike.numberfour1703.ui; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import com.qiuyuanbaike.numberfour1703.R; import com.qiuyuanbaike.numberfour1703.SPUtil; public class SplashActivity extends AppCompatActivity { SPUtil spUtil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); MyHander(); spUtil=new SPUtil(this); } public void MyHander() { new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent; if (spUtil.isFirst()){ intent=new Intent(SplashActivity.this, GuideActivity.class); spUtil.setFirst(false); }else { intent=new Intent(SplashActivity.this, MainActivity.class); } startActivity(intent); finish(); } }, 2000); } }
c25c92eeaf1325a943846f8d0c99d95a95b0822d
[ "Java" ]
2
Java
qiuyuanbaike/NumberFour1703-02
fcedab2ce7eea39cf0a196cadee171b42e134daf
ebed7271429d3b18c0b31a206ea90ab8eb96bcfe
refs/heads/master
<file_sep>Rails.application.routes.draw do # get 'articles/new' # get 'articles/show' # get 'articles/edit' # get 'articles/_form' # get 'articles/_article' # get 'articles/index' root 'welcome#home' get 'welcome/about' resources :articles # resources :articles # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep>class ArticlesController < ApplicationController before_action :set_article, only: [:edit, :update, :show, :destroy] def index @articles = Article.all end def new @article = Article.new end def edit end def create @article = Article.new(article_params) if @article.save flash[:notice] = "Article was successfully created" redirect_to article_path(@article) else render 'new' end end def update @article = Article.find(params[:id]) if @article.update(article_params) flash[:notice] = "Article was successfully updated" redirect_to article_path(@article) else render 'edit' end end def show end def destroy @article.destroy flash[:notice] = "Article was successfully deleted" redirect_to articles_path end private def set_article @article = Article.find(params[:id]) end def article_params params.require(:article).permit(:title, :description) end end
edeaca35b547b632136b591cc302692f2c18c2ae
[ "Ruby" ]
2
Ruby
patelrahul1996/login_crud-Apps-Ruby-On-Rails
63c62e2693cbc165bac83eab22cb4f5cf33430be
b4c98856f76cf03ffbc45400806bb9798307fd88
refs/heads/master
<file_sep>#ifndef CONSTANTS_H #define CONSTANTS_H #define Aquila_TEST_TXTFILE "D:/Android/aquila/tests/data/test.txt" #define Aquila_TEST_PCMFILE "D:/Android/aquila/tests/data/test_16b.dat" #define Aquila_TEST_WAVEFILE_8B_MONO "D:/Android/aquila/tests/data/8b_mono.wav" #define Aquila_TEST_WAVEFILE_8B_STEREO "D:/Android/aquila/tests/data/8b_stereo.wav" #define Aquila_TEST_WAVEFILE_16B_MONO "D:/Android/aquila/tests/data/16b_mono.wav" #define Aquila_TEST_WAVEFILE_16B_STEREO "D:/Android/aquila/tests/data/16b_stereo.wav" #define Aquila_TEST_TXTFILE_OUTPUT "D:/Android/aquila/Windows/tests/test_output.txt" #define Aquila_TEST_PCMFILE_OUTPUT "D:/Android/aquila/Windows/tests/test_output.dat" #define Aquila_TEST_WAVEFILE_OUTPUT "D:/Android/aquila/Windows/tests/test_output.wav" #endif // CONSTANTS_H <file_sep>This is Newbrick's fork from aquila =================================== Here is the [Oficial repository](https://github.com/zsiciarz/aquila) What is Aquila? =============== Aquila is an open source and cross-platform DSP (Digital Signal Processing) library for C++11. [![Build Status](https://travis-ci.org/zsiciarz/aquila.png?branch=master)](https://travis-ci.org/zsiciarz/aquila) [![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/zsiciarz/aquila?branch=master&svg=true)](https://ci.appveyor.com/project/zsiciarz/aquila) [![Coverage Status](https://coveralls.io/repos/zsiciarz/aquila/badge.png)](https://coveralls.io/r/zsiciarz/aquila) [![Coverity Scan Build Status](https://scan.coverity.com/projects/2786/badge.svg)](https://scan.coverity.com/projects/2786) Example ======= ```cpp #include "aquila/aquila.h" int main() { // input signal parameters const std::size_t SIZE = 64; const Aquila::FrequencyType sampleFreq = 2000, f1 = 125, f2 = 700; Aquila::SineGenerator sine1(sampleFreq); sine1.setAmplitude(32).setFrequency(f1).generate(SIZE); Aquila::SineGenerator sine2(sampleFreq); sine2.setAmplitude(8).setFrequency(f2).setPhase(0.75).generate(SIZE); auto sum = sine1 + sine2; Aquila::TextPlot plot("Input signal"); plot.plot(sum); // calculate the FFT auto fft = Aquila::FftFactory::getFft(SIZE); Aquila::SpectrumType spectrum = fft->fft(sum.toArray()); plot.setTitle("Spectrum"); plot.plotSpectrum(spectrum); return 0; } ``` For more usage examples see the `examples` directory or [browse them online](http://aquila-dsp.org/articles/examples/). Features ======== * various signal sources (generators, text/binary/WAVE files) * signal windowing and filtering * performing operations on a frame-by-frame basis * calculating energy, power, FFT and DCT of a signal * feature extraction, including MFCC and HFCC features, widely used in speech recognition * pattern matching with DTW (dynamic time warping) algorithm Requirements ============ The following dependencies are required to build the library from source. * a modern C++11 compiler * CMake >= 2.8 Contributing ============ See CONTRIBUTING.md for some guidelines how to get involved. License ======= The library is licensed under the MIT (X11) license. A copy of the license is distributed with the library in the LICENSE file. Authors ======= <NAME> (zbigniew at siciarz dot net) This library includes code from Takuya Ooura's mathematical software packages, which are available at http://www.kurims.kyoto-u.ac.jp/~ooura/. <file_sep>#ifndef CONSTANTS_H #define CONSTANTS_H #define Aquila_TEST_TXTFILE "/home/jtentor/GitHub/aquila/tests/data/test.txt" #define Aquila_TEST_PCMFILE "/home/jtentor/GitHub/aquila/tests/data/test_16b.dat" #define Aquila_TEST_WAVEFILE_8B_MONO "/home/jtentor/GitHub/aquila/tests/data/8b_mono.wav" #define Aquila_TEST_WAVEFILE_8B_STEREO "/home/jtentor/GitHub/aquila/tests/data/8b_stereo.wav" #define Aquila_TEST_WAVEFILE_16B_MONO "/home/jtentor/GitHub/aquila/tests/data/16b_mono.wav" #define Aquila_TEST_WAVEFILE_16B_STEREO "/home/jtentor/GitHub/aquila/tests/data/16b_stereo.wav" #define Aquila_TEST_TXTFILE_OUTPUT "/home/jtentor/GitHub/aquila/Ubuntu/tests/test_output.txt" #define Aquila_TEST_PCMFILE_OUTPUT "/home/jtentor/GitHub/aquila/Ubuntu/tests/test_output.dat" #define Aquila_TEST_WAVEFILE_OUTPUT "/home/jtentor/GitHub/aquila/Ubuntu/tests/test_output.wav" #endif // CONSTANTS_H
522d946e7b44d27622853a59c3970d16c14ca4d0
[ "Markdown", "C" ]
3
C
Newbrick/aquila
1d898ec3ef3c12735ca25c93247a8f6f17ea0ed0
9379411a132cc3c0a363d5f61cec8cb69d3451b7
refs/heads/master
<file_sep>var app=app||{}; app.Book=Backbone.Model.extend({ defaults:{ coverImage:'img/placeholder.jpg', title:'No title', author:'Unkonw', releaseDate:'Unkown', keywords:'None' }, parse:function(response){ response.id=response._id; return response; } }); <file_sep>(function($){ $.fn.dragable=function(){ function fixStyle(e){ var originalCoord = {}; originalCoord.left = this.offset().left; originalCoord.top = this.offset().top; this.data('originalCoordX' , this.offset().left); this.data('originalCoordY' , this.offset().top); this.data('mouseToItemCoordX' , e.pageX - this.offset().left); this.data('mouseToItemCoordY' , e.pageY - this.offset().top); this.css({ 'position' : 'fixed', 'z-index' : '999999', 'margin' : '0px', 'left' : originalCoord.left, 'right' : originalCoord.right }) } function updatePosition(e){ console.log(e) this.css({ 'left' : e.pageX - this.data('mouseToItemCoordX'), 'top' : e.pageY - this.data('mouseToItemCoordY') }) } return this.each(function(){ var $this=$(this); $this.bind('mousedown',function(){ if($this.hasClass('dragTrigger')){ $this.removeClass('dragTrigger'); } $this.addClass('dragTrigger'); }) $this.bind('mousemove',function(e){ e.preventDefault(); if(!$this.hasClass('dragTrigger')){ return; } //$this.trigger('beforedrag'); if(!$this.hasClass('dragging')){ console.log('dragstart'); fixStyle.call($this,e); $this.trigger('dragstart'); $this.addClass('dragging'); return; } console.log('dargging'); updatePosition.call($this,e); $this.trigger('dragging'); }) $this.bind('mouseup',function(e){ if($this.hasClass('dragging')){ $this.removeClass('dragging'); console.log('dragend') $this.trigger('dragend'); } $this.removeClass('dragTrigger'); }) }); } })(jQuery)<file_sep>#include <iostream> #include <string> using std::cin; using std::string; int main(){ string s; std::cout << "enter the string:" << std::endl; std::cin >> s; //cout << s; std::cout << s; return 0; }<file_sep>var Workspace=Backbone.Router.extend({ routers:{ '*filter':'setFilter' }, setFilter:function(item){ window.app.Todos.trigger('filter'); } }); app.TodoRouter =new Workspace(); Backbone.history.start(); <file_sep>var app=app||{}; var TodoList=Backbone.Collection.extend({ model:app.Todo, localStorage:new Backbone.LocalStorage('todos-backbone'), getCompleted:function(){ return this.filter(function(todo){ return todo.get('completed'); }) }, getRemaining:function(){ return this.filter(function(todo){ return !(todo.get('completed')); }) }, nextOrder:function(){ if(!this.length){ return 1; } return this.last().get('order')+1; }, comparator:function(todo){ return todo.get('order'); } }); app.Todos=new TodoList(); <file_sep>#include <iostream> int main(){ //int sum=0; //for(int val=50;val<=100;val++){ // sum+=val; //} int sum=0,val=50; while(val<=100){ sum+=val; val++; } std::cout << "the sum of 50 to 100 is " << sum << std::endl; return 0; }<file_sep>$(function(){ //$('#item1').dragable().bind('dragstart',function(){ // console.log('dragstart') //}); $('#item1').dragable() })<file_sep>var _root=__dirname, express=require('express'), path=require('path'), mongoose=require('mongoose'), port=8888; console.log(_root) var app=express(); app.configure(function(){ app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(_root,'public'))); app.use(express.errorHandler({ dumpExceptions:true, showStack:true })) }); app.get('/fashionWeekList',function(req,res){ function getRandomString(len) { len = len || 32; var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = $chars.length; var pwd = ''; for (var i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } var charNum,imgNum,i=0,listNm=100,descString='',resJson={},listArray=[]; for(;i<listNm;i++){ imgNum=Math.floor(Math.random()*21); //charCode=Math.floor(Math.random()*26)+65; //descString=String.fromCharCode(charCode); descString=getRandomString(Math.floor(Math.random()*200)); listArray.push({ index:i, img:imgNum, description:descString }); } resJson.num=listArray.length; resJson.list=listArray; res.json(resJson); res.end(); }) app.listen(port,function(){ console.log('Express server listening on port %d in %s mode',port,app.settings.env) }); <file_sep>var _root=__dirname, express=require('express'), path=require('path'), mongoose=require('mongoose'), port=8888; console.log(_root) var app=express(); app.configure(function(){ app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(_root,'public'))); app.use(express.errorHandler({ dumpExceptions:true, showStack:true })) }); app.listen(port,function(){ console.log('Express server listening on port %d in %s mode',port,app.settings.env) }); <file_sep>#include <iostream> int main(){ std::cout << "enter two numbers:" << std::endl; int v1,v2; std::cin >> v1 >> v2; int lower,upper; if(v1 <= v2){ lower = v1; upper = v2; }else{ lower = v2; upper = v1; } int sum=0; for(int val=lower;val<=upper;val++){ sum+=val; } std::cout << "sum of " << lower << " to " << upper << " is " << sum << std::endl; return 0; }<file_sep>var mongo=require('mongodb'); var host='127.0.0.1'; var port = mongo.Connection.DEFAULT_PORT; console.log('the port is : ' + port); var db=new mongo.Db('nodejs-introduction',new mongo.Server(host,port,{})); db.open(function(error){ console.log('we are connented@! '+ host + ':' + port); db.collection('user',function(error,collection){ console.log('we have the collection!'); collection.insert({ id:'1', name:'<NAME>', twitter:'ollieparsley', email:'<EMAIL>' },function(){ console.log('successfully inserted ollieparsley') }); collection.insert({ id:'2', name:'<NAME>', twitter:'joeblogs', email:'<EMAIL>' },function(){ console.log('successfully inserted joeblogs') }); }) }) <file_sep>var app=app||{}; $(function(){ var books=[ { title:'book 1 title', author:'book 1 author', releaseDate:'book 1 releaseDate', keywords:'book 1 keywords' }, { title:'book 2 title', author:'book 2 author', releaseDate:'book 2 releaseDate', keywords:'book 2 keywords' }, { title:'book 3 title', author:'book 3 author', releaseDate:'book 3 releaseDate', keywords:'book 3 keywords' }, { title:'book 4 title', author:'book 4 author', releaseDate:'book 4 releaseDate', keywords:'book 4 keywords' } ]; window.myApp=new app.LibraryView(books) }) <file_sep>var _root=__dirname, express=require('express'), path=require('path'), //mongoose=require('mongoose'), port=8888; var app=express(); app.configure(function(){ app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(_root,'public'))); app.use(express.errorHandler({ dumpExceptions:true, showStack:true })) }); //connect to the database //mongoose.connect('mongodb://localhost/library_database'); //var Keywords=new mongoose.Schema({ // keyword:String //}); // //var Book=new mongoose.Schema({ // title:String, // author:String, // releaseDate:Date, // keywords:[Keywords] //}); //var BookModel=mongoose.model('Book',Book) app.get('/api',function(req,res){ res.send('Lib test') }) app.get('/api/books',function(req,res){ console.log('ttttttttt') return BookModel.find(function(error,books){ if(!error){ return res.send(books); }else{ res.send(error); return console.log(error); } }) }) app.post('/api/books',function(req,res){ var book=new BookModel({ title:req.body.title, author:req.body.author, releaseDate:req.body.releaseDate, //keywords:req.body.keywords }); book.save(function(error){ if(!error){ return console.log('A new book is created!!'); }else{ return console.log(error) } }); return res.send(book); }) app.get('/api/books/:id',function(req,res){ return BookModel.findById(req.params.id,function(error,book){ if(!error){ return res.send(book); }else{ return console.log(error) } }) }) app.put('/api/books/:id',function(req,res){ console.log('Updating book '+req.body.title); return BookModel.findById(req.params.id,function(error,book){ book.title=req.body.title; book.author=req.body.author; book.releaseDate=req.body.releaseDate; //book.keywords=req.body.keywords; return book.save(function(error){ if(!error){ console.log('Update book successly!!'); }else{ console.log(error) } return res.send(book) }) }) }) app.delete('/api/books/:id',function(req,res){ return BookModel.findById(req.params.id,function(error,book){ return book.remove(function(error){ if(!error){ return res.send('delete success!!'); }else { console.log(error); return res.send('delete failed!!') } }) }) }) app.listen(port,function(){ console.log('Express server listening on port %d in %s mode',port,app.settings.env) }); <file_sep>var TodoRouter=Backbone.Router.extend({ routes:{ 'about':'showAbout', 'search/:query':'searchTodos', 'search/:query/p:page':'searchTodos' }, showAbout:function(){ console.log('show about Page!'); }, searchTodos:function(query,page){ var pageNum=page||1; console.log('Page number : '+pageNum +'of the results for todos containing the word: '+ query); } }) var todoRouter=new TodoRouter(); Backbone.history.start(); <file_sep>var mongo=require('mongodb'); var host='127.0.0.1'; var port = mongo.Connection.DEFAULT_PORT; console.log('the port is : ' + port) function getUser(id,callback){ var db=new mongo.Db('nodejs-introduction',new mongo.Server(host,port,{})); db.open(function(error){ console.log('we are connented@! '+ host + ':' + port); db.collection('user',function(error,collection){ console.log('we have the collection!'); collection.find({'id':id},function(error,cursor){ cursor.toArray(function(error,users){ if(users.length==0){ callback(false); }else{ callback(users[0]); console.log('Found a user ',users[0]) } }) }) }) }) }; getUser('1',function(user){ if(!user){ console.log('No user found with id 1') }else{ console.log('We had user:'+user) } }) getUser('2',function(user){ if(!user){ console.log('No user found with id 2') }else{ console.log('We had user:'+user) } }) getUser('3',function(user){ if(!user){ console.log('No user found with id 3') }else{ console.log('We had user:'+user) } }) <file_sep>var myModule=require('./my_module.js'); console.log('hello ',myModule.hello()); console.log('local: ',myModule.localVar); console.log('hello again:',myModule.helloWorld()) console.log('my number: '+myModule.increment(10)) <file_sep>(function($){ var defaultOptions={ scrollbar:'.CSScrollbar', scrollHandler:'.CSScrollHandle', autoScroll:false, minScrollbarLength:null, wheelSpeed:10 } $.fn.CSScrollbar = function(settings,options){ //options: update ,destroy console.log('init'); return this.each(function(){ var settings = $.extend(true,{},defaultOptions,settings),$this = $(this); var container = $this , content = container.children(); if(content.length !== 1){ console.log('content must be wrapped in only one html ele!'); return true; } console.log('settings',settings) var scrollbar = $(settings.scrollbar) , scrollHandler = $(settings.scrollHandler),$document = $(document); var containerheight = container.height(),contentHeight = content.height(), scrollbarHeight =scrollbar.height(),scrollHandlerHeight = scrollHandler.height(); console.log(scrollbar) var prevScrollHandlerPageY,prevScrollHandlerTop,currentScrollHandlerPageY,currentScrollHandlertop; var prevPageY,currentPageY; //var CSContaner bindMouseScrollHandler(); function bindMouseScrollHandler(){ console.log('bindMouseScrollHandler'); scrollHandler.bind('mousedown',function(e){ if(scrollHandler.hasClass('dragTrigger')){ scrollHandler.removeClass('dragTrigger'); } scrollHandler.addClass('dragTrigger'); //currentPageY = e.pageY; e.stopPropagation(); e.preventDefault(); }) //scrollHandler.bind('mousemove',function(e){ $document.bind('mousemove',function(e){ e.stopPropagation(); e.preventDefault(); if(!scrollHandler.hasClass('dragTrigger')){ return; } if(!scrollHandler.hasClass('dragging')){ console.log('dragstart'); scrollHandler.trigger('dragstart'); scrollHandler.addClass('dragging'); return; } console.log('dargging'); updateScrollHandlerTop(e); scrollHandler.trigger('dragging'); }) scrollHandler.bind('mouseup',function(e){ e.stopPropagation(); e.preventDefault(); if(scrollHandler.hasClass('dragging')){ scrollHandler.removeClass('dragging'); console.log('dragend') scrollHandler.trigger('dragend'); } scrollHandler.removeClass('dragTrigger'); }) $(document).bind('mouseup',function(){ if(scrollHandler.hasClass('dragging')){ scrollHandler.removeClass('dragging'); console.log('dragend') scrollHandler.trigger('dragend'); scrollHandler.removeClass('dragTrigger'); } }) } function updateContentScrollTop(e){ } function updateScrollHandlerTop(e){ if(!prevPageY){ prevPageY = e.pageY; return; } currentPageY = e.pageY; var distanceY = currentPageY - prevPageY , top = parseInt(scrollHandler.css('top')); console.log(top,distanceY,scrollbarHeight,scrollHandlerHeight) if(top + distanceY < 0){ return; } if(top + distanceY >= scrollbarHeight - scrollHandlerHeight){ return; } console.log(11) scrollHandler.css({ //top: '+=' + (currentPageY - prevPageY) top: '+=' + (currentPageY - prevPageY) }); prevPageY = currentPageY; } }) } })(jQuery)<file_sep>#include <iostream> int main(){ std::cout << "enter two numbers :" << std::endl; int v1,v2; std::cin >> v1 >> v2 ; int lower,upper; if(v1 <= v2){ lower = v1; upper = v2; }else{ lower = v2; upper = v1; } int sum = 0,val = lower; for(;val <= upper;val++){ sum += val; std::cout << val; if((val - lower +1) % 10 == 0){ std::cout << std::endl; }else{ std::cout << " "; } } std::cout <<std::endl << "sum of " << lower << " to " << upper << " is " << sum << std::endl; return 0; }<file_sep>#include <iostream> #include "Sales_item.h" int main(){ //Sales_item book; //std::cout << "enter:" << std::endl; //std::cin >> book; //std::cout << book <<std::endl; Sales_item item1,item2; std::cout << "enter two items:" << std::endl; std::cin >> item1 >> item2; std::cout << item1 + item2 << std::endl; return 0; }<file_sep>#include <iostream> int main(){ int sum,val; std::cout << "enter numbers:" << std::endl; while(std::cin >> val){ sum += val; } std::cout << "sum is " << sum << std::endl; return 0; }<file_sep>var localVar='local',number; function hello(){ return 'world'; } function helloWorld(){ return hello() + 'again'; } function myPrivateFunction(number){ return number +1 ; } function increment(number){ return myPrivateFunction(number); } module.exports.hello=hello; module.exports.helloWorld=helloWorld; module.exports.increment=increment; <file_sep>#include <iostream> int main(){ std::cout << "enter two number :" << std::endl; int v1,v2,max; std::cin >> v1 >> v2; if(v1 >= v2){ max = v1; }else{ max = v2; } std::cout << "the max number of " << v1 << " and " << v2 << " is " << max << std::endl; return 0; }<file_sep>var app=app||{}; app.BookView=Backbone.View.extend({ model:app.Book, tagName:'div', className:'bookContainer', template:_.template($('#bookTemplate').html()), events:{ 'click .delete':'deleteBook' }, render:function(){ var bookData=this.model.toJSON(); this.$el.html(this.template(bookData)); return this; }, initialize:function(){ }, deleteBook:function(e){ //console.log(e); //console.log(this) this.model.destroy(); this.stopListening(); this.remove(); } }) //var testView=new app.BookView({ // model:new app.Book({ // title:'test title' // }), // testV:'test' //}) <file_sep>$(function(){ var prevCoord={},currentCoord={}; $(document).bind('mousemove',function(e){ // console.log(e) var speed={}; currentCoord.x=e.pageX; currentCoord.y=e.pageY; currentCoord.time=(new Date()).getTime(); if(('x' in prevCoord)&&('y' in prevCoord)&&('time' in prevCoord)){ speed.x = (currentCoord.x - prevCoord.x) / (currentCoord.time - prevCoord.time) * 1000; speed.y = (currentCoord.y - prevCoord.y) / (currentCoord.time - prevCoord.time) * 1000; } console.log(speed); //$('body').append('<span>x:' + speed.x + ',y:' + speed.y + '</span><br>'); //$('body').html('x:' + speed.x + ',y:' + speed.y); prevCoord.x = currentCoord.x; prevCoord.y = currentCoord.y; prevCoord.time = currentCoord.time; }) $(document).bind('touchmove',function(e){ console.log('touchmove') var originalEvent = e.originalEvent; if(originalEvent.touches.length != 1) return; //console.log(e) var speed = {}; currentCoord.x = originalEvent.touches[0].pageX ; currentCoord.y = originalEvent.touches[0].pageX ; currentCoord.time = (new Date()).getTime(); if(('x' in prevCoord)&&('y' in prevCoord)&&('time' in prevCoord)){ speed.x = (currentCoord.x - prevCoord.x) / (currentCoord.time - prevCoord.time) * 1000; speed.y = (currentCoord.y - prevCoord.y) / (currentCoord.time - prevCoord.time) * 1000; } //console.log(speed); //$('body').append('<span>x:' + speed.x + ',y:' + speed.y + '</span><br>'); //$('body').html('x:' + speed.x + ',y:' + speed.y); prevCoord.x = currentCoord.x; prevCoord.y = currentCoord.y; prevCoord.time = currentCoord.time; }) $(document).bind('touchend',function(e){ console.log('touchend') var originalEvent = e.originalEvent; if(originalEvent.touches.length != 1) return; console.log(e) var speed = {}; currentCoord.x = originalEvent.touches[0].pageX ; currentCoord.y = originalEvent.touches[0].pageX ; currentCoord.time = (new Date()).getTime(); if(('x' in prevCoord)&&('y' in prevCoord)&&('time' in prevCoord)){ speed.x = (currentCoord.x - prevCoord.x) / (currentCoord.time - prevCoord.time) * 1000; speed.y = (currentCoord.y - prevCoord.y) / (currentCoord.time - prevCoord.time) * 1000; } //console.log(speed); //$('body').append('<span>x:' + speed.x + ',y:' + speed.y + '</span><br>'); $('body').html('x:' + speed.x + ',y:' + speed.y); prevCoord.x = currentCoord.x; prevCoord.y = currentCoord.y; prevCoord.time = currentCoord.time; }) })<file_sep>$(document).ready(function () { //load flash //$("#imgshow").scrollable({circular:true}).autoscroll({ autoplay: true,interval: 5000 }).navigator({navi:'#scro_nav'}); $("#imgshow").scrollable({circular: true, prev: "#imgshow_l", next: "#imgshow_r"}).autoscroll({autoplay: true, interval: 5000}).navigator({navi: "#scro_nav"}); $("#scro_2").autoFade({nav: '#scro_nav2', interval: 10000}); $("#sub1_l li").bind("mouseover", {list: "#sub1_l li", target: "#sub1_r li"}, ashowb); function ashowb(event) { if (!$(this).hasClass('active')) { var n = $(this).index(); $(event.data.target).hide(); $(event.data.target).eq(n).fadeIn(); $(event.data.list).removeClass("active"); $(this).addClass("active"); } return false; } //新品入库 $("#c4_sub").tabs("div.c4_l_c", {event: 'mouseover'}); //热评单品 $(".tabs_t").tabs(".tabs_b>ul", { event: 'mouseover', current: 'hover' }); $('.c1_l_2_c dl:first').addClass('first'); $('.c2_c li:first').addClass('first'); $('.c2_c li:last').addClass('last'); $('.c8_c_item:first').addClass('first'); $('.tabs_b li:last').addClass('last'); $(".search .main_input").bind({ blur: function () { if ($(this).val() == "") $(this).val("请输入产品名称、品牌或关键字"); $("#se_brand").hide(); }, focus: function () { if ($(this).val() == "请输入产品名称、品牌或关键字") $(this).val(""); $("#se_brand").show(); } }) $(".c_search .main_input").bind({ blur: function () { if ($(this).val() == "") $(this).val("请输入拼音、拼音缩写、中文、英文等可以快速匹配"); $("#se_brand").hide(); }, focus: function () { if ($(this).val() == "请输入拼音、拼音缩写、中文、英文等可以快速匹配") $(this).val(""); $("#se_brand").show(); } }) //navSlider /*function navSlider(){ var $nav = $('#c4_sub'), $cur = $('#c4_sub li.cur a'), $navLine = $('.tab_arrow'), $anchor = $('a',$nav.children()), curPosL = $cur.position().left, curW = $cur.outerWidth(true), curIdx = $('li.cur',$nav).index(); $navLine.css({'width':curW,'left':curPosL}); $anchor.not('li.last a',$nav).each(function(index){ var posL = $(this).position().left, w = $(this).outerWidth(true); $(this).mouseenter(function(){ $navLine.animate({'width':w,'left':posL},250); $(this).parent().addClass('cur').siblings().removeClass('cur'); }); }); $nav.mouseleave(function(){ $navLine.animate({'width':curW,'left':curPosL},250); $anchor.parent(':eq('+curIdx+')').addClass('cur').siblings().removeClass('cur'); }); }; navSlider();*/ //totop $("#totop").click(function () { $('html,body').animate({ scrollTop: 0 }, 100); }) function scroll() { var top = $(window).scrollTop(); if (top > 400) { $("#totop").fadeIn(); } else { $("#totop").fadeOut(); } } var t = null; $(window).scroll(function () { t && clearTimeout(t); t = setTimeout(scroll, 500); }); // 20130926 YuanYanjun // var $vernier=$('.c4_l_t .tab_arrow').eq(0); $('#c4_sub').tabs('.c4_l_con .c4_l_c',{ event:'mouseover' }) $('#c4_sub li').bind('mouseover',function(){ var $that=$(this); $vernier.animate({ 'right':(4-$that.index())*80 },{ 'easing':'swing' }) }) $("#scro_3").autoFade({nav: '#scro_nav3', interval: 5000}); $("#scroller_1_inner").scrollable({circular: true, prev: "#scroller_1_prevBtn", next: "#scroller_1_nextBtn"}).autoscroll({autoplay: true, interval: 5000}); //20130927 //$("#scroll_wraper_1").scrollable({ vertical: true, mousewheel: true,circular: false,prev:'#scroll_btn_prev',next:'#scroll_btn_next'}); //20130927 <NAME> $('#CSContainer').CSScrollbar({ scrollbar : '#CSScrollbar', scrollHandler : '#CSScrollbar .#CSScrollHandle' }) })<file_sep>var app=app||{}; app.LibraryView=Backbone.View.extend({ el:'#books', initialize:function(initializeBooks){ ///this.collection=new app.Library(initializeBooks); this.collection=new app.Library(); this.collection.fetch({reset:true}); this.render(); this.listenTo(this.collection,'add',this.renderBook); this.listenTo(this.collection,'reset',this.render); }, events:{ 'click #add':'addBook' }, render:function(){ this.collection.each(function(book){ this.renderBook(book) },this) }, renderBook:function(book){ var bookView=new app.BookView({ model:book }); this.$el.append(bookView.render().$el); }, addBook:function(e){ e.preventDefault(); console.log('add book button is clicked!!'); var formData={}; $('#addBook div').children('input').each(function(index,el){ var $this=$(el); if($this.val()!=''){ formData[$this.attr('id')]=$this.val(); }; }); //this.collection.add(new app.Book(formData)); this.collection.create(formData); //console.log(this.collection) } }) <file_sep>var https = require('https'); var options={ host:'stream.twitter.com', path:'/1/statuses/filter.json?track=bieber', method:'GET', headers:{ 'Authorization':'Basic '+ new Buffer('IntroToNode:introduction').toString('base64') } }; var request=https.request(options,function(response){ var body=''; response.on('data',function(chunk){ //body+=chunk.toString(); var tweet=JSON.parse(chunk); console.log('tweet '+tweet.text); } response.on('end',function(){ console.log('Disconnected') }) })
bcd92c2d909af5df0f446d23475cfb28e18c0806
[ "JavaScript", "C++" ]
27
JavaScript
joker-2013/learn
b395839cd2c6662b3b4defd235c02af654aebfa0
feb79023f7e1a5b761adbf3518bed601c3fd1aa6
refs/heads/master
<file_sep>#include <iostream> #include <utility> #include <unordered_set> #include <algorithm> #include <string> using namespace std; unordered_set<string> triplete; unordered_set<string>::iterator it; int main() { int n,v[50],i,st,dr; cin>>n; for(i=0;i<n;i++) cin>>v[i]; sort(v,v+n); for(i=0;i<=n-3;i++){ st=i+1; dr=n-1; while(st<dr){ if(v[i]+v[st]+v[dr]==0){ string pereche=to_string(v[i])+" "+to_string(v[st])+" "+to_string(v[dr]); if(triplete.find(pereche)==triplete.end()){ triplete.insert(pereche); cout<<pereche; } st++;dr--; } else if(v[i]+v[st]+v[dr]<0)st++; else dr--; } } return 0; }<file_sep>#include <iostream> #include <string> #include <vector> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <cstring> using namespace std; ifstream f("date.in"); //preinitializare class ingredient; class pizza; class pret { virtual float suma(int man, int distanta) = 0; }; class ingredient { string nume; int cantitate; float pret; public: ingredient() {} ingredient(string N, int C, float P) { nume.clear(); nume.swap(N); cantitate = C; pret = P; } void initializare(string N, int C, float P) { nume.clear(); nume.swap(N); cantitate = C; pret = P; } ~ingredient() { //cout << "destructed"; } string& getNume() { return nume; } int getCantitate() { return cantitate; } float getPret() { return pret; } }; class pizza :public pret { vector<ingredient> ingrediente; ingredient XX; string nume, N; int nr_ing, i, C; float P; float PRET=0; public: float suma(int man, int distanta) override { if(distanta/10>=1) return ((man+PRET)*((distanta/10)*5)/100)+man+PRET; else return man + PRET; } string& getNume() { return nume; } float getPRET() { return PRET; } friend istream &operator>>(istream &input, pizza &Piz) { input >> Piz.nume; cout << Piz.nume; input >> Piz.nr_ing; int C; Piz.PRET = 0; for (Piz.i = 1; Piz.i <= Piz.nr_ing; Piz.i++) { input >> Piz.N >> C >> Piz.P; if (C < 0)throw 7; Piz.ingrediente.resize(Piz.i); Piz.XX.initializare(Piz.N, C, Piz.P); Piz.ingrediente.push_back(Piz.XX); Piz.PRET += C * Piz.P; } return input; } }; template <class T> class Meniu { vector <T> X;//veg vector <T> XX;//n float moneyX=0,moneyXX=0; int k=0,nX=0,nXX=0,i,dist; public: Meniu(int nr) { cout << nr; //X=(pizza*)malloc(nr * sizeof(pizza)); } void add1(T Class) { //X[k] = Class; XX.push_back(Class); ++nXX; } void add2(T Class) { X.push_back(Class); ++nX; } void start() { int cant; string text,close("close"); char tip; //int dist; while (close.compare(text)) { cout << "\nPizza:"; cin >> text; if (close.compare(text) == 0)break; cout << "\nTip:"; cin >> tip; cout << "\nCantitate:"; cin >> cant; cout << "\nDistanta:"; cin >> dist; if (tip == 'n') { for (i = 0; i < nXX; i++) //cout << (XX.at(i)).getNume()<<'\n'; if (XX.at(i).getNume().compare(text)==0)break; moneyXX += cant * XX.at(i).suma(10, dist); } else { for (i = 0; i < nX; i++) if (X.at(i).getNume().compare(text) == 0)break; moneyX += cant * X.at(i).suma(10, dist); } } cout << "Profit pizza normala:" << moneyXX<<'\n'; cout << "Profit pizza vegetariana:" << moneyX << '\n'; } ~Meniu() { } }; class veg : public pizza { }; int main() { try { //Meniu<pizza> X; //vector <pizza> pza; pizza pza; veg ve; int numar_pizza,i; char c; f >> numar_pizza; Meniu <pizza> men(numar_pizza); for (i = 1; i <= numar_pizza; i++) { f >> c; if(c=='n'){ f >> pza; men.add1(pza); } else { f >> pza; men.add2(pza); } } men.start(); } catch (string *e) { cout << "somn..."; } while(1){} }<file_sep>#include <iostream> #include <fstream> #include <list> #include <utility> #include <queue> #include <vector> #include <stdio.h> using namespace std; class graf { private: list<pair<int, int> > L; list<int> A[50]; int muchii, noduri; int a[50][50], m[50][50]; public: graf(); ~graf(); friend istream &operator>>(istream &input, graf &G) { int x, y, i; input >> G.noduri >> G.muchii; for (i = 1; i <= G.muchii; i++) { input >> x >> y; G.L.push_back({x, y}); } } graf operator+(graf &G){ graf G1; for(int i=1;i<=this->noduri;i++) for(int j=1;j<=this->noduri;j++) { G1.a[i][j]=this->a[i][j]+G.a[i][j]; if(G1.a[i][j]>1)G1.a[i][j]=1; if(G1.a[i][j]!=0)G1.L.push_back({i,j}); } G1.noduri=this->noduri; G1.muchii=this->muchii; return G1; } friend ostream &operator<<(ostream &output, graf &G) { for (pair<int, int> p:(G.L)) { output << p.first << " " << p.second; output << '\n'; } } void lista_muchii_lista_matrice_adiacenta(graf &G) { for (pair<int, int> p:G.L) { G.A[p.first].push_back(p.second); a[p.first][p.second]=1; } } void BFS(int start) { //parcurgerea pe latime bool check[50]; int pred[50]; int i, j, x; for (i = 0; i < 50; i++) { check[i] = false; pred[i] = 0; } queue<int> Q; Q.push(start); pred[start] = -1; while (!Q.empty()) { x = Q.front(); Q.pop(); cout << x << " "; if (check[x])break; for (int y:A[x]) if (!pred[y]) { pred[y] = x; Q.push(y); } } cout<<'\n'; } void DFS(int start, int vizitat[50]){ //parcurgere in adancime //static int vizitat[50]; int i,j; vizitat[start]=1; cout<<start<<" "; for(int y:A[start]) if(!vizitat[y]) DFS(y,vizitat); } ////////////// void DFSu(int start, int vizitat[50]){ //parcurgere in adancime int i,j; vizitat[start]=1; for(int y:A[start]) if(!vizitat[y]) DFSu(y,vizitat); } graf transpusa(){ graf g; int i; for(i=1;i<=noduri;i++){ list<int>::iterator j; for(j=A[i].begin();j!=A[i].end();++j){ g.A[*j].push_back(i); } } return g; } bool tareconex(){ int vizitat[50]; int i; for(i=0;i<50;i++) vizitat[i]=0; DFSu(1,vizitat); for(i=1;i<=noduri;i++){ if(vizitat[i]==false) return 0; } graf g= transpusa(); for(i=0;i<50;i++) vizitat[i]=0; g.DFSu(1,vizitat); for(i=1;i<=noduri;i++){ if(vizitat[i]==false) return 0; } return 1; } void drumuri(){ int i,j,k; for( i=1; i<=noduri; i++ ) for( j=1; j<=noduri; j++ ) m[i][j] = a[i][j]; for( j=1; j<=noduri; j++ ) for( i=1; i<=noduri; i++ ) if( m[i][j] ) for( k=1; k<=noduri; k++ ) if( m[i][k] < m[k][j] ) m[i][k]=m[k][j]; for(i=1;i<=noduri;i++) { for (j = 1; j <= noduri; j++) cout << m[i][j] << " "; cout << "\n"; } } }; graf::graf(){ int i,j; for(i=0;i<50;i++) for(j=0;j<50;j++) { a[i][j]=0; m[i][j]=0; } }; graf::~graf() { L.clear(); for(int i=0;i<50;i++) A[i].clear(); } int main() { ifstream fin("C:\\Users\\Andrei\\Desktop\\Proiect_POO_1\\graf.in"); ofstream fout("C:\\Users\\Andrei\\Desktop\\Proiect_POO_1\\graf.out"); graf G1,G2,G3; fin>>G1; fin>>G2; int v[50]; for(int i=0;i<50;i++)v[i]=0; //G1.BFS(2); G1.lista_muchii_lista_matrice_adiacenta(G1); G3=G1+G2; cout<<"BF:"; G1.BFS(1); cout<<"DF:"; G1.DFS(1, v); cout<<"\nMatricea existentei drumurilor:\n"; G1.drumuri(); cout<<'\n'; if(G1.tareconex()==1)cout<<"DA"; else cout<<"NU"; fout<<G3; return 0; }
366e0e3ade42a99b2f15cd4fdc6f7e8a77902c60
[ "C++" ]
3
C++
andreidgrigore/c-
04ed7e68ea40987b9c679b61b86f1229c4c396d0
ddde4a7d3b1aec9518d41664fac0ff651606d3af
refs/heads/master
<file_sep><form action="../songs/add" method="post"> <input type="text" value="Title" onclick="this.value=''" name="song"/> <input type="text" value="Artist" onclick="this.value=''" name="artist"/> <input type="submit" value="ADD"/> </form> <h2>All Music</h2> <?php foreach ($songs as $song):?> <a class="big" href="../songs/view/ <?php echo $song['Song']['id']?>/ <?php echo strtolower(str_replace(" ","-",$song['Song']['song_name']))?>"> <span class="song"> <?php echo $song['Song']['id']?> <?php echo $song['Song']['song_name']?> - <?php echo $song['Song']['artist']?> </span> </a><br/> <?php endforeach?><file_sep>My Code Portfolio ================= Hello there visitor! Welcome to my GitHub Portfolio. This repo is designed to exhibit my coding abilities through various projects. Each project is designed around one feature/task in mind, to be coded in a specific language. Each project seeks to be self-contained and fully functional. Ideally, I would like this is to allow visitors to download a project and be able to run the application for themselves. I'll also be maintaining a wiki page for each project, so be sure to check that out for instructions, explanations and resources. Thank you for coming on by and if you'd like to contact me: - [<EMAIL>][email] - [LinkedIn][linkedin] [email]: mailto:<EMAIL> [linkedin]: http://www.linkedin.com/pub/joseph-violago/42/b11/52b<file_sep><html> <head> <title><?php echo $title?></title> <link type="text/css" rel="stylesheet" href="/diy-mvc/pub/css/songs.css" /> </head> <body> <a href="/diy-mvc/songs/viewall"><h1>Joe`s Playlist</h1></a><file_sep><?php // ToDo: Setup some sort of DELETE checker. $msg = "Success!</br> Song has been removed."; ?> <p><?php //echo $query; // ### DEBUG ### ?></p> <p>Success!</br> Song has been removed.</p> <a class="big" href="/diy-mvc/songs/viewall"><< Go Back</a><file_sep><?php class Song extends Model { }<file_sep><?php // $addMsg = $query; // ### DEBUG ### if ($song == NULL || $artist == NULL){ $addMsg = "You gotta enter something..."; } else { $addMsg = "Success!</br> $song - $artist</br> Sucessfully Added!"; } ?> <p><?php $addMsg ?></p> <a class="big" href="/diy-mvc/songs/viewall"><< Go Back</a><file_sep>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL'; DROP SCHEMA IF EXISTS `diy-mvc` ; CREATE SCHEMA IF NOT EXISTS `diy-mvc` DEFAULT CHARACTER SET latin1 ; USE `diy-mvc` ; -- ----------------------------------------------------- -- Table `diy-mvc`.`songs` -- ----------------------------------------------------- DROP TABLE IF EXISTS `diy-mvc`.`songs` ; CREATE TABLE IF NOT EXISTS `diy`.`songs` ( `id` INT(11) NOT NULL AUTO_INCREMENT , `song_name` VARCHAR(255) NOT NULL , `artist` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`) ) ENGINE = InnoDB AUTO_INCREMENT = 7 DEFAULT CHARACTER SET = latin1; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; -- ----------------------------------------------------- -- Data for table `diy-mvc`.`songs` -- ----------------------------------------------------- START TRANSACTION; USE `diy-mvc`; INSERT INTO `diy-mvc`.`songs` (`id`, `song_name`, `artist`) VALUES (1, 'Flagpole Sitta', 'Harvey Danger'); INSERT INTO `diy-mvc`.`songs` (`id`, `song_name`, `artist`) VALUES (2, 'Levels', 'Avicii'); INSERT INTO `diy-mvc`.`songs` (`id`, `song_name`, `artist`) VALUES (3, 'Tighten Up', 'The Black Keys'); INSERT INTO `diy-mvc`.`songs` (`id`, `song_name`, `artist`) VALUES (4, 'Breakfast at Tiffany\'s', 'Deep Blue Something'); INSERT INTO `diy-mvc`.`songs` (`id`, `song_name`, `artist`) VALUES (5, 'The Impression That I Get', 'The Mighty Mighty Bosstones'); COMMIT; <file_sep><?php class SongsCtrl extends Controller { function view($id = null,$song_name = null,$artist = null) { $this->set('title','Now Playing... | Joe`s Playlist'); $this->set('songs',$this->song->select($id)); } function viewall() { $this->set('title','All Songs | Joe`s Playlist'); $this->set('songs',$this->song->selectAll()); } function add() { $song = $_POST['song']; $artist = $_POST['artist']; $this->set('title','Song Added | Joe`s Playlist'); $this->set('song',$song); $this->set('artist',$artist); /* XXXX DEPRECATED: replaced by L29-L33 XXXX ** $this->set('songs',$this->song->query(' INSERT INTO songs (song_name, artist) VALUES (\''.mysql_real_escape_string($song).'\', \''.mysql_real_escape_string($artist).'\')')); ** XXXX DEPRECATED: replaced by L29-L33 XXXX */ $insert = sprintf("INSERT INTO songs (song_name, artist) VALUES('%s', '%s')", mysql_real_escape_string($song), mysql_real_escape_string($artist)); // $this->set('query',$insert); // ### DEBUG ### $this->set('songs',$this->song->query($insert)); } function delete($id = null) { $this->set('title','Song Removed | Joe`s Playlist'); /* XXXX DEPRECATED: replaced by L41-L44 XXXX ** $this->set('songs',$this->song->query('DELETE FROM songs WHERE id = \''.mysql_real_escape_string($id).'\'')); ** XXXX DEPRECATED: replaced by L41-L44 XXXX */ $delete = sprintf("DELETE FROM songs Where ID = '%d'", mysql_real_escape_string($id)); $this->set('query',$delete); $this->song->query($delete); } }<file_sep><?php /* ##### Developer Mode #### */ function devMode() { if (DEVELOPMENT_ENVIRONMENT == true) { error_reporting(E_ALL); ini_set('display_errors','On'); } else { error_reporting(E_ALL); ini_set('display_errors','Off'); ini_set('log_errors', 'On'); ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log'); } } /* #### Anti-Injection Cleanup #### */ function stripSlashesDeep($value) { $value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value); return $value; } function tidyMagicQuotes() { if ( get_magic_quotes_gpc() ) { $_GET = stripSlashesDeep($_GET ); $_POST = stripSlashesDeep($_POST ); $_COOKIE = stripSlashesDeep($_COOKIE); } } function tidyRegGlobals() { if (ini_get('register_globals')) { $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES'); foreach ($array as $value) { foreach ($GLOBALS[$value] as $key => $var) { if ($var === $GLOBALS[$key]) { unset($GLOBALS[$key]); } } } } } /* #### URL Processing #### */ function callHook() { global $url; $urlArray = array(); $urlArray = explode("/",$url); $controller = $urlArray[0]; array_shift($urlArray); $action = $urlArray[0]; array_shift($urlArray); $queryString = $urlArray; $controllerName = $controller; $model = rtrim($controller, 's'); $controller = ucfirst($controller) . 'Ctrl'; // echo $controller.'</br></br>' . $model.'</br>' . $controllerName.'</br>' . // $action.'</br>'; // ### DEBUG ### $dispatch = new $controller($model,$controllerName,$action); if ((int)method_exists($controller, $action)) { call_user_func_array(array($dispatch,$action),$queryString); } else { /* Error */ } } /* #### Load Classes #### */ function __autoload($className) { $lwrClass = strtolower($className); // $baseClass = rtrim($lwrClass, 'sctrl'); // XX DEPRECATED XX: replaced by L81 $baseClass = preg_replace ( "/sctrl/", '', $lwrClass); // echo '$className: ' . $className . "</br>"; // ### DEBUG ### // echo '$lwrClass: ' . $lwrClass . "</br>"; // ### DEBUG ### // echo '$baseClass: ' . $baseClass . "</br>"; // ### DEBUG ### /* XXXX DEPRECATED: replaced by L101-L120 XXXX ** $fileClass = "ROOT . DS . 'lib' . DS . $lwrClass . '.class.php'"; $dirApps = "ROOT . DS . 'apps-mvc' . DS"; if (file_exists($fileClass)) { echo "lib Classes Loaded."; require_once($fileClass); } elseif (file_exists($dirApps . 'controllers' . DS . $lwrClass . 'ctrl.php')) { echo "apps-mvc_controllers Classes Loaded."; require_once($dirApps . 'controllers' . DS . $lwrClass . 'ctrl.php'); } elseif (file_exists($dirApps . 'models' . DS . $lwrClass . '.php')) { echo "apps-mvc_models Classes Loaded."; require_once($dirApps . 'models' . DS . $lwrClass . '.php'); } else { // Error echo "WARNING: No classes loaded!"; } ** XXXX DEPRECATED: replaced by L101-L120 XXXX */ $classLib = ROOT . DS . 'lib' . DS . $baseClass . '.class.php'; $dirApp = ROOT . DS . 'apps-mvc' . DS; $classCtrl = $dirApp . "controllers" . DS . $lwrClass . '.php'; $classModel = $dirApp . 'models' . DS . $baseClass . '.php'; $classes = array ($classLib, $classCtrl, $classModel); // echo $classes[0] . "</br>" . $classes[1] . "</br>" . $classes[2] . "</br></br>"; // ### DEBUG ### $j = 0; for ($i = 0; $i < 3; $i++){ // echo '$i = [' . $i . "] </br>"; // ### DEBUG ### if ( file_exists($classes[$i]) ){ // echo "CLASS LOADED: " . $classes[$i] . "</br>"; // ### DEBUG ### require_once($classes[$i]); $j += 1; } // else { echo "NOT LOADED: " . $classes[$i] . "</br>"; } // ### DEBUG ### } // echo '$j = [' . $j . "] </br>"; // ### DEBUG ### // echo "</br> *** End of FOR *** </br>"; // ### DEBUG ### } /* #### DO ALL ABOVE #### */ devMode(); tidyMagicQuotes(); tidyRegGlobals(); callHook();<file_sep><h2>Now Playing:</h2> <p>Song: <?php echo $songs['Song']['song_name']?></p> <p>By: <?php echo $songs['Song']['artist']?></p> <a class="big" href="/diy-mvc/songs/delete/ <?php echo $songs['Song']['id']?>"> <span class="item">Delete this item</span> </a>
4f2ff4dfc4a956cce2d5415346c56225748b3c44
[ "Markdown", "SQL", "PHP" ]
10
PHP
JosephViolago/Portfolio
8cf1d4a37681909804eedc3e278fa938298cb9c6
bb339d59dff7a928cdce1cb74fde88a3464685da
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class RemainMonsterUI : MonoBehaviour { [SerializeField] public WaveSpawner Spawner; public TextMeshProUGUI MonsterText; private void Start() { //Spawner = GameObject.Find("Spawn").GetComponent<WaveSpawner>(); } private void Update() { MonsterText.text = string.Format("남은 몬스터 수: {0}", 1); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class HUD : UIPanel { private int level = 1; private void Update() { if (Input.GetKeyDown(KeyCode.Escape) && UI_Test.instance._currentPanel == this) { UIPanel targetPanel = UI_Test.instance.subMenu; UI_Test.instance.TriggerOpenPanel(targetPanel); Time.timeScale = 0; } if (level != UI_Test.instance.player.level) { UIPanel targetPanel = UI_Test.instance.slotMachine; UI_Test.instance.TriggerOpenPanel(targetPanel); level = UI_Test.instance.player.level; Time.timeScale = 0; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class RnadomReward : MonoBehaviour { public int[] tabel = { 1, 8, 2, 2, 2, 17, 17, 17, 17, 17 }; /// <summary> /// /// </summary> public void randomSelect() { int number = Random.Range(0, 100); if (number>=0&& number < 1) { } if (number >= 1 && number < 8) { } if (number >= 8 && number < 10) { } if (number >= 10 && number < 12) { } if (number >= 12 && number < 14) { } if (number >= 14 && number < 31) { } if (number >= 31 && number < 48) { } if (number >= 48 && number < 65) { } if (number >= 65 && number < 82) { } if (number >= 82 && number < 100) { } } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } } <file_sep>//************************************************ // EDITOR : JNE // LAST EDITED DATE : 2020.02.24 // Script Purpose : Monster_DB //****************************************************** using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; using UnityEngine; using System; [System.Serializable] public struct MonsterDB { public enum MonsterType { Zombie, DevilDog, Spiter, Tanker }; [SerializeField] public MonsterType monsterType; [SerializeField] public int ID; [SerializeField] public string name; [SerializeField] public float hp, damage, attackSpeed, attackRange, attackRadius, bloodSucking, moveSpeed, NumberOfTargets, skillCoolTime, EXP; } public class DBManager_Monster : MonoBehaviour { [ArrayElementTitle("monsterType")] [SerializeField] public MonsterDB[] monsterDB; public string[] Monster; IEnumerator Start() { WWW monsterData = new WWW("http://172.16.31.10:8080/WinterPenguin_Huma/MonsterData.php"); yield return monsterData; string monsterDataString = monsterData.text; Monster = monsterDataString.Split(';'); for (int i = 0; i < monsterDB.Length; i++) { monsterDB[i].ID = Convert.ToInt32(GetDataValue(Monster[i], "ID:")); monsterDB[i].name = GetDataValue(Monster[i], "Name:"); monsterDB[i].hp = Convert.ToSingle(GetDataValue(Monster[i], "HP:")); monsterDB[i].damage = Convert.ToSingle(GetDataValue(Monster[i], "Damage:")); monsterDB[i].attackSpeed = Convert.ToSingle(GetDataValue(Monster[i], "AttackSpeed:")); monsterDB[i].attackRange = Convert.ToSingle(GetDataValue(Monster[i], "AttackRange(m):")); monsterDB[i].attackRadius = Convert.ToSingle(GetDataValue(Monster[i], "AttackRadius(m):")); monsterDB[i].bloodSucking = Convert.ToSingle(GetDataValue(Monster[i], "BloodSucking(%):")); monsterDB[i].moveSpeed = Convert.ToSingle(GetDataValue(Monster[i], "MoveSpeed:")); monsterDB[i].NumberOfTargets = Convert.ToSingle(GetDataValue(Monster[i], "NumberOfTargets:")); monsterDB[i].skillCoolTime = Convert.ToSingle(GetDataValue(Monster[i], "SkillCoolTime:")); monsterDB[i].EXP = Convert.ToSingle(GetDataValue(Monster[i], "EXP:")); } } // Start is called before the first frame update string GetDataValue(string data, string index) { string value = data.Substring(data.IndexOf(index) + index.Length); if(value.Contains("|")) { value = value.Remove(value.IndexOf("|")); } return value; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SubMenu : UIPanel { public GameObject SettingMenu; public Button continueButton, retryButton, settingButton, giveupButton; public override void OpenBehavior() { base.OpenBehavior(); continueButton.onClick.AddListener(() => ContinueButtonClicked()); settingButton.onClick.AddListener(() => SettingButtonClicked()); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape) && UI_Test.instance._currentPanel==this) { UI_Test.instance.TriggerClosePanel(this); UI_Test.instance._currentPanel = UI_Test.instance.HUD; Time.timeScale = 1; } } void ContinueButtonClicked() { UI_Test.instance._currentPanel = UI_Test.instance.HUD; UI_Test.instance.TriggerClosePanel(this); Time.timeScale = 1; } void SettingButtonClicked() { UIPanel targetPanel = UI_Test.instance.settingMenu; UI_Test.instance.TriggerOpenPanel(targetPanel); } } <file_sep>//*************************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.3.09 // Script Purpose : RandomReawrd //*************************************** using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RandomReward : MonoBehaviour { [SerializeField] private UIManager UImanagement; public GameObject ApplyButton; [SerializeField] private Character_SuHyeon SuHyeon_get; void Start() { UImanagement = GameObject.Find("UIManager").GetComponent<UIManager>(); SuHyeon_get = GameObject.Find("Kim").GetComponent<Character_SuHyeon>(); } public int ResultCase; /// <summary> /// /// </summary> public void StartButton() { int number = Random.Range(0, 10000); if (number>=0&& number < 300) { ResultCase = 1; } if (number >= 300 && number < 2000) { ResultCase = 2; } if (number >= 2000 && number < 3600) { ResultCase = 3; } if (number >= 3600 && number < 5200) { ResultCase = 4; } if (number >= 5200 && number < 6800) { ResultCase = 5; } if (number >= 6800 && number < 8400) { ResultCase = 6; } if (number >= 8400 && number < 9999) { ResultCase = 7; } } public void Apply() { switch (ResultCase) { case 1: //꽝 UImanagement.SlotMachinePanel.SetActive(false); Debug.Log("perfect!"); break; case 2: //공격력 +10 SuHyeon_get.AtkDamage += 10; UImanagement.SlotMachinePanel.SetActive(false); break; case 3: //공격 속도 +10% SuHyeon_get.AtkSpeed += SuHyeon_get.AtkSpeed / 10f; UImanagement.SlotMachinePanel.SetActive(false); break; case 4: // 흡혈 +10%, 공격력+1 SuHyeon_get.BloodSucking += SuHyeon_get.BloodSucking / 10f; SuHyeon_get.AtkDamage += 1; UImanagement.SlotMachinePanel.SetActive(false); break; case 5: //공격 가능 몬스터 수+1, 공격력+1 SuHyeon_get.AtkCount += 1; SuHyeon_get.AtkDamage += 1; UImanagement.SlotMachinePanel.SetActive(false); break; case 6: //치명타 확률 10% 증가, 공격력1증가 if (SuHyeon_get.CriticalProb <= 90) { SuHyeon_get.CriticalProb += SuHyeon_get.CriticalProb / 10f; } else SuHyeon_get.CriticalProb = 100f; SuHyeon_get.AtkDamage += 1; UImanagement.SlotMachinePanel.SetActive(false); break; case 7: //치명타 확률 100% 증가, 공격력1증가 SuHyeon_get.CriticalProb = 100f; SuHyeon_get.AtkDamage += 1; UImanagement.SlotMachinePanel.SetActive(false); break; } } public void ShowApplyButton() { ApplyButton.SetActive(true); } } <file_sep>//********************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.12.21 // Scrit Purpose : ... //********************************** using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIManager : MonoBehaviour { public GameObject HUD; public GameObject SubMenu; public GameObject SettingMenu; public GameObject ClearPanel; public GameObject SlotMachinePanel; [SerializeField] private Player player; private int level = 1; #region Singleton /* private static UIManager _instance; public static UIManager Instance { get { return _instance; } } private void Awake() { if (null == _instance) { _instance = this; DontDestroyOnLoad(this.gameObject); } else { DestroyImmediate(this.gameObject); } }*/ #endregion private void Start() { HUD.gameObject.SetActive(true); SubMenu.SetActive(false); SettingMenu.SetActive(false); ClearPanel.SetActive(false); SlotMachinePanel.SetActive(false); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (SubMenu.activeSelf == false) { SubMenu.SetActive(true); Time.timeScale = 0; } else if (SubMenu.activeSelf && SettingMenu.activeSelf == false) { SubMenu.SetActive(false); Time.timeScale = 1; } else if (SettingMenu.activeSelf) { SettingMenu.SetActive(false); } } if (Input.GetKeyDown(KeyCode.O)) { SettingMenu.SetActive(false); Time.timeScale = 1; } if (level != player.level) { SlotMachinePanel.SetActive(true); level = player.level; Time.timeScale = 0; } } public void SettingMenuActivation() { SettingMenu.SetActive(true); } public void ContinueActivation() { SubMenu.SetActive(false); Time.timeScale = 1; } } <file_sep>/* * * EDITOR : <NAME> * Last Edit : 2021.3.10 * Script Purpose : Player's Sound Effect (SFX) Manager * */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerSound : MonoBehaviour { AudioSource speaker; // Speaker in the Player public AudioClip[] clips; // Clip list // 1. // // // private void Start() { speaker = GetComponent<AudioSource>(); } private IEnumerator SpeakerFunc() { yield return null; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Sound { public enum MonsterType { Zombie, DevilDog, Spiter, Tanker }; [SerializeField] public MonsterType monsterType; public AudioClip Attack; public AudioClip Hit; public AudioClip Dead; } public class MonsterSound : MonoBehaviour { MonsterBase monbase; public static MonsterSound instance; [ArrayElementTitle("monsterType")] [Header("SoundInput")] [SerializeField] Sound[] Sound; [Header("SoundPlyaer")] [SerializeField] AudioSource[] SoundPlayer; // Start is called before the first frame update void Start() { monbase = GameObject.Find("Monster").GetComponent<MonsterBase>(); instance = this; } public void PlaySE(string _soundName) { for(int i = 0; i < Sound.Length; i++) { if(Sound[i].monsterType.ToString() == monbase.CurrentTribe.ToString()) { if (_soundName == Sound[i].Attack.name) { for (int x = 0; x < SoundPlayer.Length; x++) { if (!SoundPlayer[x].isPlaying) { SoundPlayer[x].clip = Sound[i].Attack; SoundPlayer[x].Play(); return; } } return; } } } } } <file_sep>/* * * EDITOR : <NAME> * Last Edit : 2021.03.01 * Script Purpose : All characeter's parent Script * */ using System.Collections; using System.Collections.Generic; using UnityEngine; abstract public class Player : MonoBehaviour { public bool activatingPlayer; // Is current Playing character can move or activate now? public bool isDead = false; // Is Character dead? [SerializeField] private float hp; // Player HP public float HP { get { return hp; } set { hp = value; if (hp > MaxHP) { hp = MaxHP; } if (hp <= 0) { isDead = true; } } } public virtual IEnumerator Attack() { yield return null; } public float HpChanged(float damage) { HP += damage; return HP; } abstract public float EXP { get; set; } public int level; public float MaxHP; // 최대 체력 public float AtkDamage; // 공격력 public float AtkSpeed; // 공격 속도 public float AtkRange; // 공격 사거리 public int AtkCount; // 한번에 공격 가능한 수 public float MoveSpeed; // 이동 속도 public float AtkRadius; public float CriticalProb; public float CriticalDamage; public float BloodSucking; public float SkillCoolTime; public float Exp; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerHpBar : MonoBehaviour { private Transform cam; private DBManager_Player PlayerDB; [SerializeField] private Player player; [SerializeField] private Image hpbarImage; [SerializeField] private Transform hpBarPivot; [SerializeField] private float currentHp; [SerializeField] private float maxHp; [SerializeField] private float lerpSpeed = 0.5f; private Vector3 lookPosition; public void Start() { PlayerDB = GameObject.Find("DBManager").GetComponent<DBManager_Player>(); cam = Camera.main.transform; hpBarPivot.gameObject.SetActive(true); StartCoroutine(DataSet()); hpbarImage.fillAmount = 1.0f; } private IEnumerator DataSet() { bool DataLoading = true; while (DataLoading) { if (PlayerDB.isLoaded) { maxHp = PlayerDB.hp; DataLoading = false; } yield return null; } currentHp = maxHp; yield return null; } private void Update() { currentHp = player.HP; /* if (Input.GetKeyDown(KeyCode.P)) { player.HpChanged(10); }*/ if (maxHp != currentHp) { hpbarImage.fillAmount = Mathf.Lerp(hpbarImage.fillAmount, currentHp / maxHp, Time.smoothDeltaTime * lerpSpeed); } } private void LateUpdate() { lookPosition = new Vector3(hpBarPivot.transform.position.x, cam.position.y, cam.position.z); hpBarPivot.transform.LookAt(lookPosition); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SlotMachine : UIPanel { private void Update() { } } <file_sep>/* * * EDITOR : <NAME> * Last Edit : 2021.2.17 * Script Purpose : Setting character(Player)'s Database * */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using System; public class DBManager_Player : MonoBehaviour { private string[] characterArr; private string[] expArr; public enum PlayerID { kim = 0 } public PlayerID playerID; public int ID; // Character ID public string characterName; public float damage; public float hp; public float attackSpeed; public float attackRange; public float attackRadius; public float criticalProb; public float criticalDamage; public float bloodSucking; public float moveSpeed; public int NumberOfTargets; public float skillCoolTime; #region Exp [HideInInspector] public List<float> ExpList = new List<float>(); #endregion public bool isLoaded = false; /// <summary> /// Load Character Data(EXP,Status) from Server /// </summary> /// <param name="ID">Player's Character ID in DB</param> public void LoadingCharacterData(int ID) { isLoaded = false; ID = (int)playerID; StartCoroutine(PlayerDataGet("http://192.168.3.11:8080/WinterPenguin_Huma/CharactersDB.php",ID)); StartCoroutine(ExpDataGet("http://220.127.167.244:8080/WinterPenguin_Huma/PlayerExpDB.php", ID)); } /// <summary> /// Get Exp value from Server /// </summary> /// <param name="_url">url of Player's EXP php file</param> /// <param name="_index">ID of Player Character</param> /// <returns></returns> private IEnumerator ExpDataGet(string _url, int _index) { UnityWebRequest www = UnityWebRequest.Get(_url); yield return www.SendWebRequest(); if (www.error != null) Debug.Log(www.error.ToString()); expArr = www.downloadHandler.text.Split(';'); for(int i = 2; i < GetDataValue(expArr[_index]).Length; i++) // ID와 Name 을 건너뛰고 lv.2 경험치부터 가져오기 { ExpList.Add(Convert.ToSingle(GetDataValue(expArr[_index])[i])); } } /// <summary> /// Get Player status value from Server /// </summary> /// <param name="_characterUrl">url of Player's status php file</param> /// <param name="_index">ID of Player Character</param> /// <returns></returns> private IEnumerator PlayerDataGet(string _characterUrl, int _index) { UnityWebRequest charData = UnityWebRequest.Get(_characterUrl); yield return charData.SendWebRequest(); if (charData.error != null) { Debug.Log(charData.error.ToString()); } characterArr = charData.downloadHandler.text.Split(';'); characterName = GetDataValue(characterArr[_index], "Name:"); hp = Convert.ToSingle(GetDataValue(characterArr[_index], "HP:")); damage = Convert.ToSingle(GetDataValue(characterArr[_index], "Damage:")); attackSpeed = Convert.ToSingle(GetDataValue(characterArr[_index], "AttackSpeed:")); attackRange = Convert.ToSingle(GetDataValue(characterArr[_index], "AttackRange:")); attackRadius = Convert.ToSingle(GetDataValue(characterArr[_index], "AttackRadius:")); criticalProb = Convert.ToSingle(GetDataValue(characterArr[_index], "CriticalProbability:")); criticalDamage = Convert.ToSingle(GetDataValue(characterArr[_index], "CriticalDamage:")); bloodSucking = Convert.ToSingle(GetDataValue(characterArr[_index], "BloodSucking:")); moveSpeed = Convert.ToSingle(GetDataValue(characterArr[_index], "MoveSpeed:")); NumberOfTargets = Convert.ToInt32(GetDataValue(characterArr[_index], "NumberOfTargets:")); skillCoolTime = Convert.ToSingle(GetDataValue(characterArr[_index], "SkillCoolTime:")); isLoaded = true; } /// <summary> /// Substring Each value of php file /// </summary> /// <param name="data">One part of DB file</param> /// <param name="index">Wanted Collumn line number of DB</param> /// <returns></returns> string GetDataValue(string data, string index) { string value = data.Substring(data.IndexOf(index)+index.Length) ; if(value.Contains("|")) value = value.Remove(value.IndexOf("|")); return value; } /// <summary> /// Substring Each value of php file /// </summary> /// <param name="data">One part of DB file</param> /// <returns></returns> string[] GetDataValue(string data) { string[] value = data.Split('|'); return value; } } <file_sep>//********************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.02.03 // Scrit Purpose : ... //********************************** using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainUI : MonoBehaviour { public GameObject optionMenu; public GameObject Intro; public GameObject Stage; void Start() { optionMenu.SetActive(false); Stage.SetActive(false); Intro.SetActive(true); } void Update() { if (Intro.activeSelf == false) { if (Input.GetKeyDown(KeyCode.Escape)) { if (optionMenu.activeSelf == true) { CloseMenu(); } else { SetOptionMenuActivation(); } } } else { if (Input.anyKeyDown) { Intro.SetActive(false); Stage.SetActive(true); } } } public void CloseMenu() { optionMenu.SetActive(false); } public void SetOptionMenuActivation() { optionMenu.SetActive(true); } public void PlaySceneChange() { SceneManager.LoadScene("PlayScene"); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class BlinkText : MonoBehaviour { TextMeshProUGUI blinkText; //Text blinkText; public float time = 2.0f; void Start() { blinkText = GetComponent<TextMeshProUGUI>(); StartCoroutine(FadeInText()); } void Update() { } public IEnumerator FadeInText() { blinkText.color = new Color(blinkText.color.r, blinkText.color.g, blinkText.color.b, 0); while (blinkText.color.a < 1.0f) { blinkText.color = new Color(blinkText.color.r, blinkText.color.g, blinkText.color.b, blinkText.color.a + (Time.deltaTime/time)); yield return null; } StartCoroutine(FadeOutText()); } public IEnumerator FadeOutText() { blinkText.color = new Color(blinkText.color.r, blinkText.color.g, blinkText.color.b, 1); while (blinkText.color.a > 0.0f) { blinkText.color = new Color(blinkText.color.r, blinkText.color.g, blinkText.color.b, blinkText.color.a - (Time.deltaTime / time)); yield return null; } StartCoroutine(FadeInText()); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SlotControl : MonoBehaviour { public RandomReward randomReward; public GameObject Slot; public GameObject SlotObject; private Transform SlotObj; public int StopValue; private float timeInterval; public bool rowStopped; public string stoppedSlot; private void Start() { SlotObj = SlotObject.transform; rowStopped = true; } public void StartRotating() { SlotObj.localPosition = new Vector3(0, 0, 0); stoppedSlot = ""; StartCoroutine(Rotate()); } private IEnumerator Rotate() { rowStopped = false; timeInterval = 0.025f; for(int i = 0; i < (10*2)*3; i++) { if (SlotObj.localPosition.y <= 0f) SlotObj.localPosition = new Vector3(0, 1050f, 0); SlotObj.localPosition -= new Vector3(0, 50f, 0); yield return new WaitForSecondsRealtime(timeInterval); } /* StopValue = Random.Range(60, 100); switch (StopValue % 3) { case 1: StopValue += 2; break; case 2: StopValue += 1; break; }*/ switch (randomReward.ResultCase) { case 1: StopValue = 66; break; case 2: StopValue = 69; break; case 3: StopValue = 72; break; case 4: StopValue = 75; break; case 5: StopValue = 78; break; case 6: StopValue = 81; break; case 7: StopValue = 84; break; } for (int i = 0; i < StopValue; i++) { if(SlotObj.localPosition.y <= 0f) SlotObj.localPosition = new Vector3(0, 1050f, 0); SlotObj.localPosition -= new Vector3(0, 50f, 0); if (i > Mathf.RoundToInt(StopValue * 0.5f)) timeInterval = 0.05f; if (i > Mathf.RoundToInt(StopValue * 1f)) timeInterval = 0.1f; if (i > Mathf.RoundToInt(StopValue * 1.5f)) timeInterval = 0.15f; if (i > Mathf.RoundToInt(StopValue * 2f)) timeInterval = 0.2f; yield return new WaitForSecondsRealtime(timeInterval); } rowStopped = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { Camera mainCamera; GameObject player; private void Awake() { mainCamera = Camera.main; player = GameObject.FindGameObjectWithTag("Player"); } private void LateUpdate() { mainCamera.transform.position = new Vector3(player.transform.position.x, player.transform.position.y + 9, player.transform.position.z - (player.transform.position.y+9)*(1/Mathf.Sqrt(3))); mainCamera.transform.rotation = Quaternion.LookRotation(player.transform.position - mainCamera.transform.position ); } } <file_sep>//************************************************ // EDITOR : JNE // LAST EDITED DATE : 2020.02.22 // Script Purpose : Monster_Spiter Attack, Spit parabola //****************************************************** using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpiterAttack : MonoBehaviour { public float SpitListSize = 3; public float SpitSpeed = 1.5f; private Transform playerTransform; private float firingAngle = 45.0f; private float gravity = 9.8f; List<GameObject> SpitList; public GameObject Spit; public GameObject SpiterMouth; MonsterBase AtkSpit; void Start() { playerTransform = GameObject.FindWithTag("Player").GetComponent<Transform>(); AtkSpit = this.gameObject.GetComponent<MonsterBase>(); SpitList = new List<GameObject>(); for (int i = 0; i < SpitListSize; i++) { GameObject objSpit = (GameObject)Instantiate(Spit); objSpit.SetActive(false); SpitList.Add(objSpit); } } void Update() { if (AtkSpit.isAttack == true) { Fire(); } } void Fire() { for (int i = 0; i < SpitList.Count; i++) { if (!SpitList[i].activeInHierarchy) { SpitList[i].transform.position = SpiterMouth.transform.position; SpitList[i].transform.rotation = SpiterMouth.transform.rotation; SpitList[i].SetActive(true); Rigidbody tempRigidBodySpit = SpitList[i].GetComponent<Rigidbody>(); StartCoroutine(SimulateProjectile(i)); break; } } } IEnumerator SimulateProjectile(int i) { yield return new WaitForSeconds(0.0f); SpitList[i].transform.position = SpiterMouth.transform.position + new Vector3(0, 0.0f, 0); Vector3 Player = playerTransform.position + new Vector3(0, -playerTransform.position.y, 0); float target_Distance = Vector3.Distance(SpitList[i].transform.position, Player); float Spit_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity); float Vx = Mathf.Sqrt(Spit_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad); float Vy = Mathf.Sqrt(Spit_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad); float flightDuration = target_Distance / Vx; SpitList[i].transform.rotation = Quaternion.LookRotation(Player - SpitList[i].transform.position); float elapse_time = 0; while (elapse_time < flightDuration) { SpitList[i].transform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime * SpitSpeed); elapse_time += Time.deltaTime; yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InGameMenu : MonoBehaviour { public GameObject subMenu; public GameObject settingMenu; private void Start() { subMenu.SetActive(false); settingMenu.SetActive(false); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (subMenu.activeSelf && settingMenu.activeSelf == false) { subMenu.SetActive(false); Time.timeScale = 1; } else if (subMenu.activeSelf == false) { subMenu.SetActive(true); Time.timeScale = 0; } else if (settingMenu.activeSelf) { settingMenu.SetActive(false); } } } public void SettingMenuActivation() { settingMenu.SetActive(true); } public void ContinueActivation() { subMenu.SetActive(false); Time.timeScale = 1; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class ExpUI : MonoBehaviour { private DBManager_Player PlayerDB; [SerializeField] private Player player; [SerializeField] private Image expImage; [SerializeField] private TextMeshProUGUI levelText; [SerializeField] private float currentExp = 0; [SerializeField] private float maxExp; [SerializeField] private float lerpSpeed = 0.5f; public void Start() { PlayerDB = GameObject.Find("DBManager").GetComponent<DBManager_Player>(); expImage.fillAmount = 0; StartCoroutine(DataSet()); } private IEnumerator DataSet() { bool DataLoading = true; while (DataLoading) { if (PlayerDB.isLoaded) { maxExp = PlayerDB.ExpList[player.level]; DataLoading = false; } yield return null; } //currentExp = maxExp; yield return null; } private void FixedUpdate() { float time = Time.timeScale + 1.0f; currentExp = player.EXP; expImage.fillAmount = Mathf.Lerp(expImage.fillAmount, currentExp / maxExp, time * lerpSpeed); levelText.text = string.Format("Level {0}", player.level); } } <file_sep># WinterPenguin_StartUp First Amateur game for Joongbu Univ. students <file_sep>//*************************************** // EDITOR : <NAME> // LAST EDITED DATE : 2020.12.21 // Script Purpose : game logic //*************************************** using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Gamemanager : MonoBehaviour { /* private static Gamemanager instance = null; private void Awake() { if (null == instance) { instance = this; DontDestroyOnLoad(this.gameObject); } else { Destroy(this.gameObject); } } */ public static int StageNumber = 1; public int CurrentMonster; public static int zombieCount = 0; public static int devildogCount = 0; public static int spiterCount = 0; public static int tankerCount = 0; public static float zombiefast = 0; public static float devildogfast = 0; public static float spiterfast = 0; public static float tankerfast = 0; public List<Transform> MonsterList = new List<Transform>(); /* public static Gamemanager Instance { get { if (null == instance) { return null; } return instance; } } */ public void Stage1Select() { StageNumber = 1; zombieCount = 600; zombiefast = 0.64f; } public void Stage2Select() { StageNumber = 2; zombieCount = 600; devildogCount = 150; zombiefast = 0.64f; devildogfast = 2.56f; } public void Stage3Select() { StageNumber = 3; zombieCount = 600; devildogCount = 200; spiterCount = 40; zombiefast = 0.64f; devildogfast = 1.92f; spiterfast = 9.6f; } public void Stage4Select() { StageNumber = 4; zombieCount = 600; devildogCount = 200; spiterCount = 80; tankerCount = 8; zombiefast = 0.64f; devildogfast = 1.92f; spiterfast = 4.8f; tankerfast = 48f; } public void PlaySceneChange() { SceneManager.LoadScene("PlayScene"); } public void StageSelectSceneChange() { SceneManager.LoadScene("StageSelect"); } public void RetryButton() { } void Start() { } // Update is called once per frame void Update() { } } <file_sep>//*************************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.3.09 // Script Purpose : MonsterSpawner //*************************************** using UnityEngine; using System.Collections; using System.Collections.Generic; public class WaveSpawner : MonoBehaviour { public enum SpawnState { SPAWNING, WAITING, COUNTING }; [System.Serializable] public class Monster { public string name; public Transform enemy; } public Monster[] monsters; [SerializeField] private float waveCountdown; [SerializeField] private float oneminuteCountup = 0f; [SerializeField] private float fatserterm = 0f; public float WaveCountdown { get { return waveCountdown; } } public Transform[] spawnPoints; private SpawnState state = SpawnState.SPAWNING; public bool StartOrNotCoroutine = false; public float timeBeforeStartSpawn = 5f; public Gamemanager gamemanager; public int zombie = 0; public int devildog = 0; public int spiter = 0; public int tanker = 0; public float zombiefast_game; public float devildogfast_game; public float spiterfast_game; public float tankerfast_game; private IEnumerator enumerator_0; private IEnumerator enumerator_1; private IEnumerator enumerator_2; private IEnumerator enumerator_3; void Start() { zombie = Gamemanager.zombieCount; devildog = Gamemanager.devildogCount; spiter = Gamemanager.spiterCount; tanker = Gamemanager.tankerCount; zombiefast_game = Gamemanager.zombiefast; devildogfast_game = Gamemanager.devildogfast; spiterfast_game = Gamemanager.spiterfast; tankerfast_game = Gamemanager.tankerfast; enumerator_0 = ZombieSpawnWave(monsters[0]); enumerator_1 = DevilDogSpawnWave(monsters[1]); enumerator_2 = SpiterSpawnWave(monsters[2]); enumerator_3 = TankerSpawnWave(monsters[3]); if (spawnPoints.Length == 0) { Debug.LogError("No spawn points referenced."); } waveCountdown = timeBeforeStartSpawn; } void Update() { if (gamemanager.CurrentMonster >= 100) { state = SpawnState.WAITING; } else if (gamemanager.CurrentMonster < 100) { state = SpawnState.SPAWNING; } /* if (state == SpawnState.WAITING) { if (!EnemyIsAlive()) { WaveCompleted(); } else { return; } } */ if (waveCountdown <= 0) { if (StartOrNotCoroutine == false) { if(zombie!=0) StartCoroutine(enumerator_0); if(devildog!=0) StartCoroutine(enumerator_1); if(spiter!=0) StartCoroutine(enumerator_2); if(tanker!=0) StartCoroutine(enumerator_3); StartOrNotCoroutine =true; } if(StartOrNotCoroutine == true) { if (zombie == 0) StopCoroutine(enumerator_0); if (devildog == 0) StopCoroutine(enumerator_1); if (spiter == 0) StopCoroutine(enumerator_2); if (tanker == 0) StopCoroutine(enumerator_3); } } else { waveCountdown -= Time.deltaTime; } if(state == SpawnState.SPAWNING) { oneminuteCountup += Time.deltaTime; if (oneminuteCountup >= fatserterm) { zombiefast_game -= zombiefast_game * (75f / 1000f);//일단 좀비만 devildogfast_game -= devildogfast_game * (75f / 1000f); spiterfast_game -= spiterfast_game * (75f / 1000f); tankerfast_game -= tankerfast_game * (75f / 1000f); oneminuteCountup = 0f; } } } IEnumerator ZombieSpawnWave(Monster _monster) { while (zombie > 0) { if (state == SpawnState.SPAWNING) { SpawnEnemy(_monster.enemy); gamemanager.CurrentMonster += 1; zombie--; yield return new WaitForSeconds(Gamemanager.zombiefast); } else { yield return null; } } state = SpawnState.WAITING; //zombie==0일때로 바뀔수도 있음 yield break; } IEnumerator DevilDogSpawnWave(Monster _monster) { while (devildog > 0) { if (state == SpawnState.SPAWNING) { SpawnEnemy(_monster.enemy); gamemanager.CurrentMonster += 1; devildog--; yield return new WaitForSeconds(Gamemanager.devildogfast); } else { yield return null; } } state = SpawnState.WAITING; //zombie==0일때로 바뀔수도 있음 yield break; } IEnumerator SpiterSpawnWave(Monster _monster) { while (spiter > 0) { if (state == SpawnState.SPAWNING) { SpawnEnemy(_monster.enemy); gamemanager.CurrentMonster += 1; spiter--; yield return new WaitForSeconds(Gamemanager.spiterfast); } else { yield return null; } } state = SpawnState.WAITING; //zombie==0일때로 바뀔수도 있음 yield break; } IEnumerator TankerSpawnWave(Monster _monster) { while (tanker > 0) { if (state == SpawnState.SPAWNING) { SpawnEnemy(_monster.enemy); gamemanager.CurrentMonster += 1; tanker--; yield return new WaitForSeconds(Gamemanager.tankerfast); } else { yield return null; } } state = SpawnState.WAITING; //zombie==0일때로 바뀔수도 있음 yield break; } void SpawnEnemy(Transform _enemy) { Debug.Log("Spawning Enemy: " + _enemy.name); Transform _sp = spawnPoints[ Random.Range (0, spawnPoints.Length) ]; Instantiate(_enemy, _sp.position, _sp.rotation); } } <file_sep>//************************************************ // EDITOR : JNE // LAST EDITED DATE : 2020.02.22 // Script Purpose : Monster_Base //****************************************************** using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class MonsterBase : MonoBehaviour { public enum Tribe { Zombie, DevilDog, Spiter, Tanker }; public enum State { Idle, Move, Attack, Dead }; [SerializeField] private DBManager_Monster MonsterData; [SerializeField] private GameObject Monster; [SerializeField] protected float Damage; [SerializeField] protected float AttackSpeed; [SerializeField] protected float AttackRange; [SerializeField] protected float AttackRadius; [SerializeField] protected float BloodSucking; [SerializeField] protected float moveSpeed; [SerializeField] protected float NumberOfTargets; [SerializeField] protected float skillCoolTime; [SerializeField] protected float EXP; [SerializeField] ParticleSystem particle; protected float AttackCoolTimeCacl = 2f; protected bool canAtk = true; public bool isAttack = false; protected bool dead = false; protected Gamemanager gamemanager; protected GameObject Player; protected Player player; protected NavMeshAgent nvAgent; protected Animator Anim; protected Vector3 pushDirection; protected float distance; protected Rigidbody rb; public Tribe CurrentTribe = Tribe.Zombie; public State CurrentState = State.Idle; protected bool knockBack = false; private float hp; protected void Start() { gamemanager = GameObject.Find("GameManager").GetComponent<Gamemanager>(); MonsterData = GameObject.Find("DBManager").GetComponent<DBManager_Monster>(); player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); Player = GameObject.FindGameObjectWithTag("Player"); nvAgent = GetComponent<NavMeshAgent>(); rb = GetComponent<Rigidbody>(); Anim = GetComponent<Animator>(); StartCoroutine(CalcCoolTime()); StartCoroutine(CheckStateForActon()); StartCoroutine(DataSet()); this.nvAgent.stoppingDistance = AttackRange; this.nvAgent.speed = moveSpeed; } protected IEnumerator DataSet() { bool DataLoading = true; while (DataLoading) { for(int i = 0; i < MonsterData.monsterDB.Length; i++) { if (MonsterData.monsterDB[i].name == CurrentTribe.ToString()) { HP = MonsterData.monsterDB[i].hp; Damage = MonsterData.monsterDB[i].damage; AttackSpeed = MonsterData.monsterDB[i].attackSpeed; AttackRange = MonsterData.monsterDB[i].attackRange; AttackRadius = MonsterData.monsterDB[i].attackRadius; BloodSucking = MonsterData.monsterDB[i].bloodSucking; moveSpeed = MonsterData.monsterDB[i].moveSpeed; NumberOfTargets = MonsterData.monsterDB[i].NumberOfTargets; skillCoolTime = MonsterData.monsterDB[i].skillCoolTime; EXP = MonsterData.monsterDB[i].EXP; DataLoading = false; } } yield return null; } nvAgent.speed = moveSpeed; nvAgent.stoppingDistance = AttackRange; yield return null; } #region HP, EXP public float HP { get { return hp; } set { hp = value; if (hp <= 0) { dead = true; CurrentState = State.Dead; player.EXP += EXP; this.nvAgent.isStopped = true; this.nvAgent.speed = 0; this.gameObject.GetComponent<Collider>().enabled = false; gamemanager.CurrentMonster -= 1; Anim.SetTrigger("Death"); Invoke("Death", 2.0f); } } } void Death() { rb.gameObject.SetActive(false); this.gameObject.SetActive(false); } public float HpChanged(float damage) { rb = GetComponent<Rigidbody>(); HP += damage; particle.Play(); if (HP > 0) { knockBack = true; StartCoroutine(KnockBack()); } return HP; } #endregion #region KnockBack protected void FixedUpdate() { pushDirection = (Player.transform.position - transform.position).normalized; if(!knockBack) { FreezeVelocity(); } } protected IEnumerator KnockBack() { CurrentState = State.Idle; this.nvAgent.isStopped = true; this.nvAgent.speed = 0; if (!Anim.GetCurrentAnimatorStateInfo(0).IsName("Hit")) { Anim.SetTrigger("Hit"); } rb.velocity = pushDirection * -moveSpeed*2; yield return new WaitForSeconds(0.3f); rb.isKinematic = true; yield return new WaitForSeconds(0.25f); rb.isKinematic = false; this.nvAgent.isStopped = false; this.nvAgent.speed = moveSpeed; knockBack = false; } #endregion void FreezeVelocity() { rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; } protected bool CanAtkStateFun() { Vector3 targetDir = new Vector3(Player.transform.position.x - transform.position.x, 0f, Player.transform.position.z - transform.position.z); Physics.Raycast(new Vector3(transform.position.x, 0.5f, transform.position.z), targetDir, out RaycastHit hit, 30f); distance = Vector3.Distance(Player.transform.position, transform.position); if (hit.transform == null) { return false; } if (hit.transform.CompareTag("Player") && distance <= AttackRange) { return true; } else { return false; } } protected virtual IEnumerator CalcCoolTime() { while (true) { yield return null; if (!canAtk) { AttackCoolTimeCacl -= Time.deltaTime; if (AttackCoolTimeCacl <= 0 && !knockBack && !dead) { AttackCoolTimeCacl = AttackSpeed; canAtk = true; } } } } IEnumerator CheckStateForActon() { while (!dead) { switch (CurrentState) { case State.Idle: case State.Move: this.nvAgent.isStopped = false; isAttack = false; break; case State.Attack: isAttack = true; if(CurrentTribe == Tribe.Spiter) { Damage = 0; } break; } yield return null; } } } <file_sep>/* * * EDITOR : <NAME> * Last Edit : 2021.2.19 * Script Purpose : Player moving, rotating Controller * */ using System.Collections; using System.Collections.Generic; using System.Numerics; using UnityEngine; using Vector3 = UnityEngine.Vector3; public class CharacterController : MonoBehaviour { public bool isAttacking = false; public bool isRolling = false; private Player PlayerFunc; #region DirectionVar private float h; private float v; public float speed; public GameObject Player; #endregion DirectionVar #region Ray private Camera mainCamera; private Vector3 targetPos; public float rotSpeed; #endregion Ray #region Coroutine public Coroutine AttackCoroutine; Coroutine MoveByKeyCoroutine; Coroutine TurnAndStopCoroutine; Coroutine MouseRightCoroutine; #endregion private void Start() { mainCamera = Camera.main; PlayerFunc = GetComponent<Player>(); } private void Move() { Vector3 dir = new Vector3(h, 0, v); if (dir.magnitude > 1) { dir = dir.normalized; } transform.Translate(dir * (speed * Time.deltaTime)); if (MoveByKeyCoroutine == null) MoveByKeyCoroutine = StartCoroutine(MoveByKey(dir)); } private IEnumerator MoveByKey(Vector3 dir) { float elapsedTime = 0; while (elapsedTime < rotSpeed) { if (!isRolling) { Player.transform.forward = Vector3.Lerp(Player.transform.forward, dir, elapsedTime / rotSpeed); elapsedTime += Time.deltaTime; yield return null; } yield return null; } MoveByKeyCoroutine = null; yield break; } private void Update() { if (!isRolling) // if player is not rolling { h = Input.GetAxisRaw("Horizontal"); v = Input.GetAxisRaw("Vertical"); if ((h != 0 || v != 0) && !isAttacking) Move(); // Move if (Input.GetKey(KeyCode.Mouse0)) // Attack { isAttacking = true; Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); var temp = ray; RaycastHit hit; if (Physics.Raycast(ray, out hit, 10000f)) { targetPos = hit.point; } if (TurnAndStopCoroutine == null) TurnAndStopCoroutine = StartCoroutine(TurnAndStop(targetPos)); #if UNITY_EDITOR Debug.DrawRay(temp.origin, temp.direction * 100, Color.red); #endif } if (Input.GetKeyDown(KeyCode.Mouse1)) // Rolling forward { if (MouseRightCoroutine == null) { isRolling = true; MouseRightCoroutine = StartCoroutine(MouseRight()); } } } } #region RollingParam float rollingTime = .5f; float rollingSpeed = 2f; private float ROLLING_COOL = 5f; #endregion public IEnumerator MouseRight() { speed = speed*rollingSpeed; // increase speed as Multiply float time = 0; Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, 10000f)) { targetPos = hit.point; } Vector3 dir = (targetPos - transform.position).normalized; Vector3 des = transform.position + (dir * (speed * rollingTime)); // Calc destination with speed and time for roll forward Debug.Log(Player.transform.forward); while (time<rollingTime) { Player.transform.forward = dir; transform.position = Vector3.Lerp(transform.position, des, time/rollingTime); // Lerp Character each frames time += Time.deltaTime; yield return null; } speed = speed / rollingSpeed; isRolling = false; yield return new WaitForSeconds(ROLLING_COOL); MouseRightCoroutine = null; yield break; } private IEnumerator TurnAndStop(Vector3 dir) { float elapsedTime = 0; Vector3 direction = dir - Player.transform.position; Vector3 dirXZ = new Vector3(direction.x, Player.transform.forward.y, direction.z); while (elapsedTime < rotSpeed) { Player.transform.forward = Vector3.Lerp(Player.transform.forward, dirXZ, elapsedTime / rotSpeed); elapsedTime += Time.deltaTime; yield return null; } if (AttackCoroutine == null) // Can't move while Attacking AttackCoroutine = StartCoroutine(PlayerFunc.Attack()); TurnAndStopCoroutine = null; yield break; } }<file_sep>//********************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.02.08 // Scrit Purpose : Enemy HealthBar //********************************** using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //using System.Diagnostics; public class EnemyHpBar : MonoBehaviour { private Transform cam; private MonsterBase monster; private DBManager_Monster MonsterDB; public Image hpBarImage; public Transform hpbarPivot; public float activeTime = 3f; [SerializeField] private float currentHp; private float maxHp; private float ex_Hp; [SerializeField] private float timer; public float lerpSpeed = 2.5f; private Vector3 lookPosition; public bool timerStart; public void Start() { monster = GetComponentInParent<MonsterBase>(); MonsterDB = GameObject.Find("DBManager").GetComponent<DBManager_Monster>(); cam = Camera.main.transform; timerStart = false; hpBarImage.fillAmount = 1; //hpbarPivot.gameObject.SetActive(false); StartCoroutine(DataSet()); } #region DataSet private IEnumerator DataSet() { bool DataLoading = true; while (DataLoading) { for (int i = 0; i < MonsterDB.monsterDB.Length; i++) { if (MonsterDB.monsterDB[i].name == monster.CurrentTribe.ToString()) { maxHp = MonsterDB.monsterDB[i].hp; DataLoading = false; } } yield return null; } currentHp = maxHp; ex_Hp = currentHp; yield return null; } #endregion private void Update() { currentHp = monster.HP; if (currentHp != ex_Hp) { ex_Hp = currentHp; resetTime(); timerStart = true; } if (timerStart) { timer += Time.deltaTime; hpbarPivot.gameObject.SetActive(true); hpBarImage.fillAmount = Mathf.Lerp(hpBarImage.fillAmount, currentHp / maxHp, Time.deltaTime * lerpSpeed); if (timer > activeTime) { resetTime(); //hpbarPivot.gameObject.SetActive(false); } } } public void resetTime() { timerStart = false; timer = 0; } private void LateUpdate() { lookPosition = new Vector3(hpbarPivot.transform.position.x, cam.position.y, cam.position.z); hpbarPivot.transform.LookAt(lookPosition); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class UI_Test : MonoBehaviour { [SerializeField] public Player player; public UIPanel _basePanel; public UIPanel _currentPanel; public UIPanel HUD, subMenu, settingMenu, slotMachine; #region SingleTon public static UI_Test instance; private void Awake() { if (instance == null) instance = this; else Destroy(gameObject); } #endregion private void Start() { BasePanel(HUD); TriggerClosePanel(settingMenu); TriggerClosePanel(subMenu); TriggerClosePanel(slotMachine); TriggerOpenPanel(HUD); } public void Update() { if (_currentPanel != null) _currentPanel.UpdateBehavior(); } public void BasePanel(UIPanel panel) { _basePanel = panel; panel.OpenBehavior(); } public void TriggerPanelTransition(UIPanel panel) { TriggerOpenPanel(panel); } public void TriggerOpenPanel(UIPanel panel) { if(_currentPanel == HUD) { _currentPanel = panel; } else if(_currentPanel == subMenu && panel == settingMenu) { _currentPanel = panel; } else if(_currentPanel != null ) { TriggerClosePanel(_currentPanel); } _currentPanel = panel; panel.OpenBehavior(); } public void TriggerClosePanel(UIPanel panel) { panel.CloseBehavior(); } } <file_sep>//********************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.01.19 // Scrit Purpose : ... //********************************** using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class SkillUI : MonoBehaviour { [SerializeField] private Image skillImage; public TextMeshProUGUI skillText; [SerializeField] private DBManager_Player PlayerDB; public float cooldown; //public float skillCoolTime; [SerializeField] private float currentCoolTime; bool canUseSkill = false; public void Start() { PlayerDB = GameObject.Find("DBManager").GetComponent<DBManager_Player>(); skillImage.fillAmount = 0; StartCoroutine(DataSet()); } private IEnumerator DataSet() { bool DataLoading = true; while (DataLoading) { if (PlayerDB.isLoaded) { cooldown = PlayerDB.skillCoolTime; DataLoading = false; } yield return null; } currentCoolTime = cooldown; yield return null; } private void Update() { if (Input.GetKeyDown(KeyCode.Space) && canUseSkill) { skillImage.fillAmount = 0; canUseSkill = false; } if (canUseSkill == false) { currentCoolTime -= Time.deltaTime; if (currentCoolTime >= 0) { skillImage.fillAmount += 1 * Time.smoothDeltaTime / cooldown; skillText.text = "" + Mathf.CeilToInt(currentCoolTime); } if (skillImage.fillAmount == 1) { skillText.text = ""; canUseSkill = true; currentCoolTime = cooldown; } } } }<file_sep>//************************************************ // EDITOR : JNE // LAST EDITED DATE : 2020.02.22 // Script Purpose : Monster_spit damage //****************************************************** using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpiterSpit : MonoBehaviour { [SerializeField] private DBManager_Monster MonsterData; Player player; private float damage; void Start() { player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); MonsterData = GameObject.Find("DBManager").GetComponent<DBManager_Monster>(); damage = MonsterData.monsterDB[2].damage; } private void OnTriggerEnter(Collider collision) { if (collision.tag == "wall") { gameObject.SetActive(false); } else if (collision.tag == "Player") { gameObject.SetActive(false); player.HpChanged(-damage); } } } <file_sep>//********************************** // EDITOR : <NAME> // LAST EDITED DATE : 2021.12.21 // Scrit Purpose : ... //********************************** using System.Collections; using System.Collections.Generic; using UnityEngine; public class UI_Manager : MonoBehaviour { private static UI_Manager instance = null; public GameObject SlotMachinePanel; public static UI_Manager Instance { get { if (instance == null) { return null; } return instance; } } private void Awake() { if(null == instance) { instance = this; DontDestroyOnLoad(this.gameObject); } else { Destroy(this.gameObject); } } } <file_sep>/* * * EDITOR : <NAME> * Last Edit : 2021.2.27 * Script Purpose : Setting Character(Player)'s status * */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class Character_SuHyeon : Player { [SerializeField] private DBManager_Player PlayerDB; [SerializeField] private GameObject Player; private CharacterController characterCont; public UIManager UI; private List<GameObject> monsterList = new List<GameObject>(); // Specify monster which gonna give the damage #region Properties public bool ActivatingPlayer { get { return activatingPlayer; } set { activatingPlayer = value; if (activatingPlayer) { if (CheckActivityCoroutine == null) CheckActivityCoroutine = StartCoroutine(CheckActivity()); } else { StopCoroutine(CheckActivityCoroutine); CheckActivityCoroutine = null; } } } public override float EXP { get { return Exp; } set { Exp = value; if (Exp >= PlayerDB.ExpList[level - 1]) { Exp = Exp - PlayerDB.ExpList[level - 1]; level++; } } } #endregion #region Coroutine //Coroutine AttackCoroutine; /* [Obsoleted] Use CharacterController -> characterCont.AttackCoroutine */ Coroutine CheckActivityCoroutine; Coroutine EncroachCoroutine; #endregion private void Awake() { PlayerDB = GameObject.Find("DBManager").GetComponent<DBManager_Player>(); PlayerDB.LoadingCharacterData(0); // Load character DB characterCont = GetComponent<CharacterController>(); StartCoroutine(DataSet()); // Set character DB } private void Start() { Init(); ActivatingPlayer = true; } private void Init() { level = 1; EXP = 0; } private IEnumerator DataSet() { bool DataLoading = true; while (DataLoading) { if (PlayerDB.isLoaded) { MaxHP = PlayerDB.hp; HP = PlayerDB.hp; AtkDamage = PlayerDB.damage; AtkSpeed = PlayerDB.attackSpeed; AtkRange = PlayerDB.attackRange; AtkRadius = PlayerDB.attackRadius; CriticalProb = PlayerDB.criticalProb; CriticalDamage = PlayerDB.criticalDamage; BloodSucking = PlayerDB.bloodSucking; MoveSpeed = PlayerDB.moveSpeed; AtkCount = PlayerDB.NumberOfTargets; SkillCoolTime = PlayerDB.skillCoolTime; DataLoading = false; } yield return null; } characterCont.speed = MoveSpeed; // Apply speed param to local player status yield return null; } private IEnumerator CheckActivity() { while (ActivatingPlayer) { if (Input.GetKeyDown(KeyCode.Space)) { if (EncroachCoroutine == null) { EncroachCoroutine = StartCoroutine(Encroach()); } } yield return null; } } #region Attack Param public float radius; // Using for calculating range for skills private Vector3 playerDir; private float currentAngle; // Using for rotating Ray direction public float rotAngle; public float segments = 60; // How many rays will you shoot while sweeping one time #endregion /// <summary> /// Activate Coroutine When Player want to play basic attack /// </summary> /// <returns></returns> public override IEnumerator Attack() { currentAngle = 22.5f; radius = 3; rotAngle = 45 / segments; // Each angles that rotate every ray the player shoot playerDir = Player.transform.forward; for (float i = currentAngle; i >= -22.5f; i -= rotAngle) { Quaternion rayDir = Quaternion.AngleAxis(i, Vector3.up); // Rotate Ray Dir to Calc attack range -22.5f ~ 22.5f (Total 45 degree) Vector3 endPos = rayDir * playerDir * radius; RaycastHit[] hits; var origin = new Vector3(Player.transform.position.x, Player.transform.position.y + 0.4f, Player.transform.position.z); #if UNITY_EDITOR Debug.DrawRay(origin, endPos, Color.yellow, 1f); #endif hits = Physics.RaycastAll(origin, endPos, radius); for (int j = 0; j < hits.Length; j++) { RaycastHit hit = hits[j]; if (hit.transform.CompareTag("Monster") ) { if(monsterList.Count<5 && !monsterList.Contains(hit.transform.gameObject)) { monsterList.Add(hit.transform.gameObject); } } } } foreach (var t in monsterList) { //Attack to each monster t.GetComponent<MonsterBase>().HpChanged(-DamageCalc()); } monsterList.Clear(); yield return new WaitForSeconds(AtkSpeed); characterCont.AttackCoroutine = null; characterCont.isAttacking = false; yield break; } private float DamageCalc() { float Damage = AtkDamage; float per = Random.Range(0.0f, 100.0f); if (per >= 0f && per <= CriticalProb) { Damage = Damage * CriticalDamage; Debug.Log("Critical!!"); } return Damage; } /// <summary> /// Player Kim's original skill /// </summary> /// <returns></returns> public IEnumerator Encroach() { float timer = 0; AtkDamage += 10; BloodSucking += 20; var speedUp = AtkSpeed * 0.3f; AtkSpeed += speedUp; while (timer <= 20) { timer += Time.deltaTime; yield return null; } AtkDamage -= 10; BloodSucking -= 20; AtkSpeed -= speedUp; while (timer <= 60) { timer += Time.deltaTime; yield return null; } EncroachCoroutine = null; yield return null; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIPanel : MonoBehaviour { //public bool isOpen = false; public virtual void OpenBehavior() { gameObject.SetActive(true); /* if (!isOpen) { isOpen = true; gameObject.SetActive(true); }*/ } public virtual void UpdateBehavior() { } public virtual void CloseBehavior() { gameObject.SetActive(false); /* if (isOpen) { isOpen = false; gameObject.SetActive(false); }*/ } } <file_sep>//************************************************ // EDITOR : JNE // LAST EDITED DATE : 2020.02.22 // Script Purpose : Monster_nav //****************************************************** using System.Collections; using System.Collections.Generic; using UnityEngine; public class MonsterMelee : MonsterBase { public GameObject meleeAtkArea; protected Vector3 Look; public float CurrentHP; void Start() { base.Start(); AttackCoolTimeCacl = AttackSpeed; StartCoroutine(FSM()); StartCoroutine(ResetAtkArea()); } void Update() { if(HP > 0) { Look = new Vector3(Player.transform.position.x, transform.position.y, Player.transform.position.z); transform.LookAt(Look); } CurrentHP = HP; } IEnumerator ResetAtkArea() { while (true) { yield return null; if (!meleeAtkArea.activeInHierarchy && CurrentState == State.Attack) { yield return new WaitForSeconds(AttackSpeed); meleeAtkArea.SetActive(true); } } } protected virtual IEnumerator FSM() { yield return null; while (!dead) { yield return StartCoroutine(CurrentState.ToString()); } } protected virtual IEnumerator Idle() { yield return null; if (!Anim.GetCurrentAnimatorStateInfo(0).IsName("Idle")) { Anim.SetTrigger("Idle"); } if (CanAtkStateFun()) { if (canAtk) { CurrentState = State.Attack; } else { CurrentState = State.Idle; } } else { CurrentState = State.Move; } } protected virtual IEnumerator Attack() { yield return null; //Atk this.nvAgent.isStopped = true; this.nvAgent.updatePosition = false; this.nvAgent.updateRotation = false; this.nvAgent.velocity = Vector3.zero; if (!Anim.GetCurrentAnimatorStateInfo(0).IsName("Attack")) { Anim.SetTrigger("Attack"); } player.HpChanged(-Damage); this.nvAgent.isStopped = false; canAtk = false; CurrentState = State.Idle; } protected virtual IEnumerator Move() { yield return null; this.nvAgent.ResetPath(); this.nvAgent.isStopped = false; this.nvAgent.updatePosition = true; this.nvAgent.updateRotation = true; if (!Anim.GetCurrentAnimatorStateInfo(0).IsName("Moving")) { Anim.SetTrigger("Moving"); } if (CanAtkStateFun() && canAtk) { CurrentState = State.Attack; } else { this.nvAgent.SetDestination(Player.transform.position); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SettingMenu : UIPanel { //SettingMenu settingMenu; public override void OpenBehavior() { base.OpenBehavior(); } private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { UI_Test.instance._currentPanel = UI_Test.instance.subMenu; UI_Test.instance.TriggerClosePanel(this); } } }
f51787192362ccce6820b939b01cc26749b71035
[ "Markdown", "C#" ]
34
C#
CorgiMuzi/WinterPenguin_StartUp
0225bcffc42ee6767c42e043fdb189a2cd802175
1f3b7b9f98fbb14d0ccd38daccd2def40067733c
refs/heads/master
<repo_name>Mmear/CloudMusic<file_sep>/src/api/userQuery.js // 用户相关api import {instance} from "./setting"; const errHandler = err => Promise.reject(err); export const emailLogin = (email, pass) => { return instance.get(`/login?email=${email}&password=${pass}`).then(res => { if (res.data.code === 502) { return Promise.reject('密码错误'); } else if (res.data.code === 200) { const data = res.data; return Promise.resolve(data.account.id); } }).catch(errHandler); } export const cellPhoneLogin = (cellphone, pass) => { return instance.get(`/login/cellphone?phone=${cellphone}&password=${pass}`).then(res => { res.data.code === 200 const data = res.data.profile; return Promise.resolve({ id: data.userId, avatarUrl: data.avatarUrl, name: data.nickname, signature: data.signature, backgroundUrl: data.backgroundUrl, }); }).catch(err => { if (err.response) { console.log(err.response.data); console.log(err.response.status); } else { console.log('Error', err.message); } return Promise.reject(err); }); } export const logOut = () => { return instance.get(`/logout`).then(res => { return Promise.resolve(res.data.code); }) } // 获取用户信息(登录) , 歌单,收藏,mv, dj 数量 /user/subcount export const getSubcount = () => { return instance.get(`/user/subcount`).then(res => { return Promise.resolve(res.data); }) } // 获取用户详情 /user/detail?uid=32953014 export const getUserDetail = (id) => { return instance.get(`/user/detail?uid=${id}`).then(res => { return Promise.resolve({ level: res.data.level, listenSongs: res.data.listenSongs, }); }).catch(errHandler); } // 获取用户歌单 调用此接口, 传入用户 id, 可以获取用户歌单 /user/playlist?uid = 32953014 export const getUserPlaylist = (id) => { return instance.get(`/user/playlist?uid=${id}`).then(res => { const data = res.data.playlist.map(col => { return { name: col.name, id: col.id, tags: col.tags, picUrl: col.coverImgUrl, creator: { userId: col.creator.userId, name: col.creator.nickname, avatarUrl: col.creator.avatarUrl }, trackCount: col.trackCount } }) return Promise.resolve({cols: data}); }).catch(errHandler); } export const getPersonalFM = () => { } export default { emailLogin, cellPhoneLogin, logOut, getSubcount, getUserDetail, getUserPlaylist }<file_sep>/src/utils/storage.js export const setItem = (key, val) => { window.localStorage.setItem(key, JSON.stringify(val)); }; export const getItem = (key) => { return JSON.parse(window.localStorage.getItem(key)); } export default { setItem, getItem }<file_sep>/src/store/actions.js import songApi from "@/api/composionQuery"; // 检查是否有重复的歌曲,有则重新播放该歌曲并放至顶端 const DEFAULT_IMG_URL = require("@/assets/img/logo.png"); const checkDuplicate = (songList, id) => { return songList.findIndex(item => { return item.id === id; }); }; export default { // 更改播放状态 changePlayerStatus({ commit }) { commit("changePlayerStatus"); }, // 插入一条歌曲至播放列表顶部 insertSong({ state, commit }, song) { // console.log("[Action:insertSong] " + JSON.stringify(song)); commit("setFullScreen", true); let suspIndex = checkDuplicate(state.playlist, song.id); let playlist = state.playlist.slice(0); // song.album.picUrl = DEFAULT_IMG_URL; // 歌曲已经存在,直接播放歌曲 if (suspIndex > -1) { // 改变当前索引 const theSong = playlist.splice(suspIndex, 1); commit("setCurrentSong", ...theSong); // splice返回的是一个数组 commit("setCurrentIndex", suspIndex); } else { commit("addToPlaylist", song); commit("setCurrentSong", song); commit("setCurrentIndex", 0); } }, /** * @description 插入多条歌曲至播放列表中 * @param {Array} songs 要添加的歌曲列表 * @param {number} activeIndex 当前选中的歌曲在songs中的位置 */ insertSongs({ state, commit }, { songs, activeIndex }) { if (!Array.isArray(songs)) { return; } let playlist = state.playlist.slice(0); let activeId = songs[activeIndex].id; const check_curry = checkDuplicate.bind(null, playlist); // 获取不重复的歌曲 songs = songs.filter(item => { return check_curry(item.id) === -1; }); // 将传入的歌曲列表添加至播放列表头部 playlist = [...songs, ...playlist]; // 如果选中的歌曲之前在播放列表中 if (playlist[activeIndex] && playlist[activeIndex].id !== activeId) { // 重新计算一遍现在的index activeIndex = check_curry(null, playlist); } commit("setPlaylist", playlist); commit("setCurrentSong", playlist[activeIndex]); commit("setCurrentIndex", activeIndex); }, setFullScreen({ commit }, val) { commit("setFullScreen", val); }, // 设置播放状态 setPlayingStatus({ commit }, val) { commit("setPlayingStatus", val); }, // 从播放列表中移除指定序号的歌曲 removeSong({ state, commit }, { id, index }) { if (checkDuplicate(state.playlist, id) === -1) { return; } const currentIndex = state.currentIndex; let playlist = state.playlist.slice(0); playlist.splice(index, 1); commit("setPlaylist", playlist); // 如果currentIndex > index,则后退一位,否则不变 let newIndex = currentIndex > index ? currentIndex - 1 : currentIndex; if (newIndex === currentIndex) { // 播放列表为空 if (playlist.length <= 0) { commit("setCurrentIndex", -1) return; } // 删除了最后一首,且正在播放 if (newIndex >= playlist.length) { newIndex = 0; } // newIndex = currentIndex 的状态不会被watch到 commit("setCurrentSong", playlist[newIndex]); } commit("setCurrentIndex", newIndex); }, // 移除所有歌曲 removeAllSongs({ commit }) { const playlist = []; commit("setCurrentIndex", -1); commit("setPlaylist", playlist); } }; <file_sep>/src/api/composionQuery.js // 歌曲、歌手相关api import { instance } from "./setting"; const errHandler = err => Promise.reject(err); // 获取歌曲可用性 export const checkAvailability = id => { return instance .get(`/check/music?id=${id}`) .then(res => Promise.resolve(res.data.success)) .catch(errHandler); }; // 获取歌曲url export const getSongUrl = id => { id = Array.isArray(id) ? id.join(",") : id; return instance .get(`/song/url?id=${id}`) .then(res => { return res.data.code === 200 ? Promise.resolve(res.data.data[0].url) : "网络错误"; // res.data.data.url }) .catch(errHandler); }; // 获取歌词 export const getLyric = id => { return instance .get(`/lyric?id=${id}`) .then(res => { const data = res.data; if (data.lrc || data.klyric || data.tlyric) { return Promise.resolve({ lyric: data.lrc, // 普通歌词 klyric: data.klyric ? data.klyric : "", tlyric: data.tlyric ? data.tlyric : "" // 外文歌词翻译 }); } }) .catch(errHandler); }; // 获取歌曲详情 export const getSongDetail = id => { return instance .get(`/song/detail?ids=${id}`) .then(res => { const data = res.data.songs[0]; return Promise.resolve({ name: data.name, artists: data.ar, album: data.al // 包含歌曲封面 }); }) .catch(errHandler); }; // 获取专辑详情,其中每一条都是song形式 export const getAlbumDetail = id => { return instance .get(`/album?id=${id}`) .then(res => { const album = res.data.songs[0].al; const songList = res.data.songs.map(song => { return { artists: song.ar, alias: song.alia, name: song.name, songId: song.id }; }); return Promise.resolve({ album: { name: album.name, coverUrl: album.picUrl, alias: album.alias, }, songList }); }) .catch(errHandler); }; export default { checkAvailability, getSongUrl, getLyric, getSongDetail }<file_sep>/src/router/routes.js // import index from '@/pages/PgIndex' // import userZone from '@/pages/PgUserZone'; // 路由懒加载 const index = () => import("@/pages/PgIndex"); const userZone = () => import("@/pages/PgUserZone"); const indexMusic = () => import("@/pages/PgIntro"); const colList = () => import("@/pages/PgColList"); const login = () => import("@/pages/PgLogin"); const search = () => import("@/pages/PgSearch"); const routes = [ { path: "/", redirect: "/index" }, { path: "/index", component: index, redirect: "/index/music", children: [ { name: "indexMusic", path: "music", component: indexMusic, }, ] }, { path: "/userzone", name: "userZone", component: userZone, }, { path: "/login", name: "login", components: { // default: index, extraView: login } }, { path: "/col/:col", name: "colList", props: true, components: { extraView: colList } }, { path: "/search", name: "search", components: { searchView: search } } ]; export default routes; <file_sep>/README.md # CloudMusic 通过`Vue`框架开发的仿网易云音乐移动端项目 😘 ## 技术栈 1. 网易云音乐 API [Binaryify/NeteaseCloudMusicApi](https://github.com/Binaryify/NeteaseCloudMusicApi) 2. Vue 全家桶 3. axios 4. vue-lazyloader 5. better-scroll ## 功能 * [x] 基本音乐播放功能 * [x] 推荐歌单、音乐的获取 * [x] 登录功能(登录后获取个人歌单) * [x] 搜索功能(不完善) * [ ] 排行榜 * [ ] 私人 FM ### 待开发页面 * [ ] 歌手主页 / 专辑主页 * [ ] 评论页 ... ## 运行方法 ### 将项目和 API 克隆至本地 ``` <EMAIL>:Mmear/CloudMusic.git <EMAIL>:Binaryify/NeteaseCloudMusicApi.git ``` ### 安装依赖并运行 API 服务 ``` cd .\NeteaseCloudMusicApi\ npm run install node .\app.js ``` ### 安装本项目依赖 ``` cd .\CloudMusic\ npm run install ``` ### 运行 or 构建 ``` npm run serve // visit http://localhost:8080 npm run build ``` ## 页面展示 ![index](sample/index.png) ![userzone](sample/userzone.png) <file_sep>/src/api/minxin.js import { mapActions, mapMutations, mapState } from "vuex"; import songApi from './composionQuery'; // 获取歌曲信息的Minxin export default { methods: { ...mapActions(['']), ...mapMutations(['']), // 向播放列表添加歌曲 _getSongRelated(id) { const songUrl = songApi.getSongUrl(id); const detial = songApi.getSongUrl(id); const lyric = songApi.getLyric(id); } }, computed: { } }<file_sep>/src/utils/utils.js // 工具函数 export const domUtils = { /** * 判断DOM元素是否有该类名 * @param {HTMLElement} el dom元素 * @param {string} cName 类名 */ hasClass(el, cName = "") { // const elClassList = el.className; // if (cName && el.classList && el.classList.contains) { // return el.classList.contains(cName); // } else { // return (elClassList.indexOf(cName) === -1); // } return el.classList.contains(cName); }, /** * 向指定DOM添加类 * @param {HTMLElement} el * @param {string|Array} cName */ addClass(el, cName = "") { typeof cName === "string" ? el.classList.add(cName) : Array.isArray(cName) ? el.classList.add(...cName) : ""; }, /** * * @param {HTMLElement} el * @param {string} attr 自定义属性值,一般以'data-xxx'存在,传入后半段 * @param {*} val */ customAttribute(el, attr = "", val) { return val ? (el.dataset[attr] = val) : el.dataset[attr]; }, // 节流函数 debounce(fn, delay) { let timer = null; return function(...args) { timer ? clearTimeout(timer) : (timer = setTimeout(() => { fn.apply(this, args); }, delay)); }; } }; /** * 时间戳转换 * @param {number} time 传入秒时间 */ export const timeParser = (time) => { time = Math.floor(time); const min = Math.floor(time / 60) .toString() .padStart(2, "0"); const sec = Math.floor(time % 60) .toString() .padStart(2, "0"); return `${min}:${sec}`; };
ba5e0240574e2cebd7e629de2f183ab3946aef13
[ "JavaScript", "Markdown" ]
8
JavaScript
Mmear/CloudMusic
3086c5aad5d95707b687a9865df98c80e0215a88
7dda4f5a212b90c82b48e5bc30f7a2ade59b1ea7
refs/heads/master
<repo_name>tomasz-zieba/RISK<file_sep>/Risk.py # -*- coding: utf-8 -*- """ Created on Sun May 27 20:05:35 2018 @author: Tomek """ # -*- coding: utf-8 -*- """ Created on Mon May 21 15:25:45 2018 @author: Tomek """ # -*- coding: utf-8 -*- """ Created on Fri May 18 20:31:07 2018 @author: Tomek """ import random class wrongLandException(Exception): """ wrongLandException is raised by the setUnitsFromHand(), moveUnits(), attack() methods in the Player class to indicate that there is a problem with lands. You can use NoChildException as is, you do not need to modify/add any code. """ class wrongNumUnits(Exception): """ wrongNumUnits is raised by the setUnitsFromHand(), moveUnits(), attack() methods in the Player class to indicate that there is a problem with number of units. You can use wrongNumUnits as is, you do not need to modify/add any code. """ class noPassage(Exception): """ noPassage is raised by the moveUnits() methods in the Player class to indicate that there is no passage between to lands. You can use noPassage as is, you do not need to modify/add any code. """ class Map(object): def __init__(self, lands, neighboursLand): """ Initialize Map instance. lands: list of lands neighboursLand: dict, keys = land, value = list of neighbours land mapa: dictionary where keys are lands and """ self.lands = lands self.neighboursLand = neighboursLand self.mapa = {} for i in lands: self.mapa[i] = [None, 1] def getOwner(self,land): """ land: string, name of land return: string, name of the land's owner """ return str(self.mapa[land][0]) def getUnits(self, land): """ land: string, name of land return: int, number of units """ return self.mapa[land][1] def setOwner(self, land, name): """ land: string, name of land name: string, name of owner of land return: nothing """ self.mapa[land][0] = name def setUnits(self, land, units): """ land: string, name of land units: int, number of units return: nothing """ self.mapa[land][1] += units def removeUnits(self, land, units): """ land: string, name of land units: int, number of tanks return: nothing """ self.mapa[land][1] -= units def uptadeMap(self, land1,land2, num1, num2, player1, player2): """ land1: string, attacking land land2: string, attacked land num1: int, number of points on attacking die num2: int, number of points on defense die player1: string, name of attackig player player2: string, name of attacked player return: True if land2 change owner to player1, otherwise return False """ if num1>num2: self.mapa[land2][1] -= 1 if self.mapa[land2][1] == 0: self.mapa[land2][0] = player1.name self.mapa[land2][1] = 1 self.mapa[land1][1] -= 1 return True elif num1 <= num2: self.mapa[land1][1] -= 1 return False class Player(object): def __init__(self, mapa, unitsOnHand, lands, name = None): """ mapa: instance of class Map lands: dictionary, key = name of land, value = list of naighbours unitsOnHand: int, number of units name: string, name of Player """ self.mapa = mapa self.unitsOnHand = unitsOnHand self.unitsOnMap = 0 self.lands = lands self.name = name def getName(self): """ return: name of player """ return self.name def setName(self, name): """ name: string, name of player return: nothing """ self.name = name def setUnitsFromHand(self, land, unit): """ land: string, name of land unit: int, number of tanks to put on map return:nothing """ if self.unitsOnHand >= unit and land in self.lands: self.mapa.setUnits(land, unit) self.unitsOnHand -= unit self.unitsOnMap += unit elif land not in self.lands: raise wrongLandException elif self.unitsOnHand < unit or unit <= 0: raise wrongNumUnits def appendNewUnits(self): """ adds new units to hand depends on number of lands return: nothing """ self.unitsOnHand += int(len(self.lands) / 3) def moveUnits(self, land1, land2, lands, units): """ land1: string, name of land to remove tanks land2: string, name of land to put on tanks units: int, number of units to move return: nothing """ # DEPTH FIRST SEARCH # def is_there_way(land1,land2, lands, lista = [], passage = False): # lista.append(land1) # for i in lands[land1]: # if i == land2: # passage = True # return passage # elif i in lands and i not in lista: # passage = is_there_way(i, land2, lands, lista) # if passage == True: # return passage # return passage # BREADTH FIRST SEARCH def is_there_way(land1,land2, lands): checkedLands = [land1] landsToCheck = [] for i in lands[land1]: if i in lands: landsToCheck.append(i) checkedLands.append(i) for i in landsToCheck: if i == land2: return True else: if i in lands: for j in lands[i]: if j not in checkedLands and j in lands: landsToCheck.append(j) checkedLands.append(j) return False if land1 not in self.lands and land2 not in self.lands: raise wrongLandException elif self.mapa.getUnits(land1) - units < 1: raise wrongNumUnits # elif is_there_way(land1,land2, self.lands, lista = []) == False: # DEPTH FIRST SEARCH elif is_there_way(land1, land2, self.lands) == False: # BREADTH FIRST SEARCH raise noPassage else: self.mapa.removeUnits(land1,units) self.mapa.setUnits(land2, units) def attack(self, land1, land2, units): """ land1: string, name of attacking land land2: string, name of attacked land units: int, number of tanks to attack return: nothing """ scores = [] if land1 not in self.lands or land2 in self.lands: raise wrongLandException elif land1 not in self.mapa.mapa or land2 not in self.mapa.mapa: raise wrongLandException elif land2 not in self.mapa.neighboursLand[land1]: raise wrongLandException elif units > 3 or self.mapa.getUnits(land1) <= units: raise wrongNumUnits else: for i in range(units): attackingDie = random.choice([1,2,3,4,5,6]) scores.append(attackingDie) scores = sorted(scores) scores = scores[::-1] return scores def defense (self, land1, land2): """ land1: string, name of attacking land land2: string, name of attacked land tanks: int, number of tanks to attack return: nothing """ scores = [] if self.mapa.getUnits(land2) >=2: for i in range(2): defenseDie = random.choice([1,2,3,4,5,6]) scores.append(defenseDie) elif self.mapa.getUnits(land2) == 1: defenseDie = random.choice([1,2,3,4,5,6]) scores.append(defenseDie) scores = sorted(scores) scores = scores[::-1] return scores class Game(object): def __init__(self, players, goal = 0.8): """ players: list, instances od class Player goal: float from 0 to 1, procent of lands to win a game """ self.players = players tempLands = lands[:] self.goal = goal for i in range(len(lands)): temp = tempLands[random.randrange(0,len(tempLands))] self.players[(i + 1) % len(self.players)].lands[temp] = self.players[(i + 1) % len(self.players)].mapa.neighboursLand[temp] tempLands.remove(temp) def Attack(self, player1, player2, land1, land2, AttackDie, defenseDie): #, defenseTank): """ player1: instance of attacking player player2: instance of defense Player land1: string, name of attacking land land2: string, name of attacked land return: nothing """ for i in range(min(len(AttackDie), len(defenseDie))): attack = self.players[self.players.index(player1)].mapa.uptadeMap(land1,land2, AttackDie[i], defenseDie[i], player1, player2) if attack == True: player1.lands[land2] = player2.lands[land2] del player2.lands[land2] return True return None def checkGoal(self, player): """ player: instance of class Player return: True if player achieve a goal, False otherwise """ if len(player.lands) >= len(player.mapa.lands)*self.goal: return True else: return False lands = [ 'Alaska', 'Alberta', 'Central America', 'Eastern United States', 'Greenland', 'Northwest Territory', 'Ontario', 'Quebec', 'Western United States', 'Argentina', 'Brazil', 'Peru', 'Venezuela', 'Great Britain', 'Iceland', 'Northern Europe', 'Scandinavia', 'Southern Europe', 'Ukraine', 'Western Europe', 'Congo', 'East Africa', 'Egypt', 'Madagascar', 'North Africa', 'South Africa', 'Afghanistan', 'China', 'India', 'Irkutsk', 'Japan', 'Kamchatka', 'Middle East', 'Mongolia', 'Siam', 'Siberia', 'Ural', 'Yakutsk', 'Eastern Australia', 'Indonesia', 'New Guinea', 'Western Australia' ] neighboursLand = { 'Alaska':['Northwest Territory', 'Alberta', 'Kamchatka'], 'Alberta':['Alaska', 'Northwest Territory', 'Ontario', 'Western United States'], 'Central America':['Western United States', 'Eastern United States', 'Venezuela'], 'Eastern United States':['Central America', 'Western United States', 'Ontario', 'Quebec'], 'Greenland':['Northwest Territory', 'Quebec', 'Ontario', 'Iceland'], 'Northwest Territory':['Alaska', 'Alberta', 'Ontario', 'Greenland'], 'Ontario':['Northwest Territory', 'Alberta', 'Western United States', 'Eastern United States', 'Quebec', 'Greenland'], 'Quebec':['Ontario', 'Eastern United States', 'Greenland'], 'Western United States':['Alberta', 'Ontario', 'Eastern United States', 'Central America'], 'Argentina':['Peru', 'Brazil'], 'Brazil':['Argentina', 'Peru', 'Venezuela', 'North Africa'], 'Peru':['Brazil', 'Argentina', 'Venezuela'], 'Venezuela':['Peru', 'Brazil', 'Central America'], 'Great Britain':['Iceland', 'Scandinavia', 'Northern Europe', 'Western Europe'], 'Iceland':['Greenland', 'Great Britain', 'Scandinavia'], 'Northern Europe':['Great Britain', 'Scandinavia', 'Ukraine', 'Southern Europe', 'Western Europe'], 'Scandinavia':['Iceland', 'Ukraine', 'Northern Europe', 'Great Britain'], 'Southern Europe':['Western Europe', 'Northern Europe', 'Ukraine', 'Middle East', 'Egypt', 'North Africa'], 'Ukraine':['Middle East', 'Southern Europe', 'Northern Europe', 'Scandinavia', 'Ural', 'Afghanistan'], 'Western Europe':['Great Britain', 'Northern Europe', 'Southern Europe', 'North Africa'], 'Congo':['North Africa', 'East Africa', 'South Africa'], 'East Africa':['South Africa', 'Congo', 'North Africa', 'Egypt'], 'Egypt':['North Africa', 'East Africa', 'Middle East', 'Southern Europe'], 'Madagascar':['South Africa', 'East Africa'], 'North Africa':['Brazil', 'Egypt', 'Western Europe', 'Southern Europe', 'East Africa', 'Congo'], 'South Africa':['Congo', 'East Africa', 'Madagascar'], 'Afghanistan':['Middle East', 'Ukraine', 'Ural', 'China', 'India'], 'China':['Mongolia', 'Siam', 'Siberia', 'Ural', 'Afghanistan', 'India'], 'India':['Middle East', 'Afghanistan', 'China', 'Siam'], 'Irkutsk':['Mongolia', 'Siberia', 'Yakutsk', 'Kamchatka'], 'Japan':['Kamchatka', 'Mongolia'], 'Kamchatka':['Japan', 'Mongolia', 'Irkutsk', 'Yakutsk', 'Alaska'], 'Middle East':['East Africa', 'Egypt', 'Southern Europe', 'Ukraine', 'Afghanistan', 'India'], 'Mongolia':['Japan', 'China', 'Siberia', 'Irkutsk', 'Kamchatka'], 'Siam':['Indonesia', 'India', 'China', ], 'Siberia':['China', 'Ural', 'Yakutsk', 'Irkutsk', 'Mongolia'], 'Ural':['Ukraine', 'Afghanistan', 'China', 'Siberia'], 'Yakutsk':['Siberia', 'Irkutsk', 'Kamchatka'], 'Eastern Australia':['New Guinea', 'Western Australia'], 'Indonesia':['Siam', 'New Guinea', 'Western Australia'], 'New Guinea':['Eastern Australia', 'Indonesia', 'Western Australia'], 'Western Australia':['Eastern Australia', 'Indonesia', 'New Guinea'] } def RISK(numPlayers, lands, neighboursLand, numUnits): """ numPlayers: int, number of players lands: list, list with names of all lands neighboursLand: dictionary, dickt with key: name of land, value: names of neighbours lands numUnits: int, number of units to be deployed at the beginning of the game """ world = Map(lands,neighboursLand) players = [] for i in range(numPlayers): players.append(Player(world,numUnits,{})) gra = Game(players) ''' SET NAMES TO PLAYERS ''' for i in range(numPlayers): Flag = False print('Welcom Player ', i + 1,' in RISK game.') print('Type the name of the ', i+1, ' player.') isNameOccupied = True while isNameOccupied == True: # while loop responsible for not repeat name twice isNameOccupied = False name = input() for j in players: if j.getName() == name: isNameOccupied = True if isNameOccupied == True: print('The given name is occupied. Enter a different name.') else: gra.players[i].setName(name) while Flag == False: print('Your name is ', gra.players[i].getName()) print('If this name is correct enter "OK". If You want to change your name, enter the name again.') name = input() if name == 'OK': Flag = True else: gra.players[i].setName(name) for i in gra.players: for j in i.lands: world.setOwner(j, i.getName()) ''' LOCATE TANKS ON MAP ''' print('Now, place the units on the map.') allTanksOnHands = 0 # UNITS OF ALL PLAYERS alreadySetTanksOnHands = 0 # NUMBER OF ALREADY USED UNITS for i in range(len(gra.players)): #SUM UNITS OF ALL PLAYERS allTanksOnHands += gra.players[i].unitsOnHand firstPlayer = random.randrange(1, numPlayers + 1) # RANDOMLY CHOOSE FIRST PLAYER num = firstPlayer while alreadySetTanksOnHands < allTanksOnHands: print('----------------------------') Flag = False while Flag == False: if gra.players[num%numPlayers - 1].unitsOnHand == 0: # <NAME> NIE MA JEDNOSTEK DO ROZLOKOWANIA PUSZCZA DALEJ KOLEJKĘ num+=1 break print('Player turn, ', gra.players[num%numPlayers - 1].getName()) print('The number of available units: ', gra.players[num%numPlayers - 1].unitsOnHand) print('List of your territories with the number of units') print('--------------------------------------------------------') for i in gra.players[num%numPlayers - 1].lands: print(i, ': number of units: ', gra.players[0].mapa.getUnits(i)) print('--------------------------------------------------------') print('To place units on your territory, enter the number of units (max 3 units)') print('confirm with "enter". Then enter selected area and confirm with "enter"') input_ = input() input_2 = input() if input_ == '1' or input_ == '2' or input_ == '3': try: gra.players[num%numPlayers - 1].setUnitsFromHand(input_2, int(input_)) Flag = True num+=1 alreadySetTanksOnHands += int(input_) except wrongNumUnits: print('Units Error. Try again.') except wrongLandException: print('Territory error. Try again.') else: print('Incorrect data. Try again') ''' MAIN GAME ''' num = firstPlayer firstRoundNumber = 1 # RESPONSIBLE FOR MISSING THE STAGE OF PLACING THE NEW UNITS IN THE FIRST ROUND while Flag == True: print('Turn of the player ', gra.players[num%numPlayers - 1].getName()) if firstRoundNumber > numPlayers: gra.players[num%numPlayers - 1].appendNewUnits() while gra.players[num%numPlayers - 1].unitsOnHand > 0: print('Number of new units to be deployed:', gra.players[num%numPlayers - 1].unitsOnHand) print('List of your territories with the number of units') print('--------------------------------------------------------') for i in gra.players[num%numPlayers - 1].lands: print(i, ': number of units: ', gra.players[0].mapa.getUnits(i)) print('--------------------------------------------------------') print('To place units on your territory, enter the number of units,') print('confirm with "enter". Then enter selected area and confirm with "enter"') input_ = input() input_2 = input() try: gra.players[num%numPlayers - 1].setUnitsFromHand(input_2, int(input_)) except wrongNumUnits: print('Units Error. Try again.') except wrongLandException: print('Territory Error. Try again.') # ATTACK PHASE endRoundDecision = False while endRoundDecision == False: print('List of your territories with the number of units') print('--------------------------------------------------------') for i in gra.players[num%numPlayers - 1].lands: print(i, ': number of units: ', gra.players[0].mapa.getUnits(i)) print('--------------------------------------------------------') print('Choose territory you want to attack.') print('Enter the name of the territory you want to attack from.') print('Then enter the name of the territory you want to attack.') print('At the end, enter the number of units you want to attack.') print('Max 3 units.') print('If you do not want to attack, enter "end"') AttacingLand = input() if AttacingLand == 'end': break AttackedLand = input() NumOfUnits = input() correctAttack = False try: attackScore = gra.players[num%numPlayers - 1].attack(AttacingLand, AttackedLand, int(NumOfUnits)) correctAttack = True except wrongNumUnits: print('Units Error. Try again.') except wrongLandException: print('Territory error. Try again.') except KeyError: print('Incorrect data.') if correctAttack == True: for i in range(len(players)): if players[i].getName() == world.getOwner(AttackedLand): index = i # index: INDEX ATTACKED PLAYER IN LIST PLAYERS attackedPlayer = gra.players[index].getName() print(attackedPlayer, ' your territory') print(AttackedLand, ': number of units: ',gra.players[num%numPlayers - 1].mapa.getUnits(AttackedLand)) print('is under attack.') print(gra.players[num%numPlayers - 1].getName(), 'Press enter to roll the dice') input() print('The result of your attack is: ', attackScore) print(attackedPlayer, 'Press enter to roll the dice') input() defenseScore = gra.players[index].defense(AttacingLand, AttackedLand) print('The result of your defense is: ', defenseScore) attack = gra.Attack(gra.players[num%numPlayers - 1], gra.players[index], AttacingLand, AttackedLand, attackScore, defenseScore) if attack == True: print(gra.players[num%numPlayers - 1].getName(), ' you take control on the territory ', AttackedLand) print('Do you want to transfer more units to the new territory?') print('Enter "yes" or "no"') if input() == 'yes': moveUnits = True while moveUnits == True: print('Enter the number of units you want to transfer.') print('Remember that in the area',AttacingLand,' must remain at least one unit ') units = input() try: gra.players[num%numPlayers - 1].moveUnits(AttacingLand, AttackedLand, gra.players[num%numPlayers - 1].lands,int(units)) moveUnits = False except wrongNumUnits: print('Incorrect number of units') print('List of your territories with the number of units') print('--------------------------------------------------------') for i in gra.players[num%numPlayers - 1].lands: print(i, ': number of units: ', gra.players[0].mapa.getUnits(i)) print('--------------------------------------------------------') smallDecision = False while smallDecision == False: print('Do you want to continue the attack action?') print('To end the attack action, enter "end".') print('To continue the attack action, enter "attack".') decision = input() if decision == 'end': endRoundDecision = True smallDecision = True elif decision == 'attack': smallDecision = True else: print("Incorrect data.") # MOVING UNITS AFTER THE COMPLETE PHASE OF ATTACKS shiftPhase = True while shiftPhase == True: print('List of your territories with the number of units') print('----------------------------') for i in gra.players[num%numPlayers - 1].lands: print(i, ': number of units: ', gra.players[0].mapa.getUnits(i)) print('----------------------------') print('To move units, enter the name of the area from which you want to move units,') print('then enter the name of the area to which you want to move the units.') print('Finally, enter the number of units') print('Remember that the areas must be connected, and that there must be a minimum of 1 unit in each territory ') print('To end the round, enter "end"') smallshiftPhase = True smallDecision = False while smallshiftPhase == True: shiftFrom = input() if shiftFrom == 'end': smallDecision = True endRoundDecision = True shiftPhase = False break else: shiftTo = input() numOfShiftTanks = input() try: gra.players[num%numPlayers - 1].moveUnits(shiftFrom, shiftTo, gra.players[num%numPlayers - 1].lands, int(numOfShiftTanks)) smallshiftPhase = False except wrongLandException: print('Area error.') except wrongNumUnits: print('Unit error.') except noPassage: print('No transition between areas.') except ValueError: print('Incorrect data.') print('List of your territories with the number of units:') print('--------------------------------------------------------') for i in gra.players[num%numPlayers - 1].lands: print(i, ': number of units: ', gra.players[0].mapa.getUnits(i)) print('--------------------------------------------------------') while smallDecision == False: print('Do you want to continue the phase of moving units?') print('To end the round, enter "end".') print('Aby kontynuować akcję przemieszczania jednostek wpisz "next".') decision = input() if decision == 'end': endRoundDecision = True smallDecision = True shiftPhase = False elif decision == 'next': smallDecision = True else: print("Nieprawidłowe dane.") if gra.checkGoal(players[num%numPlayers - 1]) == True: print('Congratulations!') print('Player ', gra.players[num%numPlayers - 1].getName(), ' won the game.') print('---------------------') print('End of the game.') Flag = False else: num+=1 #CHANGE PLAYER IN THE NEXT ROUND firstRoundNumber +=1 #RESPONSIBLE FOR MISSING THE FIRST STAGE MAINGAME IN THE FIRST ROUND
ac259ea0b515abb0c0a166e52ca1bd5e85e65b39
[ "Python" ]
1
Python
tomasz-zieba/RISK
3b2c53037445c5c33c216920cdb9f4d66e12e160
77a79556288a789b8d013fd9854c2be565a96960
refs/heads/master
<repo_name>Sivapand74/DP<file_sep>/DesignPattern/src/IteratorDP/Container.java package IteratorDP; public interface Container { public Iterator1 getIterator(); }
8f91dbf7eed6565f10d9a5e5888ff95eafe6dec5
[ "Java" ]
1
Java
Sivapand74/DP
480f9ac3db335b0f1da730b3dac09929c646baea
17ed10dc9f4b1dd4095fd2dd0ee8874b743227a5
refs/heads/master
<repo_name>hercules261188/SparkSQL-with-Python<file_sep>/code/API/geo.py import math import os from pyspark.sql import SparkSession from pyspark.sql import Row from pyspark.sql.types import StringType from pyspark.sql import SQLContext class GeoTweets: def get_counter_tweets(self, orig_lon, orig_lat, dist): lon1 = orig_lon - dist / abs(math.cos(math.radians(orig_lat)) * 69); lon2 = orig_lon + dist / abs(math.cos(math.radians(orig_lat)) * 69); lat1 = orig_lat - (dist / 69); lat2 = orig_lat + (dist / 69); df_geo_sql = self.spark.sql(" select count(dss.distance) as counter " "from ( " "SELECT 3956 * 2 * ASIN(SQRT(POWER(SIN((" + str( orig_lat) + "- (lat)) * pi()/180 / 2),2) + COS(" + str( orig_lat) + "* pi()/180 ) * COS((lat) *pi()/180) * POWER(SIN((" + str( orig_lon) + "- long) *pi()/180 / 2), 2) )) as distance " "FROM tweets_geo " "WHERE long between " + str(lon1) + " and " + str(lon2) + " and lat between " + str( lat1) + " and " + str(lat2) + " " "ORDER BY Distance ) dss " " where dss.distance < " + str(dist) + " ") return df_geo_sql.first()['counter'] def __init__(self): self.spark = SparkSession.builder.appName('SparkSQL_API').getOrCreate() site_root = os.path.realpath(os.path.dirname(__file__)) dataset_csv_url = os.path.join(site_root, 'static/data', "tweets_geo.csv") self.df_geo = self.spark.read.format('csv').option("header", "true").load(dataset_csv_url) self.df_geo.createOrReplaceTempView('tweets_geo') <file_sep>/code/API/app.py import findspark findspark.init() from flask import Flask, Blueprint, jsonify, request from geo import GeoTweets app = Flask(__name__) global geo_tweets @app.route('/count_tweets/') def count_tweets(): orig_lon = float(request.args.get('lo')) orig_lat = float(request.args.get('la')) dist = float(int(request.args.get('ra')) * 0.621371) geo_tweets = GeoTweets() return jsonify(counter_tweets = geo_tweets.get_counter_tweets(orig_lon, orig_lat, dist)), 200 if __name__ == '__main__': app.run() <file_sep>/docs/Readme.md # SparkSQL with Python This repository has some examples of using Spark and SparkSQL with Python through PySpark ## Profeco We will work with the Profeco dataset, which you can download here: [Profeco](https://drive.google.com/uc?export=download&id=0B-4W2dww7ELNazFfOFVhNG5vckE) , is a daily historical record of more than 2,000 products, as of 2015, in various establishments in Mexico <a href="https://wittline.github.io/SparkSQL-with-Python/Profeco.html">Check the code here</a> * How many records are there? * How many categories are there? * How many trade chains are being monitored (and therefore reported in that database)? * What are the most monitored products in each state of the country? * What is the trade chain with the greatest variety of monitored products? ## Countries airports <a href="https://wittline.github.io/SparkSQL-with-Python/Airports.html">Check the code here</a> ## API to count the number of tweets in a radius of 1km I will separate in another file "tweets_geo.csv" all the different tweets with their geographic data information, this will help in the manipulation of this data in a query with sparkSQL <a href="https://wittline.github.io/SparkSQL-with-Python/Tweet_Count.html">Check the data preparation code here</a> The details of the code for the API REST is in the folder API in this repository ![alt text](https://wittline.github.io/SparkSQL-with-Python/images/api1.PNG) ![alt text](https://wittline.github.io/SparkSQL-with-Python/images/api2.PNG) ![alt text](https://wittline.github.io/SparkSQL-with-Python/images/api3.PNG) # Contributing and Feedback Any ideas or feedback about this repository?. Help me to improve it. # Authors - Created by <a href="https://www.linkedin.com/in/ramsescoraspe"><strong><NAME></strong></a> - Created on 2020 # License This project is licensed under the terms of the MIT license.
26e19b24ac91c14de20bce9cbc2bc4651a78a108
[ "Markdown", "Python" ]
3
Python
hercules261188/SparkSQL-with-Python
448aee9713fb018c729722f6da42ca2cfa65e3cd
b9394af8867695387e59fdf54428c24573bfae36
refs/heads/main
<repo_name>mortezasaki/PDF-To-CSV<file_sep>/README.md # PDF-To-CSV Convert pdf to csv <file_sep>/run.py #from tabula import read_pdf #df=read_pdf(r"/home/morteza/Downloads/melli.pdf",multiple_tables=True,encoding='utf-8', spreadsheet=True,pages='۱-130') #with open(r'/home/morteza//melli.csv','a') as f: # for i in range(0,len(df)): # df[i].to_csv(f,line_terminator=',', index=False, header=False, encoding='utf-8') f=open(r'/home/morteza//melli.csv','r') a=f.read() f.close() a=a.split(',,,') b='' c='' for i in range(0,len(a)): a[i]=a[i].replace('\n','') #for j in range(i,i+13): # c+=a[j]+',' #c=c.replace('\n','') #c=c[:-1] b+=a[i]+'\n' f=open(r'/home/morteza/melli2.csv','w') f.write(b) f.close()
d5b311433907d3a9f9534726de81dffbdf16a3d9
[ "Markdown", "Python" ]
2
Markdown
mortezasaki/PDF-To-CSV
df0909ff561099c76db140181339ddd2dfcd1005
e4abefdd0668a3ede2711bf18b9b317ed7b09af7
refs/heads/master
<file_sep>#!/usr/bin/make -f export DEBPYTHON_DEFAULT ?= $(shell sed -rne 's,^default-version = python(.*),\1,p' ../../debian/debian_defaults) export DEBPYTHON_SUPPORTED ?= $(shell sed -rne '/^supported-versions/{s/^supported-versions = (.*)/\1/g;s/python//gp}' ../../debian/debian_defaults) all: run check run: clean dpkg-buildpackage -b -us -uc clean-common: ./debian/rules clean <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/roscpp/share/roscpp/cmake/roscppConfig.cmake<file_sep># /usr/bin/bash cd catkin_tools_all pip install -e alabaster-0.7.12 pip install -e snowballstemmer-1.2.1 pip install -e futures-3.2.0 pip install -e Jinja2-2.10 # still missing the following package in following test #Jinja2-2.10 MarkupSafe-1.1.0 Pygments-2.3.0 Sphinx-1.8.2 babel-2.6.0 imagesize-1.1.0 packaging-18.0 pyparsing-2.3.0 sphinxcontrib-programoutput sphinxcontrib-websupport-1.1.0 typing-3.6.6 pip install -e Sphinx-1.3.6 pip install -e sphinxcontrib-programoutput-0.11 pip install -e sphinx_rtd_theme-0.4.2 pip install -e MarkupSafe-1.1.0 pip install -e trollius-trollius-2.2 pip install -e osrf_pycommon-0.1.6 pip install -e catkin_tools <file_sep># generated from rosbuild/env-hooks/10.rosbuild.sh.em # env variables in develspace export ROS_ROOT="/home/parallels/Desktop/compare2/kinetic/src/ros/rosbuild" <file_sep>roles ----- * :cpp:class:`Sphinx` * ref function without parens :cpp:func:`hello`. * ref function with parens :cpp:func:`hello()`. * :cpp:member:`Sphinx::version` * :cpp:var:`version` * :cpp:type:`List` * :cpp:enum:`MyEnum` <file_sep>#!/usr/bin/make -f # -*- makefile -*- .PHONY: override_dh_auto_clean override_dh_strip %: dh $@ --parallel override_dh_auto_clean: rm -f console_bridge-config.cmake rm -f console_bridge.pc dh_auto_clean -- override_dh_strip: dh_strip -a --dbg-package=libconsole-bridge0.2v5-dbg <file_sep>### repack the debian source https://www.cmiss.org/cmgui/wiki/BuildingUbuntuPackagesFromSource ### how to compile a steel banck common lisp https://www.reddit.com/r/Common_Lisp/comments/5j4q7i/how_to_build_sbcl_from_source/ (optional) ros distro database initilization ## rosdep init add some old version distro info to /etc/ros/rosdep/sources.list.d/20-default.list ## rosdep update update cache in /root/.ros/rosdep/sources.cache there is a database to maintain distro info here ex: kinetic -> whole stack software version is list under yaml https://raw.githubusercontent.com/ros/rosdistro/master/kinetic/distribution.yaml kinetic ## download source (any platform rosinstall_generator ros_comm --rosdistro kinetic --deps --wet-only --tar > kinetic-ros_comm-wet.rosinstall wstool init -j8 src kinetic-ros _comm-wet.rosinstall ## if you are in a virtual machine if you are in a virtual machine, you would like to have vboxtool , a gcc/gcc-g++/make is required yum install "kernel-devel-uname-r == $(uname -r)" # build essential centos which derived from redhat, can use lots RPM source from EPEL. yum -y install libtool ( will install autoconf,automake,m4,perl...etc... yum -y install gcc gcc-g++ make -- # apr compile ready -- # apr-util compile ready -- # cmake 3.5.1 compile ready -- # bzip2 compile ready -- # -- # # Download ## pip install -U rosdep rosinstall_generator wstool rosinstall # install pre-requisites if dont want to build the tarball yum install pip pip install empy pip install setuptools==40.5.0 pip install jinja2 pip install ipapython yum install zlib-devel yum install libyaml-devel yum install boost-devel yum install tinyxml yum install tinyxml-devel yum install gtest yum install libjpeg-turbo-devel yum install glib-devel yum install patch ## libool detail: to analysiz libtool dependencies Installing: libtool 2.4.2-22.el7_3 Installing for dependencies: autoconf 2.69-11.el7 automake 1.13.4-3.el7 m4 1.4.16-10.el7 perl-Data-Dumper 2.145-3.el7 perl-Test-Harness 3.28-3.el7 perl-Thread-Queue 3.02-2.el7 ## cmake detail: ./configure --prefix=/usr/ gmake make install ## gtest build: make install is not supported for gtest .. change cmakefile to generate libs cp so to /usr/lib/gtest cp h to /usr/include ## bzip2 build: sudo rm /usr/bin/bzip2 /usr/bin/bunzip2 /usr/bin/bzcat /usr/bin/bzip2recover make -f Makefile-libbz2_so *modify Makefile install path to /usr make make install (this will copy header to /usr/include and will be used by boost etc ## console_bridge compiled with gtest: yum -y install epel-release (optional) copy gtest src to /usr/src/gtest/src cmake -DCMAKE_INSTALL_PREFIX=/usr make -j32 && make install ## log4cxx-0.10.0 compiled: ./configure --prefix=/usr make -j32 && make install ## lz4-0.0.r131 compiled: cd ./lib && make -j32 cp liblz4.so /usr/lib cd .. make -j32 #make exec cp programs/lz4 /usr/bin cp ./lib/*.h /usr/include ## google-mock-1.7.0 complied: ./configure --prefix=/usr make install is not supported cp ./lib/.libs/libgmock.so /usr/lib cp ./lib/.llibs/libgmock_main.so /usr/lib ## tinyxml 2.6.2 compiled: change makefile the so is broken cannot be linked (TBD `${LIB}: ${OBJS} ${CXX} -o $@ ${LDFLAGS} ${OBJS}` make ## sbcl compiled: seems sbcl need itself to build yum install sbcl sh make.sh sh install.sh default installed to /usr/local/bin change location : by -> sh make.sh --prefix=/usr --fancy ## pkg-config compiled: step1: compile pkg-config/glib/ (require aclocal-1.15 yum install automake wont make in centos cause its version is 1.13.4 ) step:build pkg-config itself # Now python time ## empy python setup.py install ## defusedxml yum install python2-pip (8.1.2-6.el7 , pip install setuptools==40.5.0 yum install python-devel python setup.py install (there is a patch here ...need i patch it manually ? ## nose-1.3.7 python setup.py install ## paramiko-1.16.0 pip install ecdsa>=0.11 pip install pycrypto>=2.1,!=2.4 python setup.py install ## pillow 3.1.2 yum install libjpeg-turbo-devel yum install zlib ( zlib-1.2.7-17.e17 yum install zlib-devel ( 1.2.7-17.el7 python setup.py install ## pyyaml-3.11 python setup.py install # Now ready to using catkin tools.... pip install catkin-tools ...collecting catkin_tools-0.4.4.tar.gz ...collecting catkin_pkg-0.4.9.tar.gz ...collecting osrf-pycommon>0.1.1 -> osrf-pycommon-0.1.5.tar.gz ...collecting docutils-0.14-py2-none-any.whl ...collecting python_dateutil-2.7.5-py2.py3-none-any.whl ...collecting pyparsing-2.3.0-py2.py3-none-any.whl ...collecting trollius-2.2.tar.gz ...collecting six>=1.5 -> six-1.11.0-py2.py3-none-any.whl ...collecting futures-3.2.0-py2-none-any.whl but boost is requested ## compile boost-1.58 require bzip2.h ./bootstrap.sh ./b2 cp -r ./boost/ /usr/include cp -r ./stage/lib /usr/lib # ready to compile ROS catkin config -i install --install --merge-install -j12 catkin build I have done some port test on centos. the following work has been done 1, python packages are portable on most of the linux platform. 2, extract the source for a in $(ls *.tar.gz ); do tar xzvf $a; done for a in $(ls *.bz2 ); do tar xjf $a; done for a in $(ls *.xz ); do tar xJf $a; done gzip -d pkg-config_0.29.1-0ubuntu1.diff.gz patch -p1 -i pkg-config_0.29.1-0ubuntu1.diff 3, build the other binaries from source currently use from rpm source include(to be compile from source) if commit a big binary , we can use following command git filter-branch --index-filter "git rm -rf --ignore-unmatch toolchian/boost_1_58.tar.gz" HEAD rm -rf .git/refs/original/ && git reflog expire --all && git gc --aggressive --prune <file_sep>#! /usr/bin/bash MPFR=mpfr-2.4.2 GMP=gmp-4.3.2 MPC=mpc-1.0.3 wget ftp://gcc.gnu.org/pub/gcc/infrastructure/$MPFR.tar.bz2 || exit 1 tar xjf $MPFR.tar.bz2 || exit 1 ln -sf $MPFR mpfr || exit 1 wget ftp://gcc.gnu.org/pub/gcc/infrastructure/$GMP.tar.bz2 || exit 1 tar xjf $GMP.tar.bz2 || exit 1 ln -sf $GMP gmp || exit 1 wget ftp://gcc.gnu.org/pub/gcc/infrastructure/$MPC.tar.gz || exit 1 tar xzf $MPC.tar.gz || exit 1 ln -sf $MPC mpc || exit 1 rm $MPFR.tar.bz2 $GMP.tar.bz2 $MPC.tar.gz || exit 1 #if [ ! -f ./mpfr-2.4.2.tar.gz ]; then # wget https://mirrors.ustc.edu.cn/gnu/mpfr/mpfr-2.4.2.tar.gz #fi # # # #if [ ! -f ./mpc-1.1.0.tar.gz ]; then # wget https://mirrors.ustc.edu.cn/gnu/mpc/mpc-1.1.0.tar.gz #fi # if [ ! -f ./gcc-4.8.0.tar.gz ]; then wget https://mirrors.ustc.edu.cn/gnu/gcc/gcc-4.8.0/gcc-4.8.0.tar.gz -O gcc-4.8.0.tar.gz tar xzvf gcc-4.8.0.tar.gz fi <file_sep>#!/usr/bin/env python from distutils.version import StrictVersion import setuptools import sys # Setuptools 17.1 is required, and setup_requires cannot upgrade setuptools # in-place, nor trigger the use of a newer version. Abort cleanly up-front. setuptools_required = StrictVersion("17.1") setuptools_installed = StrictVersion(setuptools.__version__) if setuptools_installed < setuptools_required: sys.stderr.write( "mock requires setuptools>=17.1. Aborting installation\n") sys.exit(1) setuptools.setup( setup_requires=['pbr>=0.11'], pbr=True) <file_sep>#! /bin/sh /usr/share/dpatch/dpatch-run ## 100-bugfix-LOGCXX-284.dpatch by <<EMAIL>> ## ## All lines beginning with `## DP:' are a description of the patch. ## DP: Fixes build error on AIX with xlc_r @DPATCH@ diff -urNad log4cxx-0.10.0~/src/test/cpp/helpers/datetimedateformattestcase.cpp log4cxx-0.10.0/src/test/cpp/helpers/datetimedateformattestcase.cpp --- log4cxx-0.10.0~/src/test/cpp/helpers/datetimedateformattestcase.cpp 2008-03-31 15:33:09.000000000 -0700 +++ log4cxx-0.10.0/src/test/cpp/helpers/datetimedateformattestcase.cpp 2008-07-17 06:49:43.000000000 -0700 @@ -181,7 +181,7 @@ // output the using STL // std::basic_ostringstream<logchar> buffer; -#if defined(_USEFAC) +#if defined(_MSC_VER) && _MSC_VER < 1300 _USEFAC(locale, std::time_put<logchar>) .put(buffer, buffer, &date, fmt.c_str(), fmt.c_str() + fmt.length()); #else <file_sep>#! /bin/sh # Pre-install script for ‘python3-coverage’. # # Manpage: ‘dh_installdeb(1)’ set -e # Summary of ways this script can be called: # * <new-preinst> install # * <new-preinst> install <old-version> # * <new-preinst> upgrade <old-version> # * <old-preinst> abort-upgrade <new-version> # For details, see the Debian Policy §6.5 in the ‘debian-policy’ package # or on the web at <URL:http://www.debian.org/doc/debian-policy/>. action="$1" case "$action" in upgrade) htmlfiles_dir="/usr/lib/python3/dist-packages/coverage/htmlfiles" if [ -d "$htmlfiles_dir" ] && [ ! -L "$htmlfiles_dir" ] ; then # The ‘htmlfiles’ location should be platform-independent. # The new package will replace the directory with a symlink. rm -rf "$htmlfiles_dir" fi ;; install|abort-upgrade) ;; *) printf "preinst called with unknown action ‘%s’\n" "$action" >&2 exit 1 ;; esac #DEBHELPER# <file_sep>#!/usr/bin/make -f INSTALL ?= install PREFIX ?= /usr/local MANPAGES ?= dh_python2.1 pycompile.1 pyclean.1 clean: make -C tests clean make -C pydist clean find . -name '*.py[co]' -delete rm -f .coverage install-dev: $(INSTALL) -m 755 -d $(DESTDIR)$(PREFIX)/bin \ $(DESTDIR)$(PREFIX)/share/python/runtime.d \ $(DESTDIR)$(PREFIX)/share/debhelper/autoscripts/ \ $(DESTDIR)$(PREFIX)/share/perl5/Debian/Debhelper/Sequence/ $(INSTALL) -m 755 runtime.d/* $(DESTDIR)$(PREFIX)/share/python/runtime.d/ $(INSTALL) -m 644 autoscripts/* $(DESTDIR)$(PREFIX)/share/debhelper/autoscripts/ $(INSTALL) -m 755 dh_python2 $(DESTDIR)$(PREFIX)/share/python/ $(INSTALL) -m 755 dh_python2.py $(DESTDIR)$(PREFIX)/bin/dh_python2 $(INSTALL) -m 644 python2.pm $(DESTDIR)$(PREFIX)/share/perl5/Debian/Debhelper/Sequence/ install-runtime: $(INSTALL) -m 755 -d $(DESTDIR)$(PREFIX)/share/python/debpython $(DESTDIR)$(PREFIX)/bin $(INSTALL) -m 644 debpython/*.py $(DESTDIR)$(PREFIX)/share/python/debpython/ $(INSTALL) -m 755 pycompile $(DESTDIR)$(PREFIX)/bin/ $(INSTALL) -m 755 pyclean $(DESTDIR)$(PREFIX)/bin/ install: install-dev install-runtime dist_fallback: make -C pydist $@ check_versions: @set -e;\ DEFAULT=`sed -rn 's,^DEFAULT = \(([0-9]+)\, ([0-9]+)\),\1.\2,p' debpython/version.py`;\ SUPPORTED=`sed -rn 's,^SUPPORTED = \[\(([0-9]+)\, ([0-9]+)\)\, \(([0-9]+)\, ([0-9]+)\)\],\1.\2 \3.\4,p' debpython/version.py`;\ DEB_DEFAULT=`sed -rn 's,^default-version = python([0-9.]*),\1,p' debian/debian_defaults`;\ DEB_SUPPORTED=`sed -rn 's|^supported-versions = (.*)|\1|p' debian/debian_defaults | sed 's/python//g;s/,//g'`;\ [ "$$DEFAULT" = "$$DEB_DEFAULT" ] || \ (echo "Please update DEFAULT in debpython/version.py ($$DEFAULT vs. $$DEB_DEFAULT)" >/dev/stderr; false);\ [ "$$SUPPORTED" = "$$DEB_SUPPORTED" ] || \ (echo "Please update SUPPORTED in debpython/version.py ($$SUPPORTED vs. $$DEB_SUPPORTED)" >/dev/stderr; false) pdebuild: pdebuild --debbuildopts -I # TESTS nose: nosetests --with-doctest --with-coverage tests: nose make -C tests test%: make -C tests $@ .PHONY: clean tests test% check_versions <file_sep>#!/usr/bin/make -f buildvers := $(shell pyversions -sv) build3vers := $(shell py3versions -sv) %: dh $@ --with python2, --with python3, --with quilt override_dh_auto_build: override_dh_auto_install: # Move generated _yaml.c aside so we can regenerate it during build mv $(CURDIR)/ext/_yaml.c $(CURDIR)/upstream.yaml.c dh_install -ppython-yaml set -e && for i in $(buildvers); do \ python$$i ./setup.py install --install-layout=deb --root $(CURDIR)/debian/python-yaml; \ done dh_install -ppython-yaml-dbg set -e && for i in $(buildvers); do \ python$$i-dbg ./setup.py install --install-layout=deb --root $(CURDIR)/debian/python-yaml-dbg; \ done dh_install -ppython3-yaml set -e && for i in $(build3vers); do \ python$$i ./setup.py install --install-layout=deb --root $(CURDIR)/debian/python3-yaml; \ done dh_install -ppython3-yaml-dbg set -e && for i in $(build3vers); do \ python$$i-dbg ./setup.py install --install-layout=deb --root $(CURDIR)/debian/python3-yaml-dbg; \ done ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS))) set -e && for i in $(buildvers); do \ echo "-- running tests for "$$i" plain --" ; \ python$$i -c "import sys ; sys.path.insert(0, 'debian/python-yaml/usr/lib/python$$i/dist-packages/'); \ sys.path.insert(0, 'tests/lib'); import test_all; test_all.main([])";\ done set -e && for i in $(buildvers); do \ echo "-- running tests for "$$i" debug --" ; \ python$$i-dbg -c "import sys ; sys.path.insert(0, 'debian/python-yaml-dbg/usr/lib/python$$i/dist-packages/'); \ sys.path.insert(0, 'tests/lib'); import test_all; test_all.main([])";\ done set -e && for i in $(build3vers); do \ echo "-- running tests for "$$i" plain --" ; \ python$$i -c "import sys ; sys.path.insert(0, 'debian/python3-yaml/usr/lib/python3/dist-packages/'); \ sys.path.insert(0, 'tests/lib3'); import test_all; test_all.main([])";\ done set -e && for i in $(build3vers); do \ echo "-- running tests for "$$i" debug --" ; \ python$$i -c "import sys ; sys.path.insert(0, 'debian/python3-yaml-dbg/usr/lib/python3/dist-packages/'); \ sys.path.insert(0, 'tests/lib3'); import test_all; test_all.main([])";\ done endif # Put upstream _yaml.c back where we found it mv $(CURDIR)/upstream.yaml.c $(CURDIR)/ext/_yaml.c override_dh_installdocs: cp $(CURDIR)/CHANGES $(CURDIR)/changelog dh_installdocs rm $(CURDIR)/changelog override_dh_installdeb: rm -rf $(CURDIR)/debian/python-yaml-dbg/usr/share/doc/python-yaml-dbg ln -s python-yaml debian/python-yaml-dbg/usr/share/doc/python-yaml-dbg rm -rf $(CURDIR)/debian/python3-yaml-dbg/usr/lib/python3/dist-packages/yaml rm -rf $(CURDIR)/debian/python3-yaml-dbg/usr/share/doc/python3-yaml-dbg ln -s python3-yaml debian/python3-yaml-dbg/usr/share/doc/python3-yaml-dbg dh_installdeb override_dh_clean: dh_clean rm -rf $(CURDIR)/build <file_sep># generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in set(rosgraph_msgs_MSG_INCLUDE_DIRS "/home/parallels/Desktop/compare2/kinetic/src/ros_comm_msgs/rosgraph_msgs/msg") set(rosgraph_msgs_MSG_DEPENDENCIES std_msgs) <file_sep># Append cmake modules from source directory to the cmake module path list(APPEND CMAKE_MODULE_PATH "/home/parallels/Desktop/compare2/kinetic/src/cmake_modules/cmake/Modules") <file_sep>#!/usr/bin/python ''' Check if debian/versions is sane and generate substvars for numpy:Provides. ''' import os def main(): os.chdir(os.path.join(os.path.dirname(__file__), '..')) data = {} file = open('numpy/core/setup_common.py', 'r') try: exec(file.read(), data) finally: file.close() file = open('debian/versions', 'r') try: for line in file: line = line.strip() if not line or line.startswith('#'): continue key, value = line.split(None, 1) data[key] = value finally: file.close() assert data['abi'] == str(data['C_ABI_VERSION'] - 0x1000000), 'Is debian/versions up-to-date?' assert data['api'] == str(data['C_API_VERSION']), 'Is debian/versions up-to-date?' print 'numpy:Provides=python-numpy-abi%s, python-numpy-api%s' % (data['abi'], data['api']) if __name__ == '__main__': main() <file_sep>#!/usr/bin/make -f include /usr/share/dpkg/default.mk CXXFLAGS += -DTIXML_USE_STL OBJ_FILES := tinyxml.o tinyxmlparser.o tinyxmlerror.o %: dh $@ --parallel override_dh_auto_build: dh_auto_build -- CXXFLAGS="$(CXXFLAGS) $(CPPFLAGS)" LDFLAGS="$(LDFLAGS)" ar rc libtinyxml.a $(OBJ_FILES) rm *.o xmltest dh_auto_build -- CXXFLAGS="$(CXXFLAGS) $(CPPFLAGS) -fPIC" LDFLAGS="$(LDFLAGS)" g++ -shared -Wl,-soname,libtinyxml.so.$(DEB_VERSION_UPSTREAM) \ -o libtinyxml.so.$(DEB_VERSION_UPSTREAM) $(LDFLAGS) \ $(OBJ_FILES) override_dh_auto_install: mkdir -p debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig mkdir -p debian/tmp/usr/include install -m 644 -p libtinyxml.so.$(DEB_VERSION_UPSTREAM) debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/ ln -f -s libtinyxml.so.$(DEB_VERSION_UPSTREAM) debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/libtinyxml.so install -m 644 -p libtinyxml.a debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/ install -m 644 -p tinyxml.h debian/tmp/usr/include/ sed -e 's/\$${DEB_HOST_MULTIARCH}/$(DEB_HOST_MULTIARCH)/' -e 's/\$${DEB_VERSION_UPSTREAM}/$(DEB_VERSION_UPSTREAM)/' \ debian/tinyxml.pc.in > debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/tinyxml.pc override_dh_auto_test: mkdir xmltestdir cp -a utf8test*.xml xmltestdir cd xmltestdir && ../xmltest rm -rf xmltestdir override_dh_auto_clean: dh_auto_clean rm -f libtinyxml.so* libtinyxml.a rm -rf xmltestdir override_dh_strip: dh_strip --dbg-package=libtinyxml$(DEB_VERSION_UPSTREAM)v5-dbg override_dh_install: dh_install --fail-missing <file_sep>#!/bin/sh set -efu PYS=$(pyversions -r 2>/dev/null)" "$(py3versions -r 2>/dev/null) cd "$ADTTMP" cat << EOF > setup.py def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('npufunc_directory', parent_package, top_path) config.add_extension('npufunc', ['ufunc.c']) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration) EOF cat << EOF > ufunc.c #include "Python.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" static PyMethodDef LogitMethods[] = { {NULL, NULL, 0, NULL} }; static void double_logit(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { } PyUFuncGenericFunction funcs[1] = {&double_logit}; static char types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *data[1] = {NULL}; static void setupmodule(PyObject * m) { PyObject * logit, * d; import_array(); import_umath(); logit = PyUFunc_FromFuncAndData(funcs, data, types, 4, 3, 1, PyUFunc_Zero, "logit", "logit_docstring", 0); d = PyModule_GetDict(m); PyDict_SetItemString(d, "logit", logit); Py_DECREF(logit); } #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "npufunc", NULL, -1, LogitMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_npufunc(void) { PyObject * m = PyModule_Create(&moduledef); if (m == NULL) { return; } setupmodule(m); return m; } #else PyMODINIT_FUNC initnpufunc(void) { PyObject *m = Py_InitModule("npufunc", LogitMethods); if (m == NULL) { return; } setupmodule(m); } #endif EOF for py in $PYS; do echo "=== $py ===" $py setup.py build 2>&1 $py-dbg setup.py build 2>&1 $py setup.py install --prefix $PWD/inst 2>&1 $py-dbg setup.py install --prefix $PWD/inst 2>&1 export PYTHONPATH=$PWD/inst/lib/$py/site-packages/npufunc_directory $py -c "import npufunc; print(npufunc.logit(1,2,3))" 2>&1 $py-dbg -c "import npufunc; print(npufunc.logit(1,2,3))" 2>&1 done <file_sep>#! /bin/sh /usr/share/dpatch/dpatch-run ## 80-bugfix-LOGCXX-298.dpatch by <<EMAIL>> ## ## All lines beginning with `## DP:' are a description of the patch. ## DP: Bugfix for build errors with smtp @DPATCH@ diff -urNad log4cxx-0.10.0~/src/main/cpp/smtpappender.cpp log4cxx-0.10.0/src/main/cpp/smtpappender.cpp --- log4cxx-0.10.0~/src/main/cpp/smtpappender.cpp 2008-03-31 15:34:09.000000000 -0700 +++ log4cxx-0.10.0/src/main/cpp/smtpappender.cpp 2008-07-17 06:39:34.000000000 -0700 @@ -496,7 +496,7 @@ activate &= asciiCheck(bcc, LOG4CXX_STR("bcc")); activate &= asciiCheck(from, LOG4CXX_STR("from")); -#if !LOG4CXX_HAS_LIBESMTP +#if !LOG4CXX_HAVE_LIBESMTP LogLog::error(LOG4CXX_STR("log4cxx built without SMTP support.")); activate = false; #endif @@ -598,7 +598,7 @@ */ void SMTPAppender::sendBuffer(Pool& p) { -#if LOG4CXX_HAS_LIBESMTP +#if LOG4CXX_HAVE_LIBESMTP // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. try <file_sep>#!/bin/sh # autopkgtest check: Build and run a program against console-bridge, # to verify that the headers and pkg-config file are installed # correctly # (C) 2013 <NAME> # Author: <NAME> <<EMAIL>> set -e WORKDIR=$(mktemp -d) trap "rm -rf $WORKDIR" 0 INT QUIT ABRT PIPE TERM cd $WORKDIR cat <<EOF > consolebridgetest.cpp #include <console_bridge/console.h> int main() { logInform ("test"); return 0; } EOF g++ -o consolebridgetest consolebridgetest.cpp \ `pkg-config --cflags --libs console_bridge` echo "build: OK" [ -x consolebridgetest ] ./consolebridgetest echo "run: OK" <file_sep># /usr/bin/bash cd $(dirname "$0") source env.sh cd $DEP/utils/google-mock-1.7.0-18092013 nstall is not supported cp ./lib/.libs/libgmock.so /usr/lib cp ./lib/.libs/libgmock_main.so /usr/lib <file_sep>#!/usr/bin/make -f # -*- makefile -*- %: dh $@ --parallel --with autotools-dev override_dh_auto_configure: dh_auto_configure --buildsystem=cmake -- -Dgtest_build_tests=ON override_dh_clean: dh_clean rm -f test/*.pyc <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/std_msgs/include/std_msgs/Empty.h<file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/catkin/setup.sh<file_sep># generated from rosconsole/env-hooks/10.rosconsole.sh.develspace.em export ROSCONSOLE_CONFIG_FILE="/home/parallels/Desktop/compare2/kinetic/src/ros_comm/rosconsole/config/rosconsole.config" <file_sep>#!/usr/bin/make -f #export DH_VERBOSE=1 # for ppc64 on Ubuntu export DEB_GCC_NO_O3=1 SHELL := /bin/bash BUILDDIR := debian/build DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH) DEB_HOST_ARCH_OS ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_OS) DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH) # configure takes ages to test for all db versions. Provide the installed # version to speed things up. DB_VERSION = $(shell dpkg-query -W -f '$${Version}' libdb-dev | \ perl -pe 's/^(?:[^:]*:)?(\d+)[.](\d+)[.].*/$$1$$2/') # The 'build' target needs special handling because there there is a directory # named 'build'. .PHONY: build %: dh $@ -B$(BUILDDIR) --parallel --with autotools_dev # # configure # CONFFLAGS := LTFLAGS=--no-silent \ --host=$(DEB_HOST_GNU_TYPE) \ --build=$(DEB_BUILD_GNU_TYPE) \ --with-apr=/usr/bin/apr-1-config \ --enable-layout=Debian \ --includedir=/usr/include/apr-1.0 \ --libdir=/usr/lib/$(DEB_HOST_MULTIARCH) \ --with-ldap=yes \ --with-dbm=db$(DB_VERSION) \ --with-sqlite3 \ --with-pgsql=/usr \ --without-gdbm \ --without-sqlite2 \ --with-berkeley-db \ --with-mysql=/usr \ --with-odbc=/usr \ --with-openssl=/usr \ --with-crypto \ ac_cv_prog_AWK=mawk # files that are modified by buildconf and need to be restored during clean SAVE_FILES := configure build/apr_common.m4 ifeq ($(DEB_HOST_ARCH),i386) CONFFLAGS += apr_lock_method=USE_PROC_PTHREAD_SERIALIZE else CONFFLAGS += ac_cv_func_pthread_mutexattr_setpshared=no \ ac_cv_func_sem_open=no endif override_dh_auto_configure: mkdir -p $(BUILDDIR)/docs for f in $(SAVE_FILES) ; do [ -e $$f.dr-orig ] || cp -p $$f $$f.dr-orig ; done ./buildconf --with-apr=$(shell apr-1-config --srcdir) cd $(BUILDDIR) && $(CURDIR)/configure $(CONFFLAGS) # # build # # get cflags from apr-config but remove -O2 export DEB_CFLAGS_MAINT_PREPEND := $(shell apr-1-config --cflags |perl -p -e 's!-O.( |$$)!!') export DEB_LDFLAGS_MAINT_PREPEND := $(shell apr-1-config --ldflags) ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) MAKEARGS := -j$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) endif override_dh_auto_build: dh_auto_build --parallel -B$(BUILDDIR) $(MAKE) $(MAKEARGS) -C $(BUILDDIR) dox # # test # ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS))) override_dh_auto_test: $(MAKE) -C $(BUILDDIR)/test $(MAKEARGS) all $(MAKE) -C $(BUILDDIR)/test -j1 check else override_dh_auto_test: endif # # install # override_dh_auto_install: dh_auto_install --destdir=debian/tmp perl -p -i -e "s,^dependency_libs=.*,dependency_libs=''," debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/libaprutil-1.la override_dh_strip: dh_strip --dbg-package=libaprutil1-dbg # The -X option causes the internal-use-only driver libs to be ignored override_dh_makeshlibs: dh_makeshlibs -Xapr-util-1 -- -Idebian/symbols.$(DEB_HOST_ARCH_OS) override_dh_auto_clean: dh_auto_clean rm -rf $(BUILDDIR) for f in $(SAVE_FILES) ; do [ ! -e $$f.dr-orig ] || mv $$f.dr-orig $$f ; done <file_sep>#! /usr/bin/bash source ./env.sh cd $DEP/basic/autoconf-2.65/ ./configure --prefix=/usr make make install <file_sep>========== pycompile ========== -------------------------------- byte compile Python source files -------------------------------- :Manual section: 1 :Author: <NAME>, 2012-2013 SYNOPSIS ======== pycompile [-V [X.Y][-][A.B]] DIR_OR_FILE [-X REGEXPR] pycompile -p PACKAGE DESCRIPTION =========== Wrapper around Python standard library's py_compile module to byte-compile Python files. OPTIONS ======= --version show program's version number and exit -h, --help show this help message and exit -f, --force force rebuild of byte-code files even if timestamps are up-to-date -O byte-compile to .pyo files -q, --quiet be quiet -v, --verbose turn verbose mode on -p PACKAGE, --package=PACKAGE specify Debian package name whose files should be bytecompiled (combining with DIR_OR_FILE will additionally limit list of files) -V VRANGE force private modules to be bytecompiled with Python version from given range, regardless of the default Python version in the system. If there are no other options, bytecompile all public modules for installed Python versions that match given range. VERSION_RANGE examples: * ``2.5`` version 2.5 only * ``2.5-`` version 2.5 or newer * ``2.5-2.7`` version 2.5 or 2.6 * ``-3.0`` all supported 2.X versions -X REGEXPR, --exclude=REGEXPR exclude items that match given REGEXPR. You may use this option multiple times to build up a list of things to exclude <file_sep>#! /usr/bin/bash source ./env.sh cd $DEP/basic/pkg-config-0.29.1/ ./configure --prefix=/usr make make install <file_sep>#ifndef testXMLParser_h #define testXMLParser_h #define SOURCE_DIR "/home/arthur/ros_varient/sim-install/cmake-3.5.1/Tests/CMakeLib" #endif <file_sep>Index: b/setup.py =================================================================== --- a/setup.py +++ b/setup.py @@ -15,7 +15,13 @@ import struct import sys from distutils.command.build_ext import build_ext -from distutils import sysconfig +try: + import sysconfig + host_platform = sysconfig.get_platform() +except: + from distutils import sysconfig + host_platform = sys.platform + from setuptools import Extension, setup, find_packages # monkey patch import hook. Even though flake8 says it's not used, it is. @@ -147,6 +153,38 @@ class pil_build_ext(build_ext): if getattr(self, 'enable_%s' % x): self.feature.required.add(x) + def add_gcc_paths(self): + gcc = sysconfig.get_config_var('CC') + tmpfile = os.path.join(self.build_temp, 'gccpaths') + if not os.path.exists(self.build_temp): + os.makedirs(self.build_temp) + ret = os.system('%s -E -v - </dev/null 2>%s 1>/dev/null' % (gcc, tmpfile)) + is_gcc = False + in_incdirs = False + inc_dirs = [] + lib_dirs = [] + try: + if ret >> 8 == 0: + with open(tmpfile) as fp: + for line in fp.readlines(): + if line.startswith("gcc version"): + is_gcc = True + elif line.startswith("#include <...>"): + in_incdirs = True + elif line.startswith("End of search list"): + in_incdirs = False + elif is_gcc and line.startswith("LIBRARY_PATH"): + for d in line.strip().split("=")[1].split(":"): + d = os.path.normpath(d) + if '/gcc/' not in d: + _add_directory(self.compiler.library_dirs, + d) + elif is_gcc and in_incdirs and '/gcc/' not in line: + _add_directory(self.compiler.include_dirs, + line.strip()) + finally: + os.unlink(tmpfile) + def build_extensions(self): global TCL_ROOT @@ -195,12 +233,12 @@ class pil_build_ext(build_ext): # # add platform directories - if sys.platform == "cygwin": + if host_platform == "cygwin": # pythonX.Y.dll.a is in the /usr/lib/pythonX.Y/config directory _add_directory(library_dirs, os.path.join( "/usr/lib", "python%s" % sys.version[:3], "config")) - elif sys.platform == "darwin": + elif host_platform == "darwin": # attempt to make sure we pick freetype2 over other versions _add_directory(include_dirs, "/sw/include/freetype2") _add_directory(include_dirs, "/sw/lib/freetype2/include") @@ -240,21 +278,21 @@ class pil_build_ext(build_ext): _add_directory(library_dirs, "/usr/X11/lib") _add_directory(include_dirs, "/usr/X11/include") - elif sys.platform.startswith("linux"): + elif host_platform.startswith("linux"): self.add_multiarch_paths() - elif sys.platform.startswith("gnu"): + elif host_platform.startswith("gnu"): self.add_multiarch_paths() - elif sys.platform.startswith("freebsd"): + elif host_platform.startswith("freebsd"): _add_directory(library_dirs, "/usr/local/lib") _add_directory(include_dirs, "/usr/local/include") - elif sys.platform.startswith("netbsd"): + elif host_platform.startswith("netbsd"): _add_directory(library_dirs, "/usr/pkg/lib") _add_directory(include_dirs, "/usr/pkg/include") - elif sys.platform.startswith("sunos5"): + elif host_platform.startswith("sunos5"): _add_directory(library_dirs, "/opt/local/lib") _add_directory(include_dirs, "/opt/local/include") @@ -306,7 +344,7 @@ class pil_build_ext(build_ext): # on Windows, look for the OpenJPEG libraries in the location that # the official installer puts them - if sys.platform == "win32": + if host_platform == "win32": program_files = os.environ.get('ProgramFiles', '') best_version = (0, 0) best_path = None @@ -340,7 +378,7 @@ class pil_build_ext(build_ext): if _find_include_file(self, "zlib.h"): if _find_library_file(self, "z"): feature.zlib = "z" - elif (sys.platform == "win32" and + elif (host_platform == "win32" and _find_library_file(self, "zlib")): feature.zlib = "zlib" # alternative name @@ -349,7 +387,7 @@ class pil_build_ext(build_ext): if _find_library_file(self, "jpeg"): feature.jpeg = "jpeg" elif ( - sys.platform == "win32" and + host_platform == "win32" and _find_library_file(self, "libjpeg")): feature.jpeg = "libjpeg" # alternative name @@ -386,9 +424,9 @@ class pil_build_ext(build_ext): if feature.want('tiff'): if _find_library_file(self, "tiff"): feature.tiff = "tiff" - if sys.platform == "win32" and _find_library_file(self, "libtiff"): + if host_platform == "win32" and _find_library_file(self, "libtiff"): feature.tiff = "libtiff" - if (sys.platform == "darwin" and + if (host_platform == "darwin" and _find_library_file(self, "libtiff")): feature.tiff = "libtiff" @@ -479,7 +517,7 @@ class pil_build_ext(build_ext): if feature.jpeg2000: libs.append(feature.jpeg2000) defs.append(("HAVE_OPENJPEG", None)) - if sys.platform == "win32": + if host_platform == "win32": defs.append(("OPJ_STATIC", None)) if feature.zlib: libs.append(feature.zlib) @@ -487,7 +525,7 @@ class pil_build_ext(build_ext): if feature.tiff: libs.append(feature.tiff) defs.append(("HAVE_LIBTIFF", None)) - if sys.platform == "win32": + if host_platform == "win32": libs.extend(["kernel32", "user32", "gdi32"]) if struct.unpack("h", "\0\1".encode('ascii'))[0] == 1: defs.append(("WORDS_BIGENDIAN", None)) @@ -504,7 +542,7 @@ class pil_build_ext(build_ext): if os.path.isfile("_imagingcms.c") and feature.lcms: extra = [] - if sys.platform == "win32": + if host_platform == "win32": extra.extend(["user32", "gdi32"]) exts.append(Extension( "PIL._imagingcms", @@ -524,7 +562,7 @@ class pil_build_ext(build_ext): "PIL._webp", ["_webp.c"], libraries=libs, define_macros=defs)) if feature.tcl and feature.tk: - if sys.platform == "darwin": + if host_platform == "darwin": # locate Tcl/Tk frameworks frameworks = [] framework_roots = [ @@ -578,7 +616,7 @@ class pil_build_ext(build_ext): print("-" * 68) print("version Pillow %s" % PILLOW_VERSION) v = sys.version.split("[") - print("platform %s %s" % (sys.platform, v[0].strip())) + print("platform %s %s" % (host_platform, v[0].strip())) for v in v[1:]: print(" [%s" % v.strip()) print("-" * 68) <file_sep>#! /bin/bash # debian/repack # Re-build the pristine upstream source to serve as the Debian upstream source. set -o errexit set -o errtrace set -o nounset function usage() { progname="$(basename "$0")" printf "$progname --upstream-version VERSION FILENAME\n" } if [ $# -ne 3 ] ; then usage exit 1 fi upstream_version="$2" downloaded_file="$3" working_dir="$(mktemp -d -t)" function cleanup_exit() { exit_status=$? trap - ERR EXIT SIGTERM SIGHUP SIGINT SIGQUIT rm -rf "${working_dir}" exit $exit_status } trap "cleanup_exit" ERR EXIT SIGTERM SIGHUP SIGINT SIGQUIT package_name=$(dpkg-parsechangelog | sed -n -e 's/^Source: //p') release_version=$(dpkg-parsechangelog | sed -n -e 's/^Version: //p') upstream_version=$(printf "${release_version}" \ | sed -e 's/^[[:digit:]]\+://' -e 's/[-][^-]\+$//') upstream_dirname="${package_name}-${upstream_version}.orig" target_filename="${package_name}_${upstream_version}.orig.tar.gz" target_working_file="${working_dir}/${target_filename}" target_file="$(dirname "${downloaded_file}")/${target_filename}" repack_dir="${working_dir}/${upstream_dirname}" printf "Unpacking pristine upstream source ‘${downloaded_file}’:\n" tar -xzf "${downloaded_file}" --directory "${working_dir}" upstream_source_dirname=$(ls -1 "${working_dir}") upstream_source_dir="${working_dir}/${upstream_source_dirname}" printf "Repackaging upstream source from ‘${upstream_source_dir}’ to ‘${repack_dir}’:\n" mv "${upstream_source_dir}" "${repack_dir}" printf "Removing non-DFSG-free files:\n" nonfree_files=( coverage/htmlfiles/jquery.min.js coverage/htmlfiles/jquery.tablesorter.min.js tests/farm/html/src/htmlcov/jquery-1.4.3.min.js tests/farm/html/src/htmlcov/jquery.tablesorter.min.js tests/qunit/jquery.tmpl.min.js ) for f in "${nonfree_files[@]}" ; do rm -v "${repack_dir}/$f" done printf "Rebuilding DFSG-free upstream source tarball:\n" GZIP="--best" tar --directory "${working_dir}" -czf "${target_working_file}" "${upstream_dirname}" printf "Moving completed upstream tarball to ‘${target_file}’:\n" rm -v "${downloaded_file}" mv "${target_working_file}" "${target_file}" printf "Done.\n" # Local variables: # coding: utf-8 # mode: sh # End: # vim: fileencoding=utf-8 filetype=sh : <file_sep>#! /usr/bin/bash cd "$(dirname "$0")" ./autoconf_build.sh ./automake_build.sh ./libtool_build.sh ./pkg_config_build.sh ./cmake_build.sh # sbcl need zlib.sh ./zlib_build.sh #./sbcl_bootstrap.sh <file_sep>#!/bin/sh set -efu PYS=$(pyversions -r 2>/dev/null) cd "$ADTTMP" for py in $PYS; do # check distutils copes with multi arch $py -c 'from numpy.distutils.system_info import get_info; get_info("fftw3", 2)' done <file_sep>#! /usr/bin/bash cd "$(dirname "$0")" pwd source env.sh echo $DEP cd $DEP/python-pkg/ pkg_list=$(ls) echo $pkg_list for pkg in $pkg_list do cd $pkg python setup.py install cd .. done <file_sep>0.1.6 (2018-11-15 12:45:00 -0800) --------------------------------- - Changed package.xml to use python2 or python3 dependencies as appropriate. `#50 <https://github.com/osrf/osrf_pycommon/pull/50>`_ 0.1.5 (2018-06-19 21:00:00 -0800) --------------------------------- - Fixed a try-catch statement to adapt to changes in asyncio's raise behavior in `asyncio.get_event_loop()`. - Small changes, mostly related to distribution. 0.1.4 (2017-12-08 16:00:00 -0800) --------------------------------- - Only small test/linter fixes and documentation typos removed. 0.1.3 (2017-03-28 19:30:00 -0800) --------------------------------- - Fix to support optional arguments in verb pattern `#24 <https://github.com/osrf/osrf_pycommon/pull/24>`_ 0.1.2 (2016-03-28 19:30:00 -0800) --------------------------------- - Started keeping a changelog. - Changed ``process_utils`` module so that it will use Trollius even on Python >= 3.4 if ``trollius`` has previously been imported. <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/rosbuild/etc/catkin/profile.d/10.rosbuild.sh<file_sep>export PYTHONIOENCODING='utf-8' python -c "import yaml; print yaml.load('\N{PILE OF POO}')" python -c "import yaml; print yaml.dump('\N{PILE OF POO}', allow_unicode=True)" <file_sep>#!/bin/sh # testscript to run liblog4cxx unit tests. # Part of the Debian package for liblog4cxx set -e WORKDIR=$(mktemp -d) trap "rm -rf $WORKDIR" 0 INT QUIT ABRT PIPE TERM # Copy the source tree to $ADTTMP before perparing it for the tests cp -r . $WORKDIR ; cd $WORKDIR # Patching the automake file to use the shared library instead of static linking. patch -p1 <debian/tests/src-test-cpp-Makefile-am.patch # run configure to prepare for building the tests. # redirect, as debci seems to interpretate everything to stderr as failure... # This is #809661 ./autogen.sh 2>&1 ./configure 2>&1 # run the checks, again #809661 make check 2>&1 || (echo "MAKE CHECK FAILED" 1>&2; exit 1) # debugging -- drop all the output into the ADT_ARTIFACTS. # (lines kept to offload brain-mermoy :)) #rm -rf $ADT_ARTIFACTS/dir #mkdir -p $ADT_ARTIFACTS/dir #cp -r . $ADT_ARTIFACTS/dir <file_sep>#! /user/bin/bash source ./env.sh cd $DEP/basic/libtool-2.4.6 ./configure --prefix=/usr make -j32 make install <file_sep>export PYTHONIOENCODING='utf-8' python3 -c "import yaml; print(yaml.load('\N{PILE OF POO}'))" python3 -c "import yaml; print(yaml.dump('\N{PILE OF POO}', allow_unicode=True))" <file_sep>#!/usr/bin/env bash if [ "$TRAVIS_OS_NAME" == "linux" ]; then sudo apt-get install enchant -y elif [ "$TRAVIS_OS_NAME" == "osx" ]; then if [ "$PYTHON" == "/usr/local/bin/python3" ]; then # Brewed Python 3. brew upgrade python elif [ "$PYTHON" == "/usr/local/bin/python2" ]; then # Brewed Python 2. brew install python@2 fi $PYTHON -m pip install virtualenv $PYTHON -m virtualenv -p $PYTHON venv brew install enchant source venv/bin/activate fi <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.5 # The generator used is: set(CMAKE_DEPENDS_GENERATOR "Unix Makefiles") # The top level Makefile was generated from the following files: set(CMAKE_MAKEFILE_DEPENDS "CMakeCache.txt" "CMakeFiles/3.5.1/CMakeCCompiler.cmake" "CMakeFiles/3.5.1/CMakeCXXCompiler.cmake" "CMakeFiles/3.5.1/CMakeSystem.cmake" "CMakeFiles/feature_tests.c" "CMakeFiles/feature_tests.cxx" "CMakeLists.txt" "cmake/internal_utils.cmake" "/usr/share/cmake-3.5/Modules/CMakeCCompiler.cmake.in" "/usr/share/cmake-3.5/Modules/CMakeCCompilerABI.c" "/usr/share/cmake-3.5/Modules/CMakeCInformation.cmake" "/usr/share/cmake-3.5/Modules/CMakeCXXCompiler.cmake.in" "/usr/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp" "/usr/share/cmake-3.5/Modules/CMakeCXXInformation.cmake" "/usr/share/cmake-3.5/Modules/CMakeCommonLanguageInclude.cmake" "/usr/share/cmake-3.5/Modules/CMakeCompilerIdDetection.cmake" "/usr/share/cmake-3.5/Modules/CMakeConfigurableFile.in" "/usr/share/cmake-3.5/Modules/CMakeDetermineCCompiler.cmake" "/usr/share/cmake-3.5/Modules/CMakeDetermineCXXCompiler.cmake" "/usr/share/cmake-3.5/Modules/CMakeDetermineCompileFeatures.cmake" "/usr/share/cmake-3.5/Modules/CMakeDetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/CMakeDetermineCompilerABI.cmake" "/usr/share/cmake-3.5/Modules/CMakeDetermineCompilerId.cmake" "/usr/share/cmake-3.5/Modules/CMakeDetermineSystem.cmake" "/usr/share/cmake-3.5/Modules/CMakeFindBinUtils.cmake" "/usr/share/cmake-3.5/Modules/CMakeGenericSystem.cmake" "/usr/share/cmake-3.5/Modules/CMakeLanguageInformation.cmake" "/usr/share/cmake-3.5/Modules/CMakeParseArguments.cmake" "/usr/share/cmake-3.5/Modules/CMakeParseImplicitLinkInfo.cmake" "/usr/share/cmake-3.5/Modules/CMakeSystem.cmake.in" "/usr/share/cmake-3.5/Modules/CMakeSystemSpecificInformation.cmake" "/usr/share/cmake-3.5/Modules/CMakeSystemSpecificInitialize.cmake" "/usr/share/cmake-3.5/Modules/CMakeTestCCompiler.cmake" "/usr/share/cmake-3.5/Modules/CMakeTestCXXCompiler.cmake" "/usr/share/cmake-3.5/Modules/CMakeTestCompilerCommon.cmake" "/usr/share/cmake-3.5/Modules/CMakeUnixFindMake.cmake" "/usr/share/cmake-3.5/Modules/CheckFunctionExists.c" "/usr/share/cmake-3.5/Modules/CheckIncludeFile.c.in" "/usr/share/cmake-3.5/Modules/CheckIncludeFile.cmake" "/usr/share/cmake-3.5/Modules/CheckLibraryExists.cmake" "/usr/share/cmake-3.5/Modules/CheckSymbolExists.cmake" "/usr/share/cmake-3.5/Modules/Compiler/ADSP-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/ARMCC-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/AppleClang-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Borland-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Clang-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Clang-DetermineCompilerInternal.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Compaq-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Cray-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Embarcadero-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Fujitsu-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GHS-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GNU-C-FeatureTests.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GNU-C.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GNU-CXX-FeatureTests.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GNU-CXX.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GNU-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/GNU.cmake" "/usr/share/cmake-3.5/Modules/Compiler/HP-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/HP-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/IAR-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake" "/usr/share/cmake-3.5/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Intel-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/MIPSpro-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/MSVC-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/PGI-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/PathScale-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/SCO-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/SDCC-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/SunPro-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/TI-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/TinyCC-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/VisualAge-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/VisualAge-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/Watcom-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/XL-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/XL-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/zOS-C-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/Compiler/zOS-CXX-DetermineCompiler.cmake" "/usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake" "/usr/share/cmake-3.5/Modules/FindPackageMessage.cmake" "/usr/share/cmake-3.5/Modules/FindPythonInterp.cmake" "/usr/share/cmake-3.5/Modules/FindThreads.cmake" "/usr/share/cmake-3.5/Modules/Internal/FeatureTesting.cmake" "/usr/share/cmake-3.5/Modules/Platform/Linux-CXX.cmake" "/usr/share/cmake-3.5/Modules/Platform/Linux-GNU-C.cmake" "/usr/share/cmake-3.5/Modules/Platform/Linux-GNU-CXX.cmake" "/usr/share/cmake-3.5/Modules/Platform/Linux-GNU.cmake" "/usr/share/cmake-3.5/Modules/Platform/Linux.cmake" "/usr/share/cmake-3.5/Modules/Platform/UnixPaths.cmake" ) # The corresponding makefile is: set(CMAKE_MAKEFILE_OUTPUTS "Makefile" "CMakeFiles/cmake.check_cache" ) # Byproducts of CMake generate step: set(CMAKE_MAKEFILE_PRODUCTS "CMakeFiles/3.5.1/CMakeSystem.cmake" "CMakeFiles/3.5.1/CMakeCXXCompiler.cmake" "CMakeFiles/3.5.1/CMakeCCompiler.cmake" "CMakeFiles/3.5.1/CMakeCXXCompiler.cmake" "CMakeFiles/3.5.1/CMakeCCompiler.cmake" "CMakeFiles/CMakeDirectoryInformation.cmake" ) # Dependency information for all targets: set(CMAKE_DEPEND_INFO_FILES "CMakeFiles/gtest_xml_output_unittest_.dir/DependInfo.cmake" "CMakeFiles/gtest_uninitialized_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_shuffle_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_output_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_list_tests_unittest_.dir/DependInfo.cmake" "CMakeFiles/gtest_help_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_env_var_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_throw_on_failure_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_color_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_catch_exceptions_ex_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_catch_exceptions_no_ex_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_break_on_failure_unittest_.dir/DependInfo.cmake" "CMakeFiles/gtest-listener_test.dir/DependInfo.cmake" "CMakeFiles/gtest-message_test.dir/DependInfo.cmake" "CMakeFiles/gtest_environment_test.dir/DependInfo.cmake" "CMakeFiles/gtest-param-test_test.dir/DependInfo.cmake" "CMakeFiles/sample9_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest.dir/DependInfo.cmake" "CMakeFiles/sample10_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest-filepath_test.dir/DependInfo.cmake" "CMakeFiles/sample2_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest-linked_ptr_test.dir/DependInfo.cmake" "CMakeFiles/sample1_unittest.dir/DependInfo.cmake" "CMakeFiles/sample7_unittest.dir/DependInfo.cmake" "CMakeFiles/sample3_unittest.dir/DependInfo.cmake" "CMakeFiles/sample4_unittest.dir/DependInfo.cmake" "CMakeFiles/sample5_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest-test-part_test.dir/DependInfo.cmake" "CMakeFiles/gtest-options_test.dir/DependInfo.cmake" "CMakeFiles/gtest_main_no_exception.dir/DependInfo.cmake" "CMakeFiles/gtest_main_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest_main_no_rtti.dir/DependInfo.cmake" "CMakeFiles/gtest_main.dir/DependInfo.cmake" "CMakeFiles/gtest_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest_xml_outfile2_test_.dir/DependInfo.cmake" "CMakeFiles/sample6_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest-unittest-api_test.dir/DependInfo.cmake" "CMakeFiles/gtest_repeat_test.dir/DependInfo.cmake" "CMakeFiles/gtest-death-test_test.dir/DependInfo.cmake" "CMakeFiles/gtest_main_use_own_tuple.dir/DependInfo.cmake" "CMakeFiles/gtest_no_test_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest-port_test.dir/DependInfo.cmake" "CMakeFiles/gtest_pred_impl_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest_filter_unittest_.dir/DependInfo.cmake" "CMakeFiles/sample8_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest_premature_exit_test.dir/DependInfo.cmake" "CMakeFiles/gtest-printers_test.dir/DependInfo.cmake" "CMakeFiles/gtest_throw_on_failure_ex_test.dir/DependInfo.cmake" "CMakeFiles/gtest-death-test_ex_nocatch_test.dir/DependInfo.cmake" "CMakeFiles/gtest_prod_test.dir/DependInfo.cmake" "CMakeFiles/gtest_sole_header_test.dir/DependInfo.cmake" "CMakeFiles/gtest_xml_outfile1_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_stress_test.dir/DependInfo.cmake" "CMakeFiles/gtest-typed-test_test.dir/DependInfo.cmake" "CMakeFiles/gtest_dll_test_.dir/DependInfo.cmake" "CMakeFiles/gtest_no_exception.dir/DependInfo.cmake" "CMakeFiles/gtest_dll.dir/DependInfo.cmake" "CMakeFiles/gtest_no_rtti_unittest.dir/DependInfo.cmake" "CMakeFiles/gtest-death-test_ex_catch_test.dir/DependInfo.cmake" "CMakeFiles/gtest-tuple_test.dir/DependInfo.cmake" "CMakeFiles/gtest_use_own_tuple_test.dir/DependInfo.cmake" ) <file_sep>#define CMake_VERSION_MAJOR 3 #define CMake_VERSION_MINOR 5 #define CMake_VERSION_PATCH 1 #define CMake_VERSION "3.5.1" <file_sep>#!/bin/sh set -efu PYS=$(pyversions -rv 2>/dev/null)" "$(py3versions -rv 2>/dev/null) cd "$ADTTMP" cat << EOF > hello.f C File hello.f integer function foo (a) integer a foo = a + 1 end EOF for py in " " 3 $PYS; do [ "$py" = " " ] && py="" echo "=== f2py$py ===" f2py$py -c -m hello hello.f 2>&1 python$py -c 'import hello; assert hello.foo(4) == 5' f2py$py-dbg -c -m hello hello.f 2>&1 python$py-dbg -c 'import hello; assert hello.foo(4) == 5' 2>&1 done <file_sep>#! /bin/sh /usr/share/dpatch/dpatch-run ## 110-bugfix-LOGCXX-280.dpatch by <<EMAIL>> ## ## All lines beginning with `## DP:' are a description of the patch. ## DP: fixes build problem on HP-UX @DPATCH@ diff -urNad log4cxx-0.10.0~/src/changes/changes.xml log4cxx-0.10.0/src/changes/changes.xml --- log4cxx-0.10.0~/src/changes/changes.xml 2008-03-31 15:34:52.000000000 -0700 +++ log4cxx-0.10.0/src/changes/changes.xml 2008-07-17 06:55:12.000000000 -0700 @@ -227,6 +227,7 @@ <action issue="LOGCXX-257">ServerSocket::accept hangs on Unix</action> <action issue="LOGCXX-258">unable to build from make dist package due to missing doxygen file</action> <action issue="LOGCXX-259">Several appenders fail to compile in Visual Studio 2008</action> +<action issue="LOGCXX-280">tests and sample code unnecessarily compiled during default make target</action> </release> <release version="0.9.7" date="2004-05-10"> <action type="fix">Fixed examples source code in the "Short introduction to log4cxx".</action> diff -urNad log4cxx-0.10.0~/src/examples/cpp/Makefile.am log4cxx-0.10.0/src/examples/cpp/Makefile.am --- log4cxx-0.10.0~/src/examples/cpp/Makefile.am 2008-03-31 15:34:52.000000000 -0700 +++ log4cxx-0.10.0/src/examples/cpp/Makefile.am 2008-07-17 06:53:23.000000000 -0700 @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -noinst_PROGRAMS = trivial delayedloop stream console +check_PROGRAMS = trivial delayedloop stream console INCLUDES = -I$(top_srcdir)/src/main/include -I$(top_builddir)/src/main/include diff -urNad log4cxx-0.10.0~/src/test/cpp/Makefile.am log4cxx-0.10.0/src/test/cpp/Makefile.am --- log4cxx-0.10.0~/src/test/cpp/Makefile.am 2008-03-31 15:33:32.000000000 -0700 +++ log4cxx-0.10.0/src/test/cpp/Makefile.am 2008-07-17 06:53:50.000000000 -0700 @@ -24,7 +24,7 @@ INCLUDES = -I$(top_srcdir)/src/main/include -I$(top_builddir)/src/main/include -noinst_PROGRAMS = testsuite +check_PROGRAMS = testsuite customlogger_tests = \ customlogger/xlogger.cpp\ <file_sep>CMAKE = "/home/arthur/ros_varient/sim-install/cmake-3.5.1/bin/cmake" <file_sep># /usr/bin/bash cd $(dirname "$0") source ./env.sh echo $DEP cd $DEP/utils/tinyxml-2.6.2 make clean make sudo cp libtinyxml.so /usr/lib sudo cp tinyxml.h /usr/include <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/rosbash/etc/catkin/profile.d/15.rosbash.bash<file_sep>set(url "file:///home/arthur/ros_varient/sim-install/cmake-3.5.1/Tests/CMakeTests/FileDownloadInput.png") set(dir "/home/arthur/ros_varient/sim-install/cmake-3.5.1/Tests/CMakeTests/downloads") file(DOWNLOAD ${url} ${dir}/file3.png TIMEOUT 2 STATUS status EXPECTED_HASH SHA1=5555555555555555555555555555555555555555 ) <file_sep>source ./script/common.func os=$(JudgeOS) case ${os} in CentOS) yum -y install epel-release yum -y install python-pip yum -y install python-devel;; Ubuntu) apt install python-pip python-dev -y;; *) ;; esac <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/genpy/share/genpy/cmake/genpy-extras.cmake<file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/rosout/share/rosout/cmake/rosoutConfig.cmake<file_sep>#!/usr/bin/make -f # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 export OSLO_PACKAGE_VERSION=$(shell dpkg-parsechangelog | sed -n -e 's/^Version: //p' | sed -e 's/^[[:digit:]]*://' -e 's/[-].*//') export PYBUILD_NAME=mock %: dh $@ --with python2,python3,sphinxdoc --buildsystem=pybuild override_dh_auto_build: dh_auto_build PYTHONPATH=. sphinx-build -b html -N docs/ docs/.build/html override_dh_installchangelogs: dh_installchangelogs -- docs/changelog.txt override_dh_compress: dh_compress -X.js -X.html -X.txt override_dh_clean: rm -rf docs/.build dh_clean <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/mk/share/mk/cmake/mkConfig-version.cmake<file_sep># Install script for directory: /home/arthur/ros_varient/sim-install/cmake-3.5.1 # Set the install prefix if(NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "/usr") endif() string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) if(BUILD_TYPE) string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") else() set(CMAKE_INSTALL_CONFIG_NAME "") endif() message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") endif() # Set the component getting installed. if(NOT CMAKE_INSTALL_COMPONENT) if(COMPONENT) message(STATUS "Install component: \"${COMPONENT}\"") set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") else() set(CMAKE_INSTALL_COMPONENT) endif() endif() # Install shared libraries without execute permission? if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) set(CMAKE_INSTALL_SO_NO_EXE "0") endif() if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified") file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/doc/cmake-3.5" TYPE FILE FILES "/home/arthur/ros_varient/sim-install/cmake-3.5.1/Copyright.txt") endif() if(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified") file(INSTALL DESTINATION "${CMAKE_INSTALL_PREFIX}/share/cmake-3.5" TYPE DIRECTORY PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ DIR_PERMISSIONS OWNER_READ OWNER_EXECUTE OWNER_WRITE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE FILES "/home/arthur/ros_varient/sim-install/cmake-3.5.1/Help" "/home/arthur/ros_varient/sim-install/cmake-3.5.1/Modules" "/home/arthur/ros_varient/sim-install/cmake-3.5.1/Templates" REGEX "/[^/]*\\.sh[^/]*$" PERMISSIONS OWNER_READ OWNER_EXECUTE OWNER_WRITE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) endif() if(NOT CMAKE_INSTALL_LOCAL_ONLY) # Include the install script for each subdirectory. include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Source/kwsys/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/KWIML/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmzlib/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmcurl/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmcompress/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmbzip2/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmliblzma/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmlibarchive/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmexpat/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmjsoncpp/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Source/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Utilities/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Tests/cmake_install.cmake") include("/home/arthur/ros_varient/sim-install/cmake-3.5.1/Auxiliary/cmake_install.cmake") endif() if(CMAKE_INSTALL_COMPONENT) set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") else() set(CMAKE_INSTALL_MANIFEST "install_manifest.txt") endif() string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT "${CMAKE_INSTALL_MANIFEST_FILES}") file(WRITE "/home/arthur/ros_varient/sim-install/cmake-3.5.1/${CMAKE_INSTALL_MANIFEST}" "${CMAKE_INSTALL_MANIFEST_CONTENT}") <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/catkin/env.sh<file_sep>#! /usr/bin/bash source ./env.sh cd $DEP/basic/zlib-1.2.11 ./configure --prefix=/usr make make install <file_sep># CMake generated Testfile for # Source directory: /home/arthur/ros_varient/sim-install/console-bridge-0.3.2/test # Build directory: /home/arthur/ros_varient/sim-install/console-bridge-0.3.2/test # # This file includes the relevant testing commands required for # testing this directory and lists subdirectories to be tested as well. add_test(console_TEST "/home/arthur/ros_varient/sim-install/console-bridge-0.3.2/test/console_TEST" "--gtest_output=xml:/home/arthur/ros_varient/sim-install/console-bridge-0.3.2/test_results/console_TEST.xml") set_tests_properties(console_TEST PROPERTIES TIMEOUT "240") <file_sep># -*- coding: utf-8 -*- """ test_search ~~~~~~~~~~~ Test the search index builder. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from docutils import frontend, utils from docutils.parsers import rst from sphinx.search import IndexBuilder from sphinx.util import jsdump from util import with_app settings = parser = None def setup_module(): global settings, parser optparser = frontend.OptionParser(components=(rst.Parser,)) settings = optparser.get_default_values() parser = rst.Parser() FILE_CONTENTS = '''\ .. test that comments are not indexed: boson test that non-comments are indexed: fermion ''' def test_wordcollector(): doc = utils.new_document(b'test data', settings) doc['file'] = 'dummy' parser.parse(FILE_CONTENTS, doc) ix = IndexBuilder(None, 'en', {}, None) ix.feed('filename', 'title', doc) assert 'boson' not in ix._mapping assert 'fermion' in ix._mapping @with_app() def test_objects_are_escaped(app, status, warning): app.builder.build_all() searchindex = (app.outdir / 'searchindex.js').text() assert searchindex.startswith('Search.setIndex(') index = jsdump.loads(searchindex[16:-2]) assert 'n::Array&lt;T, d&gt;' in index.get('objects').get('') # n::Array<T,d> is escaped <file_sep>#! /usr/bin/bash VER="1.58.0" FILE="boost_1_58_0.tar.gz" DIR="boost_1_58_0" if [ ! -f ./$FILE ]; then wget https://sourceforge.net/projects/boost/files/boost/$VER/$FILE/download -O $FILE tar xzvf $FILE else rm -r boost_1_58_0 tar xzvf $FILE fi cd $DIR ./bootstrap.sh ./b2 sudo cp -r boost /usr/include/ sudo cp -P stage/lib/* /usr/lib <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/rosgraph_msgs/include/rosgraph_msgs/Log.h<file_sep>#! /usr/bin/make -f # # debian/rules # Part of Debian ‘python-coverage’ package. # # Copyright © 2010–2014 <NAME> <<EMAIL>> # This is free software; you may copy, modify and/or distribute this work # under the terms of the BSD 2-clause license. # No warranty expressed or implied. # See the file ‘coverage/__init__.py’ for details. SOURCE_PACKAGE_NAME = python-coverage PYTHON2_PACKAGE_NAME = python-coverage PYTHON3_PACKAGE_NAME = python3-coverage python2_debug_package_name = ${PYTHON2_PACKAGE_NAME}-dbg python3_debug_package_name = ${PYTHON3_PACKAGE_NAME}-dbg package_working_root = debian package_install_root = ${package_working_root}/tmp package_install_bin_dir = ${package_install_root}/usr/bin PYTHON2_VERSIONS = $(shell pyversions -vr) PYTHON3_VERSIONS = $(shell py3versions -vr) PYTHON_VERSIONS = ${PYTHON2_VERSIONS} ${PYTHON3_VERSIONS} # For some ‘/usr/bin/*-coverage’ programs (and not others), we need the # default, not current, Python interpreter in the shebang. The ‘dh-python’ # helpers can re-write shebangs, but they are too eager, converting every # program's shebang without allowing us to specify different interpreters # per program. We resort to ‘sed’. python3_program = ${package_install_bin_dir}/python3-coverage shebang_line_regex = ^\#!.*$$ python3_shebang_interpreter = /usr/bin/python3 debug_object_exclude += _d.so # Unfortunately, ‘dh_install --exclude’ requires a substring, and a glob # wildcard will *not* work. So we need to specify the exact substring for # the Python 3 debug module filenames. python3_objcode_versions = $(shell \ printf "%s\n" ${PYTHON3_VERSIONS} | sed -e 's/\.//g') DEB_HOST_MULTIARCH = $(shell dpkg-architecture -qDEB_HOST_MULTIARCH) debug_object_exclude += $(foreach ver,${python3_objcode_versions}, \ .cpython-${ver}dm-${DEB_HOST_MULTIARCH}.so) DISTRIBUTION_NAME = coverage egg_info_dir = ${DISTRIBUTION_NAME}.egg-info GENERATED_FILES += ${egg_info_dir}/PKG-INFO ${egg_info_dir}/SOURCES.txt HTMLFILES_DIR = ${DISTRIBUTION_NAME}/htmlfiles htmlfiles_dirname = $(notdir ${HTMLFILES_DIR}) bundled_libraries += $(addprefix ${HTMLFILES_DIR}/, \ jquery.hotkeys.js \ jquery.isonscreen.js \ ) RESOURCES_DIR = resources package_install_resources_root = ${package_install_root}/${RESOURCES_DIR} DOCUMENTATION_DIR = doc MANPAGE_SUFFIX = .1 manpage_tempfile_suffix = ${MANPAGE_SUFFIX}.tmp default_manpage_name = python-coverage${MANPAGE_SUFFIX} python2_manpage_names = $(addsuffix ${MANPAGE_SUFFIX}, \ $(notdir $(wildcard ${package_install_bin_dir}/python2*-coverage))) python3_manpage_names = $(addsuffix ${MANPAGE_SUFFIX}, \ $(notdir $(wildcard ${package_install_bin_dir}/python3*-coverage))) versioned_manpage_names = ${python2_manpage_names} ${python3_manpage_names} versioned_manpage_paths = $(addprefix ${DOCUMENTATION_DIR}/, \ ${versioned_manpage_names}) GENERATED_FILES += ${DOCUMENTATION_DIR}/*${MANPAGE_SUFFIX} GENERATED_FILES += ${DOCUMENTATION_DIR}/*${manpage_tempfile_suffix} INSTALL = install # Send HTTP traffic to the “discard” service during packaging actions. export http_proxy = http://127.0.1.1:9/ export https_proxy = ${http_proxy} RST_SUFFIX = .txt RST2MAN = rst2man ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))) .PHONY: test-python% test-python%: python$* setup.py test -vv endif .PHONY: build build: build-arch build-indep build: remove-bundled-libraries build: ${MANPAGES} manpage-symlinks dh $@ --with python2,python3 .PHONY: build-arch build-arch: build-stamp dh $@ --with python2,python3 .PHONY: build-indep build-indep: build-stamp dh $@ --with python2,python3 build-stamp: touch $@ .PHONY: build-python% build-python%: python$*-dbg setup.py build python$* setup.py build .PHONY: remove-bundled-libraries remove-bundled-libraries: $(RM) ${bundled_libraries} .PHONY: manpage-symlinks manpage-symlinks: ${versioned_manpage_paths} ${DOCUMENTATION_DIR}/${default_manpage_name}: ${package_working_root}/${default_manpage_name} $(INSTALL) --mode=u=rw,go=r "$<" "$@" ${DOCUMENTATION_DIR}/%${MANPAGE_SUFFIX}: ${DOCUMENTATION_DIR}/${default_manpage_name} ln -s ${default_manpage_name} "$@" %.1: %.1${RST_SUFFIX} $(RST2MAN) $< > "$@".tmp cat debian/manpage_encoding_declaration.UTF-8 "$@".tmp > "$@" .PHONY: clean clean: dh $@ --with python2,python3 $(RM) -r ${GENERATED_FILES} .PHONY: override_dh_auto_clean override_dh_auto_clean: dh_auto_clean $(RM) -r build $(RM) -r ${egg_info_dir} # Policy §4.9 strongly recommends the ‘get-orig-source’ target: # “This target is optional, but providing it if possible is a good idea.” .PHONY: get-orig-source get-orig-source: http_proxy = get-orig-source: makefile_dir = $(abspath $(dir $(firstword ${MAKEFILE_LIST}))) get-orig-source: package_dir = $(abspath $(dir ${makefile_dir})) get-orig-source: uscan --noconf --verbose \ --force-download --download-current-version \ --rename \ --destdir=$(CURDIR) \ --check-dirname-level=0 ${package_dir} .PHONY: install install: build dh $@ --with python2,python3 \ --package ${python2_debug_package_name} \ --package ${python3_debug_package_name} dh $@ --with python2,python3 \ $(foreach exclude_part,${debug_object_exclude}, \ --exclude ${exclude_part}) ${package_install_resources_root}: $(INSTALL) -d "$@" ${package_install_resources_root}/${htmlfiles_dirname}: ${HTMLFILES_DIR} ${package_install_resources_root} $(INSTALL) -d "$@" $(INSTALL) --mode=u=rw,go=r "$<"/* "$@" .PHONY: install-resource-files install-resource-files: ${package_install_resources_root} install-resource-files: ${package_install_resources_root}/${htmlfiles_dirname} .PHONY: install-python% install-python%: python_version_major = $(firstword $(subst ., ,$*)) install-python%: python$*-dbg setup.py install --install-layout=deb \ --root=$(CURDIR)/${package_install_root} python$* setup.py install --install-layout=deb \ --root=$(CURDIR)/${package_install_root} if [ "${python_version_major}" = "3" ] ; then \ sed -i -e '1 s,${shebang_line_regex},#! ${python3_shebang_interpreter},' \ "${python3_program}" ; \ fi .PHONY: binary-indep binary-indep: build install .PHONY: binary-arch binary-arch: build install dh $@ --with python2,python3 .PHONY: binary binary: build binary-indep binary-arch .PHONY: override_dh_strip override_dh_strip: dh_strip --package=${PYTHON2_PACKAGE_NAME} --dbg-package=${python2_debug_package_name} dh_strip --package=${PYTHON3_PACKAGE_NAME} --dbg-package=${python3_debug_package_name} .PHONY: override_dh_auto_build override_dh_auto_build: $(foreach pyversion,${PYTHON_VERSIONS},$(pyversion:%=build-python%)) override_dh_auto_build: dh_auto_build .PHONY: override_dh_auto_install override_dh_auto_install: $(foreach pyversion,${PYTHON_VERSIONS},$(pyversion:%=install-python%)) override_dh_auto_install: install-resource-files dh_auto_install .PHONY: override_dh_link override_dh_link: dh_link for pyversion in ${PYTHON2_VERSIONS} ; do \ dh_link \ --package=${PYTHON2_PACKAGE_NAME} \ usr/share/${PYTHON2_PACKAGE_NAME}/${htmlfiles_dirname} \ usr/lib/python$${pyversion}/dist-packages/${HTMLFILES_DIR} ; \ done .PHONY: override_dh_installchangelogs override_dh_installchangelogs: dh_installchangelogs CHANGES.txt .PHONY: override_dh_installdocs override_dh_installdocs: dh_installdocs \ --package=${PYTHON2_PACKAGE_NAME} \ --package=${python2_debug_package_name} \ --link-doc=${PYTHON2_PACKAGE_NAME} dh_installdocs \ --package=${PYTHON3_PACKAGE_NAME} \ --package=${python3_debug_package_name} \ --link-doc=${PYTHON3_PACKAGE_NAME} # Local variables: # mode: makefile # coding: utf-8 # End: # vim: filetype=make fileencoding=utf-8 : <file_sep>#! /usr/bin/bash PWD=$(pwd) DEP=$PWD/../dependencies OSRF_SOURCE_BAREBONE=$PWD/../osrf-distro-source/bare_bone <file_sep>from distutils.core import setup from distutils.sysconfig import get_python_lib setup( name='PILcompat', description='PIL compatibility hack', packages=['PILcompat'], author='<NAME>', author_email='<EMAIL>', data_files=[(get_python_lib(), ['PILcompat.pth'])], ) <file_sep># generated from ros_environment/env-hooks/1.ros_etc_dir.sh.em # env variable in develspace export ROS_ETC_DIR="/home/parallels/Desktop/compare2/kinetic/devel/.private/ros_environment/etc/ros" <file_sep># generated from rosbash/env-hooks/15.rosbash.zsh.em . "/home/parallels/Desktop/compare2/kinetic/src/ros/rosbash/roszsh" <file_sep># /usr/bin/bash cd $(dirname "$0") source env.sh cd $DEP/utils/lz4-0.0~r131 cd ./lib && make -j32 cp liblz4.so /usr/lib cd .. make -j32 #make exec cp programs/lz4 /usr/bin cp ./lib/lz4.h /usr/include <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/std_srvs/include/std_srvs/TriggerRequest.h<file_sep>any role -------- * :cpp:any:`Sphinx` * ref function without parens :cpp:any:`hello`. * ref function with parens :cpp:any:`hello()`. * :cpp:any:`Sphinx::version` * :cpp:any:`version` * :cpp:any:`List` * :cpp:any:`MyEnum` <file_sep>source ./script/common.func MPFR=mpfr-2.4.2 GMP=gmp-4.3.2 MPC=mpc-1.0.3 os=$(JudgeOS) # todo: check to see if we cant eliminate libc-devel case ${os} in CentOS) yum -y install compat-glibc glibc-devel yum -y install gcc gcc-c++;; Ubuntu) apt install python-pip python-dev wget -y;; *) ;; esac # if [[ ! -f ./gcc-4.8.0.tar.gz ]]; then wget https://mirrors.ustc.edu.cn/gnu/gcc/gcc-4.8.0/gcc-4.8.0.tar.gz -O gcc-4.8.0.tar.gz tar xvf gcc-4.8.0.tar.gz cp ./toolchain/download_prerequisites ./gcc-4.8.0/contrib/download_prerequisites cd ./gcc-4.8.0 ./contrib/download_prerequisites cd ../ fi mkdir -p objdir cd objdir ../gcc-4.8.0/configure --prefix=/opt --disable-multilib --enable-languages=c,c++ make -j32 make install export CXX=/opt/bin/g++ export CC=/opt/bin/gcc <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/genmsg/share/genmsg/cmake/genmsgConfig.cmake<file_sep>#!/usr/bin/make -f include ../common.mk DPY=$(DEBPYTHON_DEFAULT) clean: clean-common check: test -f debian/python-foo/usr/lib/python$(DPY)/dist-packages/foo.py test -f debian/python-foo/usr/lib/python$(DPY)/dist-packages/bar/bar.py grep -q pycompile debian/python-foo/DEBIAN/postinst grep -q pyclean debian/python-foo/DEBIAN/prerm <file_sep>#! /usr/bin/bash cd $(dirname "$0") source ./env.sh cd $DEP/utils/apr-1.5.2 ./configure --prefix=/usr --disable-static --with-installbuilddir=/usr/share/apr-1/build && make -j32 make install cd $DEP/utils/apr-util-1.5.4 ./configure --prefix=/usr --with-gdbm=/usr --with-openssl=/usr --with-crypto --with-apr=/usr && make -j32 make install <file_sep>#! /usr/bin/bash cd $(dirname "$0") source ./env.sh cd $DEP/utils/log4cxx-0.10.0 ./configure --prefix=/usr make -j32 make install <file_sep>#! /usr/bin/bash source ./env.sh cd $DEP/basic/automake-1.15 ./configure --prefix=/usr make make install <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/std_msgs/include/std_msgs/Duration.h<file_sep>#! /bin/sh /usr/share/dpatch/dpatch-run ## 110-bugfix-LOGCXX-249.dpatch by <<EMAIL>> ## ## All lines beginning with `## DP:' are a description of the patch. ## DP: Fixes crash when using ConsoleAppender without setting a layout @DPATCH@ diff -urNad log4cxx-0.10.0~/src/changes/changes.xml log4cxx-0.10.0/src/changes/changes.xml --- log4cxx-0.10.0~/src/changes/changes.xml 2008-03-31 15:34:52.000000000 -0700 +++ log4cxx-0.10.0/src/changes/changes.xml 2008-07-17 06:58:26.000000000 -0700 @@ -219,6 +219,7 @@ <action issue="LOGCXX-246">Config refresh hangs a client application that uses TelnetAppender</action> <action issue="LOGCXX-247">MSVC project has wrong additional include directories</action> <action issue="LOGCXX-248">ODBCAppender has unicode issues</action> +<action issue="LOGCXX-249">Console appender crashes if layout is not set</action> <action issue="LOGCXX-251">NDC::cloneStack and NDC::inherit missing in 0.10.0 RC2</action> <action issue="LOGCXX-252">Add documentation for use of operator&lt;&lt; in logging requests</action> <action issue="LOGCXX-253">Transcoder compilation error with utf-8 charset</action> diff -urNad log4cxx-0.10.0~/src/main/cpp/writerappender.cpp log4cxx-0.10.0/src/main/cpp/writerappender.cpp --- log4cxx-0.10.0~/src/main/cpp/writerappender.cpp 2008-03-31 15:34:09.000000000 -0700 +++ log4cxx-0.10.0/src/main/cpp/writerappender.cpp 2008-07-17 06:57:48.000000000 -0700 @@ -115,6 +115,10 @@ return false; } + + if (layout == 0) { + return false; + } return true; } diff -urNad log4cxx-0.10.0~/src/test/cpp/consoleappendertestcase.cpp log4cxx-0.10.0/src/test/cpp/consoleappendertestcase.cpp --- log4cxx-0.10.0~/src/test/cpp/consoleappendertestcase.cpp 2008-03-31 15:33:32.000000000 -0700 +++ log4cxx-0.10.0/src/test/cpp/consoleappendertestcase.cpp 2008-07-17 06:59:42.000000000 -0700 @@ -33,7 +33,7 @@ // LOGUNIT_TEST(testDefaultThreshold); LOGUNIT_TEST(testSetOptionThreshold); - + LOGUNIT_TEST(testNoLayout); LOGUNIT_TEST_SUITE_END(); @@ -42,6 +42,16 @@ WriterAppender* createWriterAppender() const { return new log4cxx::ConsoleAppender(); } + + void testNoLayout() { + Pool p; + ConsoleAppenderPtr appender(new ConsoleAppender()); + appender->activateOptions(p); + LoggerPtr logger(Logger::getRootLogger()); + logger->addAppender(appender); + LOG4CXX_INFO(logger, "No layout specified for ConsoleAppender"); + logger->removeAppender(appender); + } }; LOGUNIT_TEST_SUITE_REGISTRATION(ConsoleAppenderTestCase); <file_sep>#! /bin/sh # Post-install script for ‘python-coverage-dbg’. # # Manpage: ‘dh_installdeb(1)’ set -e # Summary of ways this script can be called: # * <postinst> configure <most-recently-configured-version> # * <old-postinst> abort-upgrade <new-version> # * <conflictor's-postinst> abort-remove in-favour <package> # <new-version> # * <postinst> abort-remove # * <deconfigured's-postinst> abort-deconfigure in-favour # <failed-install-package> <version> # [removing <conflicting-package> <version>] # For details, see the Debian Policy §6.5 in the ‘debian-policy’ package # or on the web at <URL:http://www.debian.org/doc/debian-policy/>. action="$1" main_package_name=python-coverage debug_package_name=${main_package_name}-dbg doc_root_dir="/usr/share/doc" main_doc_dir="${doc_root_dir}/${main_package_name}" debug_doc_dir="${doc_root_dir}/${debug_package_name}" case "$action" in configure) most_recent_version="$2" if dpkg --compare-versions "$most_recent_version" lt-nl "3.6-1"; then # Replace debug package doc directory with symlink to # main doc directory. if [ ! -L "$debug_doc_dir" ] && [ -d "$debug_doc_dir" ]; then if rmdir "$debug_doc_dir" 2>/dev/null; then ln -sf $main_package_name "$debug_doc_dir" fi fi fi ;; abort-upgrade|abort-remove|abort-deconfigure) ;; *) printf "postinst called with unknown action ‘%s’\n" "$action" >&2 exit 1 ;; esac #DEBHELPER# exit 0 <file_sep>#! /usr/bin/bash cd $(dirname "$0") source env.sh cd $DEP/utils/gtest-1.7.0 ./configure --prefix=/usr make -j32 # gtest do not support make install, we have to copy manually cp ./lib/.libs/libgtest_main.so /usr/lib cp ./lib/.libs/libgtest.so /usr/lib cp -r ./include/gtest /usr/include <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/roscpp/include/ros/common.h<file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/catkin/_setup_util.py<file_sep>#!/usr/bin/make -f clean: rm -rf cache #rm -f dist_fallback dist_fallback: sources.list python ./generate_fallback_list.py --skip-sensible-names .PHONY: clean <file_sep>#! /usr/bin/bash catkin config -s ./osrf-distro-source/bare-bone/ -i ./release --install --merge-install -j12 catkin build <file_sep># generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in set(roscpp_MSG_INCLUDE_DIRS "/home/parallels/Desktop/compare2/kinetic/src/ros_comm/roscpp/msg") set(roscpp_MSG_DEPENDENCIES ) <file_sep>with ubuntu 18.04: step1: $sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list' $sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654 step2: $sudo apt-get update $sudo apt-get install python3-rosdep python3-rosinstall-generator python3-wstool python3-rosinstall build-essential $sudo rosdep init $rosdep update step3: git clone --> this repo step4: we use the melodic dependencies [optional--], also we can rosolve dependencies later with pip3 rosdep install --from-paths src --ignore-src --rosdistro melodic -y step5: $ export ROS_PYTHON_VERSION=3 $ sudo ./src/catkin/bin/catkin_make_isolated --install --install-space /opt/ros/melodic -DCMAKE_BUILD_TYPE=Release or just export ROS_PYTHON_VERSION=3 catkin build --cmake-args -DPYTHON_VERSION=3.6 with the help of - apt install python3-catkin-tools - pip3 install empy - sudo apt install python3-netifaces - sudo apt-get install python3-rospkg step6: source ./devel/setup.bash run roscore with python3 happily on ubuntu 18.04 <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/rosgraph_msgs/include/rosgraph_msgs/Clock.h<file_sep># /usr/bin/bash cd $(dirname "$0") source ./env.sh cd $DEP/utils/bzip2-1.0.6 # clear the old one sudo rm /usr/bin/bzip2 /usr/bin/bunzip2 /usr/bin/bzcat /usr/bin/bzip2recover make -f Makefile-libbz2_so make make install cp ./bzlip.h /usr/include cp ./libbz2.so /usr/lib <file_sep>#! /usr/bin/bash source ./env.sh cd $DEP/basic/sbcl-1.3.1 echo '"1.3.1"' > version.lisp-expr sh make.sh --prefix=/usr --fancy sh install.sh <file_sep>#! /usr/bin/bash cd $(dirname "$0") source env.sh cd $DEP/utils/openssl-1.0.2g ./Configure --prefix=/usr && make depend -j32 && make -j32 && make install <file_sep>#!/bin/sh set -efu blaslib=$(update-alternatives --list libblas.so.3 | grep $(basename $0)) update-alternatives --set libblas.so.3 $blaslib # one python is enough PYS=${PYS:-"$(pyversions -d 2>/dev/null)"} #test only modules that link against libblas PYS=$PYS TESTPKG=numpy.core debian/tests/python2 PYS=$PYS TESTPKG=numpy.linalg debian/tests/python2 <file_sep>#!/usr/bin/make -f #export DH_VERBOSE=1 SHELL=/bin/bash BUILDDIR := debian/build DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH) DEB_HOST_ARCH_OS ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_OS) DEB_HOST_ARCH_BITS ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_BITS) DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH) # The 'build' target needs special handling because there there is a directory # named 'build'. .PHONY: build %: dh $@ -B$(BUILDDIR) --parallel --with autotools_dev # # configure # CONFFLAGS := LTFLAGS=--no-silent \ --host=$(DEB_HOST_GNU_TYPE) \ --build=$(DEB_BUILD_GNU_TYPE) \ --enable-layout=Debian \ --includedir=/usr/include/apr-1.0 \ --with-installbuilddir=/usr/share/apr-1.0/build \ --libdir=/usr/lib/$(DEB_HOST_MULTIARCH) \ --enable-nonportable-atomics \ --enable-allocator-uses-mmap \ ac_cv_prog_AWK=mawk # apr_cv_mutex_robust_shared causes hangs in procmutex test on arm(el|hf) and alpha ifneq (,$(findstring armel,$(DEB_HOST_ARCH))) CONFFLAGS += apr_cv_mutex_robust_shared=no endif ifneq (,$(findstring armhf,$(DEB_HOST_ARCH))) CONFFLAGS += apr_cv_mutex_robust_shared=no endif ifneq (,$(findstring alpha,$(DEB_HOST_ARCH))) CONFFLAGS += apr_cv_mutex_robust_shared=no endif # SH4 cannot use proc_pthread. ifneq (,$(findstring sh4,$(DEB_HOST_ARCH))) CONFFLAGS += apr_cv_hasprocpthreadser=no ac_cv_define_PTHREAD_PROCESS_SHARED=no endif # multicast not supported on Hurd ifeq (hurd,$(DEB_HOST_ARCH_OS)) CONFFLAGS += apr_cv_struct_ipmreq=no endif # some minimal cross-building support ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) ifeq ($(DEB_HOST_ARCH_OS),linux) CONFFLAGS += ac_cv_file__dev_zero=yes \ ac_cv_func_setpgrp_void=yes \ apr_cv_epoll=yes \ ac_cv_struct_rlimit=yes \ apr_cv_tcp_nodelay_with_cork=yes \ apr_cv_process_shared_works=yes endif ifeq ($(DEB_HOST_ARCH_BITS),32) CONFFLAGS += ac_cv_sizeof_struct_iovec=8 else ifeq ($(DEB_HOST_ARCH_BITS),64) CONFFLAGS += ac_cv_sizeof_struct_iovec=16 endif endif # files that are modified by buildconf and need to be restored during clean SAVE_FILES := configure build/libtool.m4 build/ltmain.sh override_dh_auto_configure: mkdir -p $(BUILDDIR)/docs for f in $(SAVE_FILES) ; do [ -e $$f.dr-orig ] || cp -p $$f $$f.dr-orig ; done ./buildconf # We need to force the use of bash here. Otherwise, if apr is built with # /bin/sh -> /bin/bash, the resulting libtool will not work on systems # where /bin/sh -> /bin/dash. cd $(BUILDDIR) && CONFIG_SHELL=/bin/bash /bin/bash $(CURDIR)/configure $(CONFFLAGS) ifeq (linux,$(DEB_HOST_ARCH_OS)) if grep -q APR_HAS_POSIXSEM_SERIALIZE.*0 $(BUILDDIR)/include/apr.h ;\ then \ echo "WARNING: This is Linux but configure did not detect POSIX semaphores." ;\ if ! df /dev/shm/.|grep -q ^tmpfs ;\ then \ echo "ERROR: POSIX semaphores not usable and /dev/shm not mounted." ;\ echo "ERROR: Aborting." ;\ echo "HINT: If you are using pbuilder or cowbuilder, add /dev/shm to BINDMOUNTS" ;\ echo "HINT: in pbuilderrc" ;\ exit 1 ;\ fi ;\ fi endif # # build # ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) NUMJOBS := $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) endif override_dh_auto_build: $(MAKE) -j$(NUMJOBS) -C $(BUILDDIR) all dox find debian/build/docs/dox/html -name \*.md5 -delete # # test # ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS))) # the testsockets test will fail on vservers (no 127.0.0.1) or if ipv6 is # enabled in the kernel but not configured on any interface IGNORE_TESTSOCK = $(shell IGN=false; \ /sbin/ifconfig|grep -q 127.0.0.1 || IGN=true; \ grep -q ipv6 /proc/net/protocols && ( /sbin/ifconfig|grep -q inet6 || IGN=true ) ; \ echo $$IGN ) override_dh_auto_test: $(MAKE) -C $(BUILDDIR)/test -j$(NUMJOBS) all cd $(BUILDDIR)/test && ./testall -v testsockets testsock || $(IGNORE_TESTSOCK) cd $(BUILDDIR)/test && ( ulimit -S -s 8192 ; ./testall -v testatomic) cd $(BUILDDIR)/test && ./testall -v -x testsockets testsock testatomic else override_dh_auto_test: endif # # install # override_dh_auto_install: dh_auto_install --destdir=debian/tmp perl -p -i -e "s,^dependency_libs=.*,dependency_libs=''," debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/libapr-1.la # Remove hostname to make build reproducible perl -p -i -e 's/Libtool was configured on host.*//' debian/tmp/usr/share/apr-1.0/build/libtool if ! head -n 1 debian/tmp/usr/share/apr-1.0/build/libtool | grep -q /bin/bash ; then \ echo ERROR: The built libtool uses /bin/sh instead of /bin/bash ; \ exit 1 ; \ fi override_dh_strip: dh_strip --dbg-package=libapr1-dbg override_dh_makeshlibs: dh_makeshlibs -- -Idebian/symbols.$(DEB_HOST_ARCH_OS) override_dh_auto_clean: dh_auto_clean rm -rf $(BUILDDIR) for f in $(SAVE_FILES) ; do [ ! -e $$f.dr-orig ] || mv $$f.dr-orig $$f ; done <file_sep>#! /usr/bin/bash source env.sh cd $DEP/basic/cmake-3.5.1/ ./configure --prefix=/usr/ gmake make install <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/roscpp/include/roscpp/SetLoggerLevel.h<file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/roslisp/etc/catkin/profile.d/99.roslisp.sh<file_sep>#!/usr/bin/make -f DH_VERBOSE=1 PY2VERS=$(shell pyversions -vr debian/control) PY3VERS=$(shell py3versions -vr) PYDEF=$(shell pyversions -dv) PY3DEF=$(shell py3versions -dv) PYLIBPATH := $(shell python -c "from distutils.command.build import build ; from distutils.core import Distribution ; b = build(Distribution()) ; b.finalize_options() ; print b.build_platlib") # Look at #634012 to understand why is needed and what will happen if we set # compat to 9 unexport LDFLAGS export ATLAS=None %: dh $@ --with python2,python3 override_dh_auto_build: cd numpy/random/mtrand && python generate_mtrand_c.py dh_auto_build set -e; for v in $(PY3VERS); do \ python$$v setup.py build; \ python$$v-dbg setup.py build; \ done override_dh_auto_clean: rm -rf build/ rm -rf `find -name build -type d` rm -rf `find . -name "*.pyc" -type f` rm -rf doc/fontList.cache numpy/f2py/docs/usersguide/index.html rm -rf doc/source/reference/generated # cython generated rm -f numpy/random/mtrand/mtrand.c override_dh_installman: dh_installman -ppython-numpy doc/f2py/f2py.1 dh_installman -ppython3-numpy doc/f2py/f2py.1 -mv debian/python3-numpy/usr/share/man/man1/f2py.1 \ debian/python3-numpy/usr/share/man/man1/f2py3.1 # link manpage for versioned and dbg incarnations of f2py set -e; for v in $(PY2VERS); do \ dh_link /usr/share/man/man1/f2py.1.gz /usr/share/man/man1/f2py$$v.1.gz; \ dh_link -ppython-numpy-dbg /usr/share/man/man1/f2py.1.gz /usr/share/man/man1/f2py$$v-dbg.1.gz; \ done set -e; for v in $(PY3VERS); do \ dh_link -ppython3-numpy /usr/share/man/man1/f2py3.1.gz /usr/share/man/man1/f2py$$v.1.gz; \ dh_link -ppython3-numpy-dbg /usr/share/man/man1/f2py3.1.gz /usr/share/man/man1/f2py$$v-dbg.1.gz; \ done dh_link -ppython-numpy-dbg /usr/share/man/man1/f2py.1.gz /usr/share/man/man1/f2py-dbg.1.gz; dh_link -ppython3-numpy-dbg /usr/share/man/man1/f2py3.1.gz /usr/share/man/man1/f2py3-dbg.1.gz; override_dh_install: # add shebang information to f2py script set -e; for v in $(PY2VERS) $(PY3VERS); do \ sed -i "1s,#!.*python[^ ]*\(.*\),#!/usr/bin/python$$v," debian/tmp/usr/bin/f2py$$v; \ cp -a debian/tmp/usr/bin/f2py$$v debian/tmp/usr/bin/f2py$$v-dbg ; \ sed -i "1s,#!.*python[^ ]*\(.*\),#!/usr/bin/python$$v-dbg," debian/tmp/usr/bin/f2py$$v-dbg; \ done # install unversioned f2py script cp -a debian/tmp/usr/bin/f2py$(PYDEF) debian/tmp/usr/bin/f2py sed -i "1s,#!.*python[^ ]*\(.*\),#!/usr/bin/python," debian/tmp/usr/bin/f2py cp -a debian/tmp/usr/bin/f2py$(PYDEF)-dbg debian/tmp/usr/bin/f2py-dbg sed -i "1s,#!.*python[^ ]*\(.*\),#!/usr/bin/python-dbg," debian/tmp/usr/bin/f2py-dbg cp -a debian/tmp/usr/bin/f2py$(PY3DEF) debian/tmp/usr/bin/f2py3 sed -i "1s,#!.*python[^ ]*\(.*\),#!/usr/bin/python3," debian/tmp/usr/bin/f2py3 cp -a debian/tmp/usr/bin/f2py$(PY3DEF)-dbg debian/tmp/usr/bin/f2py3-dbg sed -i "1s,#!.*python[^ ]*\(.*\),#!/usr/bin/python3-dbg," debian/tmp/usr/bin/f2py3-dbg dh_install # remove files installed from .install (that's due to the dir listed there) -find $(CURDIR)/debian/python-numpy/ -name "*_d.so" -delete # create symlinks for .h files dh_link -ppython-numpy usr/lib/python$(PYDEF)/dist-packages/numpy/core/include/numpy usr/include/numpy; set -e; for i in $(PY2VERS); do \ [ -d $(CURDIR)/debian/python-numpy/usr/include/python$$i ] || \ mkdir -p $(CURDIR)/debian/python-numpy/usr/include/python$$i; \ dh_link -ppython-numpy usr/lib/python$$i/dist-packages/numpy/core/include/numpy usr/include/python$$i/numpy; \ done set -e; for i in $(PY2VERS); do \ [ -d $(CURDIR)/debian/python-numpy-dbg/usr/include/python$${i}_d ] || \ mkdir -p $(CURDIR)/debian/python-numpy-dbg/usr/include/python$${i}_d; \ dh_link -ppython-numpy-dbg usr/lib/python$$i/dist-packages/numpy/core/include/numpy usr/include/python$${i}_d/numpy; \ done # Python 3 set -e; for i in $(PY3VERS); do \ ABITAG=`python$$i -c "import sys; print(sys.abiflags)"`; \ [ -d $(CURDIR)/debian/python3-numpy/usr/include/python$$i$$ABITAG ] || \ mkdir -p $(CURDIR)/debian/python3-numpy/usr/include/python$$i$$ABITAG; \ dh_link -ppython3-numpy usr/lib/python3/dist-packages/numpy/core/include/numpy usr/include/python$$i$$ABITAG/numpy; \ done set -e; for i in $(PY3VERS); do \ ABITAG=`python$$i-dbg -c "import sys; print(sys.abiflags)"`; \ [ -d $(CURDIR)/debian/python3-numpy-dbg/usr/include/python$${i}$$ABITAG ] || \ mkdir -p $(CURDIR)/debian/python3-numpy-dbg/usr/include/python$${i}$$ABITAG; \ dh_link -ppython3-numpy-dbg usr/lib/python3/dist-packages/numpy/core/include/numpy/ usr/include/python$${i}$$ABITAG/numpy; \ done # share -dbg and normal package doc dirs rm -rf debian/python-numpy-dbg/usr/share/doc/python-numpy-dbg dh_link -ppython-numpy-dbg usr/share/doc/python-numpy usr/share/doc/python-numpy-dbg rm -rf debian/python3-numpy-dbg/usr/share/doc/python3-numpy-dbg dh_link -ppython3-numpy-dbg usr/share/doc/python3-numpy usr/share/doc/python3-numpy-dbg override_dh_gencontrol: python debian/versions.helper >> debian/python-numpy.substvars python debian/versions3.helper >> debian/python3-numpy.substvars dh_gencontrol override_dh_compress: dh_compress -X.js -Xobjects.inv -X.txt override_dh_strip: ifeq (,$(filter nostrip,$(DEB_BUILD_OPTIONS))) dh_strip -ppython-numpy --dbg-package=python-numpy-dbg dh_strip -ppython3-numpy --dbg-package=python3-numpy-dbg # dh_strip seemingly doesn't catch the PEP 3149-style debug names rm debian/python3-numpy/usr/lib/python3*/*-packages/*/*/*.cpython-3?d*.so endif override_dh_python2: dh_python2 -v # avoid lintian autoreject -mv debian/python-numpy/usr/share/pyshared/numpy/core/lib/libnpymath.a \ debian/python-numpy/usr/lib/python2.7/dist-packages/numpy/core/lib/libnpymath.a override_dh_installdocs-indep: dh_installdocs -i dh_sphinxdoc -i build: build-arch build-indep ; build-arch: dh build --with=python2,python3 build-indep: # build doc only for default python version (export MPLCONFIGDIR=. ; make -C doc html PYTHONPATH=../$(PYLIBPATH)) update_intersphinx_mapping: wget http://docs.python.org/dev/objects.inv -O debian/python.org_objects.inv override_dh_auto_install: dh_auto_install # Install for Python 3 set -e; for v in $(PY3VERS); do \ python$$v setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb; \ python$$v-dbg setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb; \ done # yes, we need to run tests after install # The reason is that numpy tries hard to not let you run it from the # source directory, so we need to mess with the import order so to # select the code in the installation path ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS))) set -e; for v in $(PY2VERS) ; do \ echo "-- running tests for "$$v" plain --" ; \ python$$v -c "import sys ; sys.path.insert(0, '$(CURDIR)/debian/tmp/usr/lib/python$$v/dist-packages/') ; import numpy; numpy.test(verbose=5)" ; \ echo "-- running tests for "$$v" debug --" ; \ python$$v-dbg -c "import sys ; sys.path.insert(0, '$(CURDIR)/debian/tmp/usr/lib/python$$v/dist-packages/') ; import numpy; numpy.test(verbose=5)" ; \ done # Python 3.2 maps to python3/ dir alone? bah set -e; for v in $(PY3VERS) ; do \ echo "-- running tests for "$$v" plain --" ; \ python$$v -c "import sys ; sys.path.insert(0, '$(CURDIR)/debian/tmp/usr/lib/python3/dist-packages/') ; import numpy; numpy.test(verbose=5)" ; \ echo "-- running tests for "$$v" debug --" ; \ python$$v-dbg -c "import sys ; sys.path.insert(0, '$(CURDIR)/debian/tmp/usr/lib/python3/dist-packages/') ; import numpy; numpy.test(verbose=5)" ; \ done endif <file_sep>#! /usr/bin/bash cd "$(dirname "$0")" ./gtest_build.sh ./googlemock_build.sh ./apr_build.sh ./bzip2_build.sh ./lz4_build.sh ./openssl_build.sh ./log4cxx_build.sh ./console_bridge_build.sh ./tinyxml_build.sh <file_sep>#!/bin/sh set -efu PYS=${PYS:-"$(pyversions -r 2>/dev/null)"} TESTPKG=${TESTPKG:-numpy} cd "$ADTTMP" for py in $PYS; do echo "=== $py ===" $py -c "import $TESTPKG; $TESTPKG.test(verbose=2)" 2>&1 done <file_sep>/home/parallels/Desktop/compare2/kinetic/devel/.private/geneus/share/geneus/cmake/geneusConfig.cmake<file_sep> import pip installed_packages=pip.get_installed_distributions() installed_packages_list=sorted(["%s==%s" % (i.key,i.version) for i in installed_packages]) print(installed_packages_list) <file_sep>#!/usr/bin/make -f include ../common.mk DPY=$(DEBPYTHON_DEFAULT) check: grep -q "pycompile -p python-foo /usr/lib/python-foo -V $(DPY)"\ debian/python-foo/DEBIAN/postinst test -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/bar.so test ! -f debian/python-foo/usr/share/pyshared/foo/bar.so test -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/spam.so test ! -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/spam.so.0.1 test -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/baz.so test ! -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/baz.so.0.1 test ! -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/baz.so.0.1.2 test -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/quux.so test ! -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/quux.so.0 test ! -L debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/quux.so.0 test ! -f debian/python-foo/usr/lib/python${DPY}/dist-packages/foo/quux.so.0.0.0 clean: clean-common rm -rf lib/Foo.egg-info build <file_sep># /usr/bin/bash cd $(dirname "$0") source ./env.sh cd $DEP/utils/console-bridge-0.3.2 mkdir /usr/src/gtest/ cp -r test/gtest/* /usr/src/gtest/ cmake -DCMAKE_INSTALL_PREFIX=/usr make -j32 make test make install <file_sep># ROS Cross Platform Porting Guide The whole stack of ROS software have a complicated dependency tree. With the benefit of good design in ROS philosophy we can port the ROS to the non-official platform and architecture. The keypoint of porting work is figuring out dependency hell. it generally means the whole software should be built from source. Yeah,Cook By Yourself. ROS software can be group to 4 parts -- python package , include compile utility and ROS python package. -- ROS C/C++ package, we can utilize catkin tools to do some parallel compiling work. -- The toolchain,which include GCC,Steel-Bank Common Lisp,etc. 1, prepare basic tools *./script/init.sh* 2, build toolchain (optional) *./toolchain/gcc_download_build.sh* 3, build dependencies *./script/basic_build.sh* *./script/python_pkg_build.sh* *./script/utils_build.sh* 4, build ROS *./build.sh* <file_sep>#! /usr/bin/python # -*- coding: UTF-8 -*- try: from setuptools import setup, find_packages except ImportError: exit() setup(name='Foo', version=0.1, description="Foo to rule them all", long_description="TODO", keywords='foo bar baz', author='<NAME>', author_email='<EMAIL>', url='http://www.debian.org/', license='MIT', package_dir={'': 'lib'}, packages=find_packages('lib/'), package_data = {'foo': ['jquery.js']}, zip_safe=False, install_requires = ['Mako', 'SQLAlchemy >=0.5', 'Baz [extras]'], )
ca7d6214ce0fa33e71d2f5c0f1a8bcb661600c9d
[ "CMake", "reStructuredText", "Markdown", "Makefile", "Python", "C", "Shell" ]
104
Makefile
GitBubble/bootstrap-ros
0c52cf0c13b100d8ac09eba7d5235aff7457b09e
2a7bde66fb552079e7069952a17708b02d221f88
refs/heads/master
<repo_name>early-in-career/databases<file_sep>/server/models/index.js console.log('ola!'); var db = require('../db'); //refactor the query function => DRY fool module.exports = { messages: { //this will modify the data in the data base get: function(callback) { //fetch messages // need to get: id, text, room name, username; var querryString = 'select messages.id, users.username, messages.message, messages.roomname from messages left outer join users on (messages.username = users.id) order by messages.id desc'; //left outer join takes everything from the left table and matches from the right table (will load all messages even if there isn't a match to the user table) db.query(querryString, function (err, results) { //callback needs to be a parameter in the get method callback(results); }); }, post: function (params, callback) { //create a message var querryString = 'INSERT INTO messages(username, message, roomname) values ((select id from users where users.id = ?), ?, ?)'; db.query(querryString, params, function(err) { if (err) { console.log(err); } else { callback(results); } }); } }, users: { get: function (callback) { //fetch all users var querryString = 'SELECT * FROM users'; db.query(querryString, function (err, results) { //error handling? //node callbacks take call a callback on the results if no error ==> the get request must take a callback function callback(results); // doooo something // res.end(JSON.stringify()); }); }, post: function (params, callback) { //create a user var querryString = 'INSERT INTO users(username) values (?)'; db.query(querryString, params, function(err) { if (err) { console.log(err); } else { callback(results); } }); } } };<file_sep>/server/controllers/index.js var models = require('../models'); var express = require('express'); //do we need to require parser here? /* bodyparser methods .text --> parses bodies to strings req.body --> new body containing parsed data populated on the request object */ module.exports = { messages: { //will handle requests and signal changes to the model get: function (req, res) { //.complete invoked when query completed (kind of like a promise) //in find all, instruct orm to include the user model in the fetch //performs a left outer join by default (with the word include) //noteL if the user model had a property called required set to true ==> inner join Message.findAll( {include: [User]} ).complete(function(error, result) { res.json(result); }); }, post: function (req, res) { //sequilize expects the on object with all the parameters we want to build User.findOrCreate({username: req.body.username}).complete(function(error, user) { var params = { //username needs to rep user ID ==> interact with user table //need a step prior to the params assignment to fetch the user id based on the provided user name //the result, or user is the user object ==> can access the id from the db info userid: user.id, message: req.body[message], roomname: req.body[roomname] }; Message.create(params).complete(function (error, result) { res.json(result); }); }); } }, users: { get: function (req, res) { //don't need to iunclude the user since we are only dealing with user User.findAll().complete(function (error, result) { res.json(result); }); }, post: function (req, res) { var params = {username: req.body[username]}; User.create(params).complete(function(error, user) { res.sendStatus(201); }); // var params = [req.body.username]; // models.users.post(params, function(err, response) { // res.json(response); // }); } } }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////OLD VERSION/////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // module.exports = { // messages: { // //will handle requests and signal changes to the model // get: function (req, res) { // models.messages.get(function(err, response) { // //response should return a json of the results (from the model's query) // //sends a json response (use instead of res.end()) // res.json(response); // }); // }, // post: function (req, res) { // //sql expects the parameters to be in the form of an array // //they can be accessed via kv pairs of the req.body object; // var params = [req.body[username], req.body[message], req.body[roomname]]; // models.messages.post(params, function(err, response) { // res.json(response); // }); // } // }, // users: { // get: function (req, res) { // models.users.get(function(err, response) { // //also want to send back a json of the result from the model's query // res.json(response); // }); // }, // post: function (req, res) { // var params = [req.body.username]; // models.users.post(params, function(err, response) { // res.json(response); // }); // } // } // };<file_sep>/server/db/index.js var Sequilize = require('Sequilize'); var orm = new Sequilize('chat', 'root', ''); //database, username, password; //orm creates intuitive rep of the data //create an orm user object: var User = orm.define('User', { username: Sequilize.STRING }); //create an orm Message object: var Message = orm.define('Message', { message: Sequilize.STRING, roomname: Sequilize.STRING }); //declare relationship between the two: User.hasMany(Messages); //belongs to tells the orm where the foreign keys are Message.belongsTo(User); //synchronize the data base with the schema we have created: User.sync(); Message.sync(); //export them: exports.User = User; exports.Message = Message; //////////////////////////////////////////////////////////////////////////////// //////////////////////////OLD VERSION/////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // var mysql = require('mysql'); // // Create a database connection and export it from this file. // // You will need to connect with the user "root", no password, // // and to the database "chat". // var dbConnection = mysql.createConnection({ // user: 'root', // password: '', // database: 'chat' // }); // dbConnection.connect(function(err) { // //basically if there is an error with the connection, throw the error // if (err) { // throw err; // } // //otherwise, tell us that we have connected! // console.log('you are now connected!'); // }); // // dbConnection.query('select * from user', function(err, results, fields) { // // if (err) { // // console.log(err); // // } else { // // console.log(results); // // } // // }); // module.exports = dbConnection;
53000f7e3cc7825cb401c80e753f3643755fac05
[ "JavaScript" ]
3
JavaScript
early-in-career/databases
893513cf44e77d1848d2cfca3c373600abfedb9b
6cad5b67f287a02662cf93383aab5deb2040278a
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>${groupId}</groupId> <artifactId>${artifactId}</artifactId> <version>${version}</version> <packaging>pom</packaging> <name>Playground OSGi</name> <description>Playground for OSGi realted stuff</description> <inceptionYear>2019</inceptionYear> <organization> <name>maggu2810</name> <url>https://www.maggu2810.de/</url> </organization> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> </license> </licenses> <scm> <connection>scm:git:git@github.com:maggu2810/playground-osgi.git</connection> <developerConnection>scm:git:git@github.com:maggu2810/playground-osgi.git</developerConnection> <tag>HEAD</tag> <url>https://github.com/maggu2810/playground-osgi</url> </scm> <issueManagement> <system>Gitlab</system> <url>https://github.com/maggu2810/playground-osgi/issues</url> </issueManagement> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <my.java.version>11</my.java.version> <maven.compiler.source>${my.java.version}</maven.compiler.source> <maven.compiler.target>${my.java.version}</maven.compiler.target> <maven.compiler.compilerVersion>${my.java.version}</maven.compiler.compilerVersion> <bnd.version>5.1.1</bnd.version> </properties> <repositories> <!-- Maven Central --> <!-- Use this first, so we prefer Central all the time --> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>Maven Repository Switchboard</name> <url>https://repo1.maven.org/maven2</url> </repository> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>bintray-maggu2810-maven</id> <url>https://dl.bintray.com/maggu2810/maven/</url> </repository> </repositories> <pluginRepositories> <!-- Maven Central --> <!-- Use this first, so we prefer Central all the time --> <pluginRepository> <releases> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>Maven Plugin Repository</name> <url>https://repo1.maven.org/maven2</url> </pluginRepository> </pluginRepositories> <build> <pluginManagement> <plugins> <!-- BEG: bnd --> <!-- Use the bnd-maven-plugin and assemble the symbolic names --> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-maven-plugin</artifactId> <version>${bnd.version}</version> <configuration> <bnd>-exportcontents: \ !*.internal.*,\ !*.impl.*, \ de.maggu2810.playground.osgi.* -sources: false -contract: *</bnd> </configuration> <executions> <execution> <goals> <goal>bnd-process</goal> </goals> </execution> </executions> </plugin> <!-- Required to make the maven-jar-plugin pick up the bnd generated manifest. Also avoid packaging empty Jars --> <!-- Moved... --> <!-- Setup the indexer for running and testing --> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-indexer-maven-plugin</artifactId> <version>${bnd.version}</version> <configuration> <localURLs>REQUIRED</localURLs> <attach>false</attach> </configuration> <executions> <execution> <id>index</id> <goals> <goal>index</goal> </goals> <configuration> <indexName>${project.artifactId}</indexName> </configuration> </execution> <execution> <id>test-index</id> <goals> <goal>index</goal> </goals> <configuration> <indexName>${project.artifactId}</indexName> <outputFile>${project.build.directory}/test-index.xml</outputFile> <scopes> <scope>test</scope> </scopes> </configuration> </execution> </executions> </plugin> <!-- Define the version of the resolver plugin we use --> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-resolver-maven-plugin</artifactId> <version>${bnd.version}</version> <configuration> <failOnChanges>false</failOnChanges> <bndruns></bndruns> </configuration> <executions> <execution> <goals> <goal>resolve</goal> </goals> </execution> </executions> </plugin> <!-- Define the version of the export plugin we use --> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-export-maven-plugin</artifactId> <version>${bnd.version}</version> <configuration> <resolve>true</resolve> <failOnChanges>true</failOnChanges> </configuration> <executions> <execution> <goals> <goal>export</goal> </goals> </execution> </executions> </plugin> <!-- Define the version of the testing plugin that we use --> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-testing-maven-plugin</artifactId> <version>${bnd.version}</version> <executions> <execution> <goals> <goal>testing</goal> </goals> </execution> </executions> </plugin> <!-- Define the version of the baseline plugin we use and avoid failing when no baseline jar exists. (for example before the first release) --> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-baseline-maven-plugin</artifactId> <version>${bnd.version}</version> <configuration> <failOnMissing>false</failOnMissing> </configuration> <executions> <execution> <goals> <goal>baseline</goal> </goals> </execution> </executions> </plugin> <!-- END: bnd --> <!-- BEG: official ones --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <version>3.0.0-M2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> <configuration> <archive> <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile> </archive> <skipIfEmpty>true</skipIfEmpty> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.3</version> <configuration> <failOnError>!${quality.skip}</failOnError> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <version>3.6.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.2</version> <configuration> <preparationGoals>clean install</preparationGoals> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>3.0.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> </plugin> <!-- END: official ones --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.9.1</version> </plugin> <plugin> <groupId>org.apache.karaf.tooling</groupId> <artifactId>karaf-maven-plugin</artifactId> <version>${karaf.version}</version> <extensions>true</extensions> </plugin> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> <version>2.10.0</version> <configuration> <predefinedSortOrder>recommended_2008_06</predefinedSortOrder> <createBackupFile>false</createBackupFile> <keepBlankLines>true</keepBlankLines> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.commonjava.maven.plugins</groupId> <artifactId>directory-maven-plugin</artifactId> <version>0.1</version> <executions> <execution> <id>directories</id> <goals> <goal>highest-basedir</goal> </goals> <phase>initialize</phase> <configuration> <property>basedirRoot</property> </configuration> </execution> </executions> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.5</version> </plugin> </plugins> </reporting> <profiles> <profile> <id>with-bnd-resolver-resolve</id> <activation> <property> <name>withResolver</name> </property> </activation> <build> <pluginManagement> <plugins> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-resolver-maven-plugin</artifactId> <version>${bnd.version}</version> <executions> <execution> <goals> <goal>resolve</goal> </goals> <phase>package</phase> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> </profile> <profile> <id>bnd-testing-on-check-only</id> <activation> <property> <name>!check</name> </property> </activation> <build> <pluginManagement> <plugins> <plugin> <groupId>biz.aQute.bnd</groupId> <artifactId>bnd-testing-maven-plugin</artifactId> <version>${bnd.version}</version> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </pluginManagement> </build> </profile> <profile> <id>check-base</id> <activation> <property> <name>check</name> </property> </activation> <properties> <license.skipUpdateLicense>false</license.skipUpdateLicense> <spotbugs.version>3.1.6</spotbugs.version> <pmd.version>6.5.0</pmd.version> <quality.spotbugs.skip>${quality.skip}</quality.spotbugs.skip> </properties> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>3.1.0</version> <configuration> <skip>${quality.skip}</skip> <configLocation>${basedirRoot}/quality/checkstyle/checkstyle.xml</configLocation> <propertyExpansion>config_loc=${basedirRoot}/quality/checkstyle</propertyExpansion> <violationSeverity>info</violationSeverity> </configuration> <dependencies> <dependency> <groupId>com.puppycrawl.tools</groupId> <artifactId>checkstyle</artifactId> <version>8.29</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.10.0</version> <configuration> <skip>${quality.skip}</skip> <linkXRef>false</linkXRef> <rulesets> <ruleset>${basedirRoot}/quality/pmd/pmd_ruleset.xml</ruleset> </rulesets> </configuration> <dependencies> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-core</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-java</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-javascript</artifactId> <version>${pmd.version}</version> </dependency> <dependency> <groupId>net.sourceforge.pmd</groupId> <artifactId>pmd-jsp</artifactId> <version>${pmd.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-maven-plugin</artifactId> <version>${spotbugs.version}</version> <configuration> <skip>${quality.spotbugs.skip}</skip> <plugins> <plugin> <!-- https://github.com/KengoTODA/findbugs-slf4j --> <groupId>jp.skypencil.findbugs.slf4j</groupId> <artifactId>bug-pattern</artifactId> <version>1.4.2</version> </plugin> </plugins> <findbugsXmlOutput>true</findbugsXmlOutput> <findbugsXmlWithMessages>true</findbugsXmlWithMessages> <xmlOutput>true</xmlOutput> <effort>Max</effort> <threshold>Low</threshold> <maxRank>20</maxRank> <excludeFilterFile>${basedirRoot}/quality/findbugs/findbugs_exclude.xml</excludeFilterFile> </configuration> <dependencies> <!-- overwrite dependency on spotbugs if you want to specify the version of spotbugs --> <dependency> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs</artifactId> <version>${spotbugs.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>license-maven-plugin</artifactId> <version>1.16</version> <configuration> <licenseName>apache_v2</licenseName> <!--<licenseResolver>file:///${basedirRoot}/quality/licenses</licenseResolver> --> <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage> <emptyLineAfterHeader>true</emptyLineAfterHeader> <ignoreNoFileToScan>true</ignoreNoFileToScan> </configuration> <executions> <execution> <goals> <goal>update-file-header</goal> </goals> <phase>process-sources</phase> <configuration> <includes> <include>**/*.java</include> </includes> <excludes> <exclude>**/feature.xml</exclude> <exclude>**/jquery-*.js</exclude> <exclude>**/propeller.js</exclude> <exclude>**/sockjs-*.min.js</exclude> <exclude>**/stomp.js</exclude> </excludes> <canUpdateCopyright>true</canUpdateCopyright> <canUpdateDescription>true</canUpdateDescription> <canUpdateLicense>true</canUpdateLicense> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.github.dantwining.whitespace-maven-plugin</groupId> <artifactId>whitespace-maven-plugin</artifactId> <version>1.0.4</version> <executions> <execution> <goals> <goal>trim</goal> </goals> <phase>process-sources</phase> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> </profile> <profile> <id>check-sortpom</id> <activation> <property> <name>check</name> </property> </activation> <build> <pluginManagement> <plugins> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> <executions> <execution> <id>sortpom-verify</id> <goals> <goal>verify</goal> </goals> <phase>verify</phase> <configuration> <verifyFail>Stop</verifyFail> </configuration> </execution> </executions> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> </plugin> </plugins> </build> </profile> <profile> <id>check-buildsystem</id> <activation> <property> <name>check</name> <value>buildsystem</value> </property> </activation> <properties> <license.skipUpdateLicense>true</license.skipUpdateLicense> </properties> <build> <defaultGoal>clean install spotbugs:spotbugs pmd:pmd pmd:cpd checkstyle:checkstyle javadoc:javadoc</defaultGoal> </build> </profile> <profile> <id>check-gitlab</id> <activation> <property> <name>check</name> <value>gitlab</value> </property> </activation> <properties> <license.skipUpdateLicense>true</license.skipUpdateLicense> </properties> <build> <defaultGoal>clean install spotbugs:check pmd:check checkstyle:check javadoc:javadoc</defaultGoal> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>license-maven-plugin</artifactId> <configuration> <dryRun>true</dryRun> <failOnNotUptodateHeader>true</failOnNotUptodateHeader> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>check-commit</id> <activation> <property> <name>check</name> <value>commit</value> </property> </activation> <build> <defaultGoal>sortpom:sort clean install spotbugs:check pmd:check checkstyle:check javadoc:javadoc</defaultGoal> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>license-maven-plugin</artifactId> </plugin> <plugin> <groupId>com.github.dantwining.whitespace-maven-plugin</groupId> <artifactId>whitespace-maven-plugin</artifactId> </plugin> </plugins> </build> </profile> <profile> <id>repos-apache-snapshots</id> <activation> <property> <name>karaf-snapshot</name> </property> </activation> <repositories> <repository> <releases> <enabled>false</enabled> </releases> <snapshots> </snapshots> <id>apache-snapshots</id> <url>https://repository.apache.org/snapshots/</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <releases> <enabled>false</enabled> </releases> <snapshots> </snapshots> <id>apache-snapshots</id> <url>https://repository.apache.org/snapshots/</url> </pluginRepository> </pluginRepositories> </profile> <profile> <id>karaf-4.2.8-staging</id> <activation> <property> <name>karaf</name> <value>4.2.8-staging</value> </property> </activation> <properties> <karaf.repo.staging>https://repository.apache.org/content/repositories/orgapachekaraf-1138/</karaf.repo.staging> <karaf.version>4.2.8</karaf.version> <hibernate.version>5.4.8.Final</hibernate.version> <jetty.version>9.4.22.v20191022</jetty.version> <pax.web.version>7.2.14</pax.web.version> <pax.jdbc.version>1.4.4</pax.jdbc.version> </properties> <repositories> <repository> <id>karaf-4.2.8-staging</id> <url>${karaf.repo.staging}</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>karaf-4.2.8-staging</id> <url>${karaf.repo.staging}</url> </pluginRepository> </pluginRepositories> </profile> <profile> <id>karaf-current</id> <activation> <property> <name>!karaf</name> </property> </activation> <properties> <karaf.version>4.2.8</karaf.version> <hibernate.version>5.4.8.Final</hibernate.version> <jetty.version>9.4.22.v20191022</jetty.version> <pax.web.version>7.2.14</pax.web.version> <pax.jdbc.version>1.4.4</pax.jdbc.version> <pax.logging.version>1.11.4</pax.logging.version> </properties> <dependencyManagement> <dependencies> <!-- BEG: knopflerfish dependency --> <!-- See: https://issues.apache.org/jira/projects/KARAF/issues/KARAF-6462 --> <!-- See: https://lists.apache.org/thread.html/r9296dda9205af512fe063221a8bd91deef567ee08df3195a7a2ff4ba%40%3Cuser.karaf.apache.org%3E --> <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>framework</artifactId> <version>${karaf.version}</version> <type>kar</type> <exclusions> <exclusion> <groupId>org.knopflerfish.kf6</groupId> <artifactId>log-API</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.ops4j.pax.logging</groupId> <artifactId>pax-logging-log4j2</artifactId> <version>1.11.4</version> <exclusions> <exclusion> <groupId>org.knopflerfish.kf6</groupId> <artifactId>log-API</artifactId> </exclusion> </exclusions> </dependency> <!-- END: knopflerfish dependency --> </dependencies> </dependencyManagement> </profile> <!-- BEG: Set 'os.id' --> <profile> <id>os.id</id> <activation> <property> <name>!skipInjectionOfOsId</name> </property> </activation> <properties> <os.id>${os.family}-${os.arch}</os.id> </properties> </profile> <!-- BEGIN: Set the 'os.family' property --> <!-- Valid activation options are (see https://maven.apache.org/enforcer/enforcer-rules/requireOS.html): --> <!-- dos, mac, netware, os/2, tandem, unix, windows, win9x, z/os, os/400 --> <profile> <id>os.family.mac</id> <activation> <os> <family>mac</family> </os> </activation> <properties> <os.family>mac</os.family> </properties> </profile> <profile> <id>os.family.unix</id> <activation> <os> <family>unix</family> </os> </activation> <properties> <os.family>unix</os.family> </properties> </profile> <profile> <id>os.family.windows</id> <activation> <os> <family>windows</family> </os> </activation> <properties> <os.family>windows</os.family> </properties> </profile> <!-- END: Set 'os.id' --> <profile> <id>only-eclipse</id> <activation> <property> <name>m2e.version</name> </property> </activation> <build> <pluginManagement> </pluginManagement> </build> </profile> </profiles> </project> <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>${groupId}.karaf</groupId> <artifactId>${rootArtifactId}.karaf</artifactId> <version>${version}</version> </parent> <groupId>${groupId}.karaf.dists</groupId> <artifactId>${artifactId}</artifactId> <packaging>pom</packaging> <dependencies> <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>framework</artifactId> <version>${karaf.version}</version> <type>kar</type> </dependency> <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>standard</artifactId> <version>${karaf.version}</version> <classifier>features</classifier> <type>xml</type> </dependency> <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>framework</artifactId> <version>${karaf.version}</version> <classifier>features</classifier> <type>xml</type> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.karaf.features</groupId> <artifactId>enterprise</artifactId> <version>${karaf.version}</version> <classifier>features</classifier> <type>xml</type> <scope>runtime</scope> </dependency> </dependencies> </project> <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>de.maggu2810.maven.archetypes</groupId> <artifactId>osgi-project-archetype</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>maven-archetype</packaging> <name>OSGi Project Archetype</name> <description>Archetype for OSGi projects</description> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> </license> </licenses> <scm> <connection>scm:git:git@github.com:maggu2810/osgi-project-archetype.git</connection> <developerConnection>scm:git:git@github.com:maggu2810/osgi-project-archetype.git</developerConnection> <tag>HEAD</tag> <url>https://github.com/maggu2810/osgi-project-archetype</url> </scm> <issueManagement> <system>GitHub</system> <url>https://github.com/maggu2810/osgi-project-archetype/issues</url> </issueManagement> <distributionManagement> <repository> <id>bintray</id> <url>https://api.bintray.com/maven/maggu2810/maven/osgi-project-archetype</url> </repository> <snapshotRepository> <id>bintray</id> <url>https://oss.jfrog.org/artifactory/simple/oss-snapshot-local/</url> </snapshotRepository> </distributionManagement> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <build> <pluginManagement> <plugins> <plugin> <artifactId>maven-archetype-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> <version>3.0.0-M2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.10.3</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <version>3.6.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.2</version> <configuration> <preparationGoals>clean install</preparationGoals> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> <configuration> <addDefaultExcludes>false</addDefaultExcludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>3.0.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> </plugin> </plugins> </pluginManagement> <extensions> <extension> <groupId>org.apache.maven.archetype</groupId> <artifactId>archetype-packaging</artifactId> <version>2.4</version> </extension> </extensions> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>2.5</version> </plugin> </plugins> </reporting> <profiles> <profile> <id>check-base</id> <activation> <property> <name>check</name> </property> </activation> <build> <pluginManagement> <plugins> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> <version>2.10.0</version> <configuration> <predefinedSortOrder>recommended_2008_06</predefinedSortOrder> <createBackupFile>false</createBackupFile> <keepBlankLines>true</keepBlankLines> </configuration> <executions> <execution> <id>sortpom-verify</id> <goals> <goal>verify</goal> </goals> <phase>verify</phase> <configuration> <verifyFail>Stop</verifyFail> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.github.dantwining.whitespace-maven-plugin</groupId> <artifactId>whitespace-maven-plugin</artifactId> <version>1.0.4</version> <executions> <execution> <goals> <goal>trim</goal> </goals> <phase>process-sources</phase> </execution> </executions> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep># osgi-project-archetype ## build archetype ``` mvn clean install ``` ## create project from archetype ``` mvn archetype:generate \ -DarchetypeGroupId=de.maggu2810.maven.archetypes \ -DarchetypeArtifactId=osgi-project-archetype \ -DarchetypeVersion=1.0.0-SNAPSHOT \ -DgroupId=tmp1.tmp2.tmp3 \ -DartifactId=tmp4.tmp5.tmp6 \ -Dversion=1.0.0-SNAPSHOT \ -Dpackage=tmp7.tmp8.tmp9 ``` <file_sep>#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) /*- * ${symbol_pound}%L * ${groupId}.bundles.dummy * %% * Copyright (C) 2019 maggu2810 * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ${symbol_pound}L% */ package ${package}.jfx.standalone.main; import java.util.List; import java.util.Map; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class HelloFX extends Application { private static void keepDim(final Stage stage, final Scene scene) { final double stageHeight = stage.getHeight(); final double stageWidth = stage.getWidth(); stage.setScene(scene); stage.setHeight(stageHeight); stage.setWidth(stageWidth); } @Override public void init() throws Exception { final Parameters params = getParameters(); final Map<String, String> named = params.getNamed(); final List<String> unnamed = params.getUnnamed(); final List<String> raw = params.getRaw(); System.out.printf("named: %s%nunnamed: %s%nraw: %s%n", named, unnamed, raw); } @Override public void start(final Stage stage) { // Instantiating the BorderPane class final BorderPane bPane = new BorderPane(); // Creating a scene object final Scene scene = new Scene(bPane, 640, 480); // Setting title to the Stage stage.setTitle("BorderPane Example"); // Setting the top, bottom, center, right and left nodes to the pane bPane.setTop(new TextField("Top")); bPane.setBottom(new Label(String.format("Hello, JavaFX %s, running on Java %s.", System.getProperty("javafx.version"), System.getProperty("java.version")))); bPane.setLeft(new TextField("Left")); bPane.setRight(new TextField("Right")); final Button testBtn = new Button("test"); testBtn.setOnAction(testBtnEvent -> { System.out.printf("class: %s; %s%n", testBtnEvent.getClass(), testBtnEvent); final Button backBtn = new Button("back"); backBtn.setOnAction(backBtnEvent -> { keepDim(stage, scene); }); keepDim(stage, new Scene(backBtn)); }); bPane.setCenter(testBtn); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } }
6a067042eb4057b425c23e1290be6047752744b6
[ "Markdown", "Java", "Maven POM" ]
5
Maven POM
maggu2810/osgi-project-archetype
01ff0ab1354e2de8830087652da0888b6d24f9b6
dfda5cd5ea71a2855029ebd66d4c159924db3336
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.FCMUtils; using Google.GData.Documents; using Google.GData.Client; using fcm.Windows.Google.Model; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using Utils = MackkadoITFramework.Helper.Utils; namespace fcm.Windows.Google.Model { public class ModelGoogle { //Keeps track of our logged in state. public bool loggedIn = false; //A connection with the DocList API. private DocumentsService service; //The name of the shell context menu option. private const string KEY_NAME = "Send to Google Docs"; //Keeps track of if we've minimized the OptionsForm before. private bool firstMinimize = true; //The timer in milliseconds to display balloon tips. private const int BALLOON_TIMER = 10000; //The most recently uploaded document. private DocumentEntry lastUploadEntry = null; //Keeps track of if the last balloon tip was an upload complete message. private bool lastToolTipWasUpload = false; /// <summary> /// Authenticates to Google servers /// </summary> /// <param name="username">The user's username (e-mail)</param> /// <param name="password">The user's password</param> /// <exception cref="AuthenticationException">Thrown on invalid credentials.</exception> public void Login( string username, string password ) { if (loggedIn) { throw new ApplicationException( "Already logged in." ); } try { service = new DocumentsService( "DocListUploader" ); ((GDataRequestFactory)service.RequestFactory).KeepAlive = false; service.setUserCredentials( username, password ); //force the service to authenticate DocumentsListQuery query = new DocumentsListQuery(); query.NumberToRetrieve = 1; service.Query( query ); loggedIn = true; } catch (AuthenticationException e) { loggedIn = false; service = null; throw e; } } /// <summary> /// Retrieves a list of documents from the server. /// </summary> /// <returns>The list of documents as a DocumentsFeed.</returns> public DocumentsFeed GetDocs() { DocumentsListQuery query = new DocumentsListQuery(); query.ShowFolders = true; DocumentsFeed feed = service.Query( query ); return feed; } public DocumentsFeed GetFolderList(string folderID) { FolderQuery query = new FolderQuery( folderID ); query.ShowFolders = false; DocumentsFeed feed = service.Query(query); return feed; } /// <summary> /// Logs the user out of Google Docs. /// </summary> public void Logout() { loggedIn = false; service = null; } /// <summary> /// Uploads the file to Google Docs /// </summary> /// <param name="fileName">The file with path to upload</param> /// <exception cref="ApplicationException">Thrown when user isn't logged in.</exception> public void UploadFile( string fileName ) { if (!loggedIn) { throw new ApplicationException( "Need to be logged in to upload documents." ); } else { lastUploadEntry = service.UploadDocument( fileName, null ); } } /// <summary> /// Create a new folder with the name folderName inside parent folder with ID destFolderId /// </summary> /// <param name="folderName"> new folder's name </param> /// <param name="destFolderId"> destination folder's ID </param> /// <returns> The ID of the newly created folder </returns> public String CreateFolder( String folderName, String destFolderId ) { AtomCategory category = new AtomCategory( "http://schemas.google.com/docs/2007#folder", new AtomUri( "http://schemas.google.com/g/2005#kind" ) ); category.Label = "folder"; AtomEntry folder = new AtomEntry(); folder.Categories.Add( category ); folder.Title = new AtomTextConstruct( AtomTextConstructElementType.Title, folderName ); Uri feedUri; AtomEntry newFolderEntry; if (destFolderId.Equals( "" )) { feedUri = new Uri( "http://docs.google.com/feeds/documents/private/full" ); newFolderEntry = this.service.Insert( feedUri, folder ); // send request } else { // !! PROBLEM, "Can not update a read-only feed"; URI: "http://docs.google.com/feeds/documents/private/full/folder:0B5S1An4gAziBNGYxOWI1M2ItYzVjNC00MDViLWFiZWYtM2VhZGUzZDRkZmZl/contents" feedUri = new Uri( "http://docs.google.com/feeds/documents/private/full/folder" + "%3A" + destFolderId + "/contents" ); Console.WriteLine( feedUri.ToString() ); AtomFeed feed = new AtomFeed( feedUri, this.service ); newFolderEntry = this.service.Insert( feed, folder ); // send request } //Console.WriteLine(FolderQuery.DocumentId(newFolderEntry.Id.AbsoluteUri)); // String folderId = FolderQuery.DocumentID( newFolderEntry.Id.AbsoluteUri ); String folderId = newFolderEntry.Id.AbsoluteUri; Console.WriteLine( folderId ); return folderId; } public static void LoadGoogleDocsInTree( TreeView tvGoogle, DocumentsFeed feed ) { // Create folders first // foreach (DocumentEntry entry in feed.Entries) { if (!entry.IsFolder) continue; int image = 0; int imageSelected = 0; image = FCMConstant.Image.Folder; imageSelected = FCMConstant.Image.Folder; TreeNode tn = new TreeNode( entry.Title.Text, image, imageSelected ); tvGoogle.Nodes.Add( tn ); tn.Tag = entry; } // Load documents // foreach (DocumentEntry entry in feed.Entries) { if (entry.IsFolder) continue; TreeNode parent = new TreeNode(); parent = tvGoogle.Nodes[0]; foreach (var folder in entry.ParentFolders) { foreach( TreeNode tn in tvGoogle.Nodes) { if (tn.Text == folder.Title) { parent = tn; } } } int image = 0; int imageSelected = 0; string documentType = MackkadoITFramework.Helper.Utils.DocumentType.WORD; if (entry.IsFolder) { documentType = MackkadoITFramework.Helper.Utils.DocumentType.FOLDER; image = FCMConstant.Image.Folder; imageSelected = FCMConstant.Image.Folder; } else { if (entry.IsDocument) { documentType = MackkadoITFramework.Helper.Utils.DocumentType.WORD; image = FCMConstant.Image.Document; imageSelected = FCMConstant.Image.Document; } else { if (entry.IsSpreadsheet) { documentType = Utils.DocumentType.EXCEL; image = FCMConstant.Image.Excel; imageSelected = FCMConstant.Image.Excel; } else { if (entry.IsPDF) { documentType = MackkadoITFramework.Helper.Utils.DocumentType.PDF; image = FCMConstant.Image.PDF; imageSelected = FCMConstant.Image.PDF; } } } } TreeNode child = new TreeNode( entry.Title.Text, image, imageSelected ); child.Tag = entry; parent.Nodes.Add( child ); } return; } } } <file_sep>using System; using System.Collections.Generic; using System.Windows.Forms; using MackkadoITFramework.APIDocument; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace fcm.Windows { public partial class UIMaintainProject : Form { private Client _Client; public UIMaintainProject( Client iClient ) { InitializeComponent(); _Client = iClient; txtClientID.Text = _Client.UID.ToString(); txtClientName.Text = _Client.Name; } private void btnGenerateProjectFiles_Click(object sender, EventArgs e) { ReplicateFolderFilesReplace(); } // ----------------------------------------------------- // This method replicates folders and files for a given // folder structure (source and destination) // ----------------------------------------------------- private void ReplicateFolderFilesReplace() { Cursor.Current = Cursors.WaitCursor; Word.Application vkWordApp = new Word.Application(); string sourceFolder = txtSourceFolder.Text; string destinationFolder = txtDestinationFolder.Text; if (sourceFolder == "" || destinationFolder == "") { return; } var ts = new List<WordDocumentTasks.TagStructure>(); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<XX>>", TagValue = "VV1" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<YY>>", TagValue = "VV2" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<VV>>", TagValue = "VV3" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientNAME>>", TagValue = "Client 2" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientADDRESS>>", TagValue = "St Street" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientEMAILADDRESS>>", TagValue = "Email@com" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientPHONE>>", TagValue = "09393893" }); WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder); WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp); Cursor.Current = Cursors.Arrow; MessageBox.Show("Project Successfully Created."); } private void MaintainProject_Load(object sender, EventArgs e) { txtSourceFolder.Text = "C:\\Research\\TestTemplate\\TemplateFrom"; txtDestinationFolder.Text = "C:\\Research\\TestTemplate\\TemplateTo"; } private void groupBox2_Enter(object sender, EventArgs e) { } } } <file_sep>select * from management.document WHERE cuid="DAN-04" or cuid="DAN-01"; // delete from management.document WHERE cuid="DAN-04" and uid = 364; <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace FCMMySQLBusinessLibrary.Model.ModelClient { public class ClientExtraInformation { public int UID { get; set; } // bigint public int FKClientUID { get; set; } // bigint /// <summary> /// Date to enter on policies /// </summary> [Required( ErrorMessage = "Date to enter on policies is required." )] [Display( Name = "Date to enter on policies" )] [DataType( DataType.Date )] [UIHint( "Date" )] [DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true )] public DateTime DateToEnterOnPolicies { get; set; } // date [Required( ErrorMessage = "Scope of services is required." )] [Display( Name = "Scope Of Services" )] public string ScopeOfServices { get; set; } // varchar(200) [Required(ErrorMessage = "Action plan date is required.")] [Display(Name = "Action plan date")] [DataType(DataType.Date)] [UIHint("Date")] [DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true )] public DateTime ActionPlanDate { get; set; } // date [Required( ErrorMessage = "Certification Target Date is required." )] [Display( Name = "Certification Target Date" )] [DataType( DataType.Date )] [UIHint( "Date" )] [DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true )] public DateTime CertificationTargetDate { get; set; } // date [Display(Name = "Time Trading")] public string TimeTrading { get; set; } // varchar(200) [Display(Name = "Regions of Operation")] public string RegionsOfOperation { get; set; } // varchar(200) [Display(Name = "Operational Meetings Frequency")] public string OperationalMeetingsFrequency { get; set; } // varchar(50) [Display(Name = "Project Meetings Frequency")] public string ProjectMeetingsFrequency { get; set; } // varchar(50) public string IsVoid { get; set; } public string UserIdCreatedBy { get; set; } public string UserIdUpdatedBy { get; set; } public DateTime CreationDateTime { get; set; } public DateTime UpdateDateTime { get; set; } public int RecordVersion { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelClient { public class ClientOtherInfo { public int UID { get; set; } public int FKClientUID { get; set; } public string RCFieldCode { get; set; } public string FieldValueText { get; set; } /// <summary> /// Database fields /// </summary> public struct FieldName { public const string UID = "UID"; public const string FKClientUID = "FKClientUID"; public const string RCFieldCode = "RCFieldCode"; public const string FieldValueText = "FieldValueText"; } /// <summary> /// Get Last UID /// </summary> /// <returns></returns> private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientOtherInfo"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add Client Other Information Field /// </summary> public void Add() { int nextUID = GetLastUID() + 1; DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO ClientOtherInfo " + "(UID, FKClientUID, RCFieldCode, FieldValueText" + ")" + " VALUES " + "( " + " @UID " + ", @FKClientUID " + ", @RCFieldCode " + ", @FieldValueText " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = nextUID; command.Parameters.Add("@FKClientUID", MySqlDbType.VarChar).Value = FKClientUID; command.Parameters.Add("@RCFieldCode", MySqlDbType.VarChar).Value = RCFieldCode; command.Parameters.Add("@FieldValueText", MySqlDbType.VarChar).Value = FieldValueText; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Update Client Other Information Field /// </summary> public void Update() { DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientOtherInfo " + " SET FKClientUID = @FKClientUID " + " ,SET RCFieldCode = @RCFieldCode " + " ,SET FieldValueText = @FieldValueText " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = UID; command.Parameters.Add("@FKClientUID", MySqlDbType.VarChar).Value = FKClientUID; command.Parameters.Add("@RCFieldCode", MySqlDbType.VarChar).Value = RCFieldCode; command.Parameters.Add("@FieldValueText", MySqlDbType.VarChar).Value = FieldValueText; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// List employees /// </summary> /// <param name="clientID"></param> public static List<ClientOtherInfo> List(int clientID) { var clientOtherList = new List<ClientOtherInfo>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID, " + " FKClientUID, " + " RCFieldCode, " + " FieldValueText " + " FROM ClientOtherInfo " + " WHERE FKClientUID = {0}", clientID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var clientOther = new ClientOtherInfo(); LoadObject(reader, clientOther); clientOtherList.Add(clientOther); } } } } return clientOtherList; } /// <summary> /// This method loads the information from the sqlreader into the Employee object /// </summary> /// <param name="reader"></param> /// <param name="employee"></param> private static void LoadObject(MySqlDataReader reader, ClientOtherInfo clientOther) { clientOther.UID = Convert.ToInt32(reader[FieldName.UID].ToString()); clientOther.FKClientUID = Convert.ToInt32(reader[FieldName.FKClientUID]); clientOther.RCFieldCode = reader[FieldName.RCFieldCode].ToString(); clientOther.FieldValueText = reader[FieldName.FieldValueText].ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Components { public partial class UCDocumentList : UserControl { public DataTable elementSourceDataTable; public UCDocumentList() { InitializeComponent(); // // Create datatable // var CUID = new DataColumn("CUID", typeof(String)); var Name = new DataColumn("Name", typeof(String)); var Directory = new DataColumn("Directory", typeof(String)); var Subdirectory = new DataColumn("Subdirectory", typeof(String)); var SequenceNumber = new DataColumn("SequenceNumber", typeof(String)); var LatestIssueNumber = new DataColumn("LatestIssueNumber", typeof(String)); var LatestIssueLocation = new DataColumn("LatestIssueLocation", typeof(String)); var Comments = new DataColumn("Comments", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(CUID); elementSourceDataTable.Columns.Add(Name); elementSourceDataTable.Columns.Add(Directory); elementSourceDataTable.Columns.Add(Subdirectory); elementSourceDataTable.Columns.Add(SequenceNumber); elementSourceDataTable.Columns.Add(LatestIssueNumber); elementSourceDataTable.Columns.Add(LatestIssueLocation); elementSourceDataTable.Columns.Add(Comments); dgvDocumentList.DataSource = elementSourceDataTable; } public void List(string ListType, int DocumentSetID) { if (ListType == "ALL") { loadDocumentList(); } } // // List companies // private void loadDocumentList() { elementSourceDataTable.Clear(); var docoList = new DocumentList(); docoList.List(); foreach (Document doco in docoList.documentList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["CUID"] = doco.CUID; elementRow["Name"] = doco.Name; elementRow["Directory"] = doco.Directory; elementRow["Subdirectory"] = doco.Subdirectory; elementRow["SequenceNumber"] = doco.SequenceNumber; elementRow["LatestIssueNumber"] = doco.LatestIssueNumber; elementRow["LatestIssueLocation"] = doco.LatestIssueLocation; elementSourceDataTable.Rows.Add(elementRow); } } private void UCDocumentList_Load(object sender, EventArgs e) { ucDocument1.Visible = false; } private void EditMetadata(bool RefreshOnly) { if (!RefreshOnly) { if (ucDocument1.Visible == true) { ucDocument1.Visible = false; return; } ucDocument1.Visible = true; } if (dgvDocumentList.SelectedRows.Count <= 0) return; var selectedRow = dgvDocumentList.SelectedRows; Document rm = new Document(); rm.CUID = selectedRow[0].Cells["CUID"].Value.ToString(); rm.Directory = selectedRow[0].Cells["Directory"].Value.ToString(); rm.LatestIssueLocation = selectedRow[0].Cells["LatestIssueLocation"].Value.ToString(); rm.LatestIssueNumber = selectedRow[0].Cells["LatestIssueNumber"].Value.ToString(); rm.Name = selectedRow[0].Cells["Name"].Value.ToString(); rm.SequenceNumber = selectedRow[0].Cells["SequenceNumber"].Value.ToString(); rm.Subdirectory = selectedRow[0].Cells["Subdirectory"].Value.ToString(); rm.Comments = selectedRow[0].Cells["Comments"].Value.ToString(); ucDocument1.SetValues(rm); } private void btnDocumentDetails_Click(object sender, EventArgs e) { EditMetadata(false); } private void btnEdit_Click(object sender, EventArgs e) { EditMetadata(false); } private void dgvDocumentList_SelectionChanged(object sender, EventArgs e) { EditMetadata(true); } } } <file_sep>using System; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Interface; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using HeaderInfo = MackkadoITFramework.Utils.HeaderInfo; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Repository; // using fcm.ProxyAsync; namespace fcm.Windows { public partial class UIClientList : Form, IBUSClientList { private Form _sourceWindow; // ClientAsync m_Proxy = new ClientAsync(); int clientUID; private Form _comingFromForm; public UIClientList(Form comingFromForm) { InitializeComponent(); _comingFromForm = comingFromForm; clientUID = Utils.ClientID; } private void UIClientList_Load(object sender, EventArgs e) { ClientList(HeaderInfo.Instance); } /// <summary> /// List companies Async /// </summary> private void loadClientListAsync() { // m_Proxy.BeginClientList(HeaderInfo.Instance, OnClientListCompletion, null); } //void OnClientListCompletion(IAsyncResult result) //{ // var responseClientList = m_Proxy.EndClientList(result); // result.AsyncWaitHandle.Close(); // var clientList = responseClientList.clientList; // try // { // clientBindingSource.DataSource = clientList; // } // catch (Exception ex) // { // LogFile.WriteToTodaysLogFile( // "Error binding response. " + ex.ToString(), // Utils.UserID, // ResponseStatus.MessageCode.Error.FCMERR00009999, // "UIClientList.cs"); // } // m_Proxy.Close(); //} private void btnOk_Click(object sender, EventArgs e) { clientUID = GetClientUIDSelected(); if (clientUID <= 0) return; Utils.ClientID = clientUID; this.Close(); if (_sourceWindow != null) _sourceWindow.Activate(); } private void dgvClientList_CellMouseDown( object sender, DataGridViewCellMouseEventArgs e ) { if (e.ColumnIndex >= 0 && e.RowIndex >= 0) { dgvClientList.CurrentCell = dgvClientList.Rows[e.RowIndex].Cells[e.ColumnIndex]; } } private void miClientDetails_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; GetClientUIDSelected(); UIClientRegistration uicr = new UIClientRegistration(this, clientUID); uicr.Show(); Cursor.Current = Cursors.Arrow; } private void miContract_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; clientUID = GetClientUIDSelected(); if (clientUID <= 0) return; //Client client = new Client(HeaderInfo.Instance); //client.UID = Utils.ClientID; ClientReadRequest crr = new ClientReadRequest(); crr.clientUID = Utils.ClientID; crr.headerInfo = HeaderInfo.Instance; var crresponse = BUSClient.ClientRead( crr ); if (crresponse.client.UID <= 0) return; UIClientContract uicc = new UIClientContract(this, crresponse.client); uicc.Show(); Cursor.Current = Cursors.Arrow; } /// <summary> /// Get Client Selected /// </summary> /// <returns></returns> private int GetClientUIDSelected() { if (dgvClientList.SelectedRows.Count <= 0) return 0; var selectedRow = dgvClientList.SelectedRows; //String textClientUID = selectedRow[0].Cells["dgv" + DBFieldName.Client.UID].Value.ToString(); String textClientUID = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.UID].Value.ToString(); clientUID = Convert.ToInt32(textClientUID); Utils.ClientID = clientUID; return clientUID; } private void miDocuments_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; GetClientUIDSelected(); UIClientDocumentSet uicds = new UIClientDocumentSet(); uicds.Show(); Cursor.Current = Cursors.Arrow; } private void toolStripExit_Click(object sender, EventArgs e) { _comingFromForm.Activate(); _comingFromForm.Refresh(); this.Dispose(); } private void miNewClient_Click(object sender, EventArgs e) { UIClientRegistration uicr = new UIClientRegistration(this); uicr.Show(); } private void tsRefresh_Click(object sender, EventArgs e) { ClientList(HeaderInfo.Instance); } public override void Refresh() { ClientList(HeaderInfo.Instance); } private void miMetadata_Click(object sender, EventArgs e) { UIClientMetadata ucm = new UIClientMetadata(this); ucm.Show(); } private void dgvClientList_SelectionChanged(object sender, EventArgs e) { GetClientUIDSelected(); } /// Implementing Interface /// <summary> /// List Companies Sync /// </summary> public ClientListResponse ClientList(HeaderInfo headerInfo) { //loadClientListAsync(); //return; var responseClientList = new BUSClient().ClientList(HeaderInfo.Instance); if (responseClientList.response.ReturnCode < 0000) { LogFile.WriteToTodaysLogFile("Error loading client list", HeaderInfo.Instance.UserID, "", "UIClientList.cs"); return responseClientList; } var clientList = responseClientList.clientList; try { clientBindingSource.DataSource = clientList; } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Error binding response. " + ex.ToString(), Utils.UserID, ResponseStatus.MessageCode.Error.FCMERR00009999, "UIClientList.cs"); } return responseClientList; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.ProcessRequest { public class ProcessRequestArguments { #region Fields public int FKRequestUID { get; set; } public string Code { get; set; } public string ValueType { get; set; } // INT, STRING, DATE public string Value { get; set; } #endregion Fields #region Fields Building Blocks #region Permitted Values public enum ProcessRequestCodeValues { CLIENTUID, OVERRIDE, CLIENTSETID, CLIENTDOCUID } public enum ValueTypeValue { NUMBER, STRING } #endregion Permitted Values /// <summary> /// Database fields /// </summary> public struct FieldName { public const string FKRequestUID = "FKRequestUID"; public const string Code = "Code"; public const string ValueType = "ValueType"; public const string Value = "Value"; } /// <summary> /// Process Request Arguments string of fields. /// </summary> /// <returns></returns> private static string FieldString() { return ( FieldName.FKRequestUID + "," + FieldName.Code + "," + FieldName.ValueType + "," + FieldName.Value ); } /// <summary> /// Load from Reader /// </summary> /// <param name="processRequest"></param> /// <param name="tablePrefix"></param> /// <param name="reader"></param> public static void LoadFromReader( ProcessRequestArguments processRequest, MySqlDataReader reader) { processRequest.FKRequestUID = Convert.ToInt32(reader[FieldName.FKRequestUID].ToString()); processRequest.Code = reader[FieldName.Code].ToString(); processRequest.ValueType = reader[FieldName.ValueType].ToString(); processRequest.Value = reader[FieldName.Value].ToString(); return; } #endregion Fields Building Blocks /// <summary> /// Check if request code exists for request. /// </summary> /// <param name="requestUID"></param> /// <param name="requestCode"></param> /// <returns></returns> public static bool Exists(int requestUID, string requestCode) { int xUID = 0; bool exist = false; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = "SELECT FKRequestUID UID FROM ProcessRequestArguments WHERE FKRequestUID = " + requestUID.ToString() + " AND Code = '" + requestCode + "'"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { xUID = Convert.ToInt32(reader["UID"]); exist = true; } catch (Exception) { xUID = 0; } } } } return exist; } /// <summary> /// Add New Process Request Argument /// </summary> public ResponseStatus Add() { ResponseStatus responseSuccessful = new ResponseStatus(); ResponseStatus responseError = new ResponseStatus(messageType: MessageType.Error); // Check if request has already been added // if (ProcessRequestArguments.Exists(this.FKRequestUID, this.Code)) { responseError.Message = "Request Argument already exists " + this.Code; responseError.Contents = this; return responseError; } DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO ProcessRequestArguments " + "( " + FieldString() + ")" + " VALUES " + "( " + " @" + FieldName.FKRequestUID + ", @" + FieldName.Code + ", @" + FieldName.ValueType + ", @" + FieldName.Value + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKRequestUID", MySqlDbType.Int32).Value = FKRequestUID; command.Parameters.Add("@Code", MySqlDbType.VarChar).Value = Code; command.Parameters.Add("@ValueType", MySqlDbType.VarChar).Value = ValueType; command.Parameters.Add("@Value", MySqlDbType.VarChar).Value = Value; connection.Open(); command.ExecuteNonQuery(); } } return responseSuccessful; } /// <summary> /// List requests /// </summary> /// <param name="StatusIn"></param> /// <returns></returns> public static List<ProcessRequestArguments> List(int requestID) { var result = new List<ProcessRequestArguments>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + FieldString() + " FROM ProcessRequestArguments " + " WHERE " + " FKRequestUID = '" + requestID.ToString() + "'" + " " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _ProcessRequestArguments = new ProcessRequestArguments(); ProcessRequestArguments.LoadFromReader(_ProcessRequestArguments, reader); result.Add(_ProcessRequestArguments); } } } } return result; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using fcm.Windows; namespace fcm.Components { public partial class UCReportMetadata : UserControl { UIReportMetadata uiReportMetadata; public UCReportMetadata() { InitializeComponent(); } public void SetUIReportInst(UIReportMetadata inst) { uiReportMetadata = inst; } private void btnNew_Click(object sender, EventArgs e) { ClearFields(); // Generate new Unique ID txtUID.Text = (ReportMetadata.GetLastUID() + 1).ToString(); } private void ClearFields() { txtRecordType.Text = "DF"; txtFieldCode.Text = ""; txtClientUID.Text = ""; txtDescription.Text = ""; txtInformationType.Text = ""; txtTableName.Text = ""; txtFieldName.Text = ""; txtFilePath.Text = ""; txtFileName.Text = ""; } public void SetValues(ReportMetadata input) { txtUID.Text = input.UID.ToString(); txtRecordType.Text = input.RecordType; txtFieldCode.Text = input.FieldCode; txtClientUID.Text = input.ClientUID.ToString(); txtDescription.Text = input.Description; txtInformationType.Text = input.InformationType; txtTableName.Text = input.TableName; txtFieldName.Text = input.FieldName; txtFilePath.Text = input.FilePath; txtFileName.Text = input.FileName; } private void textBox2_TextChanged(object sender, EventArgs e) { } private void btnSave_Click(object sender, EventArgs e) { ReportMetadata rmd = new ReportMetadata(); rmd.UID = Convert.ToInt32( txtUID.Text ); rmd.RecordType = txtRecordType.Text; if (string.IsNullOrEmpty (txtClientUID.Text) ) rmd.ClientUID = 0; else rmd.ClientUID = Convert.ToInt32(txtClientUID.Text ); rmd.ClientType = txtClientType.Text; rmd.Description = txtDescription.Text; rmd.InformationType = txtInformationType.Text; rmd.FieldCode = txtFieldCode.Text; rmd.TableName = txtTableName.Text; rmd.FieldName = txtFieldName.Text; rmd.FilePath = txtFilePath.Text; rmd.FileName = txtFileName.Text; rmd.Save(); MessageBox.Show("Code Type Save Successfully."); if (uiReportMetadata != null) { uiReportMetadata.loadMetadataList(rmd.UID); } this.Visible = false; } private void UCReportMetadata_Load(object sender, EventArgs e) { } private void btnDelete_Click(object sender, EventArgs e) { var conf = MessageBox.Show("Are you sure?", "Delete Item", MessageBoxButtons.YesNo); if (conf != DialogResult.Yes) return; ReportMetadata rmd = new ReportMetadata(); rmd.UID = Convert.ToInt32(txtUID.Text); bool ret = rmd.Delete(); if (ret) { MessageBox.Show("Item Deleted Successfully."); } else { MessageBox.Show("Deletion was unsuccessful."); } if (uiReportMetadata != null) { uiReportMetadata.loadMetadataList(rmd.UID); } this.Visible = false; } } } <file_sep>using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using fcm.Windows; using fcm.Components; namespace fcm.Windows { /// <summary> /// Summary description for Form1. /// </summary> public class frmParserMainUI : System.Windows.Forms.Form { private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MainMenu mainMenu; private IContainer components; private System.Windows.Forms.OpenFileDialog openFileDialog; private MenuItem menuItem2; private MenuItem miClient; private MenuItem miEmployee; private MenuItem menuItem7; private string _userID; // private string _connectionString; // private ClientList _ClientList; private MenuItem menuItem3; private MenuItem menuItem4; private MenuItem menuItem6; private MenuItem menuItem9; private PictureBox pictureBox1; private MenuItem menuItem1; /// <summary> /// MS Word COM Object /// </summary> private Word.ApplicationClass vk_word_app = new Word.ApplicationClass(); public frmParserMainUI() { // // Required for Windows Form Designer support // InitializeComponent(); _userID = "Daniel"; //_connectionString = //"Data Source=FNOA0189\\SQL2005;Initial Catalog=DanMacTest;integrated security=True"; //_connectionString = // "Data Source=TOSHIBAMACHADO\\SQLEXPRESS;" + // "Initial Catalog=management;" + // "Persist Security info=false;" + // "integrated security=sspi;"; //_connectionString = // "Data Source=DESKTOPMACHADO\\SQLEXPRESS;" + // "Initial Catalog=management;" + // "Persist Security info=false;" + // "integrated security=sspi;"; // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmParserMainUI)); this.mainMenu = new System.Windows.Forms.MainMenu(this.components); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.menuItem9 = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.miClient = new System.Windows.Forms.MenuItem(); this.miEmployee = new System.Windows.Forms.MenuItem(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // mainMenu // this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem5, this.menuItem7, this.menuItem2}); // // menuItem5 // this.menuItem5.Index = 0; this.menuItem5.Text = "E&xit"; this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click); // // menuItem7 // this.menuItem7.Index = 1; this.menuItem7.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem3, this.menuItem4, this.menuItem1, this.menuItem9}); this.menuItem7.Text = "Maintenance"; // // menuItem3 // this.menuItem3.Index = 0; this.menuItem3.Text = "Reference Data"; this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click); // // menuItem4 // this.menuItem4.Index = 1; this.menuItem4.Text = "Report Metadata"; this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click); // // menuItem9 // this.menuItem9.Index = 3; this.menuItem9.Text = "Document Set"; this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click); // // menuItem1 // this.menuItem1.Index = 2; this.menuItem1.Text = "Document"; this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); // // menuItem2 // this.menuItem2.Index = 2; this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miClient, this.miEmployee, this.menuItem6}); this.menuItem2.Text = "Client"; this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); // // miClient // this.miClient.Index = 0; this.miClient.Text = "Details"; this.miClient.Click += new System.EventHandler(this.miClient_Click); // // miEmployee // this.miEmployee.Index = 1; this.miEmployee.Text = "Employees"; this.miEmployee.Click += new System.EventHandler(this.miEmployee_Click); // // menuItem6 // this.menuItem6.Index = 2; this.menuItem6.Text = "Proposal"; this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click_1); // // openFileDialog // this.openFileDialog.Multiselect = true; this.openFileDialog.Title = "SAMS Parser.Net"; // // pictureBox1 // this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pictureBox1.Image = global::fcm.Properties.Resources.FCMLogo; this.pictureBox1.Location = new System.Drawing.Point(12, 315); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(236, 74); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // frmParserMainUI // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(718, 401); this.Controls.Add(this.pictureBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu; this.Name = "frmParserMainUI"; this.ShowIcon = false; this.Text = " "; this.Load += new System.EventHandler(this.frmParserMainUI_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new frmParserMainUI()); } /// <summary> /// Get source document. Open a FileDialog window for user to select single/multiple files for /// parsing. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void butSourceDocument_Click(object sender, System.EventArgs e) { if( openFileDialog.ShowDialog() == DialogResult.OK ) { object fileName = openFileDialog.FileName; object saveFile = fileName + "_Vk.doc"; object vk_read_only = false; object vk_visible = true; object vk_false = false; object vk_true = true; object vk_dynamic = 2; object vk_missing = System.Reflection.Missing.Value; // Let make the word application visible vk_word_app.Visible = true; vk_word_app.Activate(); // Let's open the document Word.Document vk_my_doc = vk_word_app.Documents.Open( ref fileName, ref vk_missing, ref vk_read_only, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_visible ); // Let's create a new document Word.Document vk_new_doc = vk_word_app.Documents.Add( ref vk_missing, ref vk_missing, ref vk_missing, ref vk_visible ); // Select and Copy from the original document vk_my_doc.Select(); vk_word_app.Selection.Copy(); // Paste into new document as unformatted text vk_new_doc.Select(); vk_word_app.Selection.PasteSpecial( ref vk_missing, ref vk_false, ref vk_missing, ref vk_false, ref vk_dynamic, ref vk_missing, ref vk_missing ); // close the original document vk_my_doc.Close( ref vk_false, ref vk_missing, ref vk_missing ); // Let try to replace Vahe with VAHE in the new document object vk_find = "^l"; object vk_replace = " "; object vk_num = 1; vk_new_doc.Select(); WordDocumentTasks.FindAndReplace( "<<Client Name>>", "tEST", vk_num, vk_word_app); // Save the new document vk_new_doc.SaveAs( ref saveFile, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing ); // close the new document vk_new_doc.Close( ref vk_false, ref vk_missing, ref vk_missing ); /* // Let's get the content from the document Word.Paragraphs vk_my_doc_p = vk_new_doc.Paragraphs; // Count number of paragraphs in the file long p_count = vk_my_doc_p.Count; // step through the paragraphs for( int i=1; i<=p_count; i++ ) { Word.Paragraph vk_p = vk_my_doc_p.Item( i ); Word.Range vk_r = vk_p.Range; string text = vk_r.Text; MessageBox.Show( text ); } */ // close word application vk_word_app.Quit( ref vk_false, ref vk_missing, ref vk_missing ); } } private void menuItem5_Click(object sender, System.EventArgs e) { // Terminate the program this.Close(); } private void menuItem2_Click(object sender, EventArgs e) { } private void miClient_Click(object sender, EventArgs e) { UIClientDetails ClientDetails = new UIClientDetails(_userID); ClientDetails.Show(); } private void frmParserMainUI_Load(object sender, EventArgs e) { //Utils.ClientList = new ClientList(_userID); //Utils.ClientList.List(); //foreach (Client c in Utils.ClientList.clientList) //{ // cbxClientName.Items.Add(c.UID + "; " + c.Name); //} //cbxClientName.SelectedIndex = 0; //Utils.ClientID = Utils.ClientList.clientList[cbxClientName.SelectedIndex].UID; //Utils.ClientIndex = cbxClientName.SelectedIndex; UILogon log = new UILogon(); log.ShowDialog(); } private void miMaintainProjectDocuments_Click(object sender, EventArgs e) { } private void miMaintainProject_Click(object sender, EventArgs e) { //var i = cbxClientName.SelectedIndex; //if (i > 0) //{ // var ClientSelected = Utils.ClientList.clientList[i]; // UIMaintainProject mproject = new UIMaintainProject(ClientSelected); // mproject.Show(); //} //else //{ // MessageBox.Show("Please select a Client."); //} } private void menuItem6_Click(object sender, EventArgs e) { UIReportMetadata generalMetadata = new UIReportMetadata(_userID); generalMetadata.Show(); } private void miCreateNewSet_Click(object sender, EventArgs e) { // UIMaintainProject maintainProject = new UIMaintainProject( } private void menuItem3_Click(object sender, EventArgs e) { UIReferenceData referenceData = new UIReferenceData(); referenceData.Show(); } private void menuItem8_Click(object sender, EventArgs e) { } private void miDocument_Click(object sender, EventArgs e) { } private void menuItem4_Click(object sender, EventArgs e) { UIReportMetadata gmd = new UIReportMetadata(_userID); gmd.Show(); } private void menuItem6_Click_1(object sender, EventArgs e) { UIProposal uip = new UIProposal(); uip.Show(); } private void menuItem9_Click(object sender, EventArgs e) { UIDocument utf = new UIDocument(); utf.Show(); } private void cbxClientName_SelectedIndexChanged(object sender, EventArgs e) { //Utils.ClientID = Utils.ClientList.clientList[cbxClientName.SelectedIndex].UID; //Utils.ClientIndex = cbxClientName.SelectedIndex; } private void miEmployee_Click(object sender, EventArgs e) { } private void menuItem1_Click(object sender, EventArgs e) { UIDocumentList uid = new UIDocumentList(); uid.Show(); } } }<file_sep>using System.ServiceModel; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.ServiceContract; namespace FCMMySQLBusinessLibrary.Service.SVCClientDocument.Interface { [ServiceContract] public interface IBUSClientDocument { SCClientDocument.ClientDocumentUpdateResponse ClientDocumentUpdate(ClientDocument clientDocument); } } <file_sep>using System.Collections.Generic; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public class BUSClientDocumentSet { public int DocumentCount { get { return _DocumentCount; } } private int _DocumentCount; public BUSClientDocumentSet(int iClientUID, int iClientDocumentSetUID) { // Calculate number of documents in set ResponseStatus response = new ResponseStatus(); var clientDocSet = new ClientDocumentSet(iClientUID, iClientDocumentSetUID); _DocumentCount = clientDocSet.GetNumberOfDocuments(); } /// <summary> /// Add client document set /// </summary> /// <param name="eventClient"></param> /// <returns></returns> public static ResponseStatus ClientDocumentSetAdd(HeaderInfo headerInfo) { ResponseStatus response = new ResponseStatus(); ClientDocumentSet cds = new ClientDocumentSet(Utils.ClientID); cds.FKClientUID = Utils.ClientID; //cds.FolderOnly = "CLIENT" + Utils.ClientID.ToString().Trim().PadLeft(4, '0'); //cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + @"\" + cds.FolderOnly; cds.SourceFolder = FCMConstant.SYSFOLDER.TEMPLATEFOLDER; cds.Add(headerInfo); return response; } /// <summary> /// List document sets for a client /// </summary> /// <param name="eventClient"></param> /// <returns></returns> public static List<ClientDocumentSet> ClientDocumentSetList(int iClientUID, string sortOrder) { List<ClientDocumentSet> response = new List<ClientDocumentSet>(); response = ClientDocumentSet.List(iClientUID, sortOrder); return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FCMMySQLBusinessLibrary.Repository.RepositoryDocument { public class RepDocumentSetDocument { /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> public static string SQLDocumentConcat(string tablePrefix) { string ret = " " + tablePrefix + ".UID " + tablePrefix + "UID, " + tablePrefix + ".FKDocumentUID " + tablePrefix + "FKDocumentUID, " + tablePrefix + ".FKDocumentSetUID " + tablePrefix + "FKDocumentSetUID, " + tablePrefix + ".Location " + tablePrefix + "Location, " + tablePrefix + ".IsVoid " + tablePrefix + "IsVoid, " + tablePrefix + ".StartDate " + tablePrefix + "StartDate, " + tablePrefix + ".EndDate " + tablePrefix + "EndDate, " + tablePrefix + ".FKParentDocumentUID " + tablePrefix + "FKParentDocumentUID, " + tablePrefix + ".SequenceNumber " + tablePrefix + "SequenceNumber, " + tablePrefix + ".FKParentDocumentSetUID " + tablePrefix + "FKParentDocumentSetUID, " + tablePrefix + ".DocumentType " + tablePrefix + "DocumentType "; return ret; } } } <file_sep>using System.ComponentModel.DataAnnotations; namespace FCMMySQLBusinessLibrary.Model.ModelClient { public class ClientEmployee { /// <summary> /// /// </summary> [Required( ErrorMessage = "Managing Director's Name is mandatory." )] [Display( Name = "Managing Director" )] public string ManagingDirector { get; set; } /// <summary> /// HSR1 - Health And Safety Rep /// </summary> [Required( ErrorMessage = "Health And Safety Representative is mandatory." )] [Display( Name = "Health And Safety Representative" )] public string HealthAndSafetyRep { get; set; } /// <summary> /// OHSEAUDITOR - OHS Auditor /// </summary> [Required( ErrorMessage = "OHS&E Auditor is mandatory." )] [Display( Name = "OHS&E Auditor" )] public string OHSEAuditor { get; set; } /// <summary> /// PM1 - Project Manager /// </summary> [Required( ErrorMessage = "Project Manager is mandatory." )] [Display( Name = "Project Manager" )] public string ProjectManager { get; set; } /// <summary> /// POHSEREP - Project OHS Representative /// </summary> [Required( ErrorMessage = "Project OHS Representative is mandatory." )] [Display( Name = "Project OHS Representative" )] public string ProjectOHSRepresentative { get; set; } /// <summary> /// SM1 - Site Manager Name /// </summary> [Required( ErrorMessage = "Site Manager Name is mandatory." )] [Display( Name = "Site Manager" )] public string SiteManager { get; set; } /// <summary> /// SMN1 - Systems Manager Name /// </summary> [Required( ErrorMessage = "Systems Manager Name is mandatory." )] [Display( Name = "Systems Manager" )] public string SystemsManager { get; set; } /// <summary> /// SUP1 - Supervisor Name /// </summary> [Display( Name = "Supervisor's Name" )] [Required( ErrorMessage = "Supervisor Name is mandatory." )] public string Supervisor { get; set; } /// <summary> /// WCPERSON - Workers Compensation Person /// </summary> [Display( Name = "Workers Compensation Person" )] [Required( ErrorMessage = "Workers Compensation Person's name is mandatory." )] public string WorkersCompensationCoordinator { get; set; } /// <summary> /// LH1 - Leading Hand 1 /// </summary> [Display( Name = "Leading Hand 1" )] [Required( ErrorMessage = "Leading Hand 1 is mandatory." )] public string LeadingHand1 { get; set; } /// <summary> /// LH2 - Leading Hand 2 /// </summary> [Display( Name = "Leading Hand 2" )] [Required( ErrorMessage = "Leading Hand 2 is mandatory." )] public string LeadingHand2 { get; set; } /// <summary> /// ADMINPERSON - Administration Person /// </summary> [Display( Name = "Administration Person" )] [Required( ErrorMessage = "Administration Person is mandatory." )] public string AdministrationPerson { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Components { public partial class UCDocument : UserControl { public UCDocument() { InitializeComponent(); } private void UCDocument_Load(object sender, EventArgs e) { } public void SetValues(Document inDoco) { txtCUID.Text = inDoco.CUID; txtDirectory.Text = inDoco.Directory; txtLatestIssueLocation.Text = inDoco.LatestIssueLocation; txtLatestIssueNumber.Text = inDoco.LatestIssueNumber; txtName.Text = inDoco.Name; txtSeqNum.Text = inDoco.SequenceNumber; txtSubDirectory.Text = inDoco.Subdirectory; txtComments.Text = inDoco.Comments; } public void New() { txtCUID.Text = ""; txtDirectory.Text = ""; txtLatestIssueLocation.Text = ""; txtLatestIssueNumber.Text = ""; txtName.Text = ""; txtSeqNum.Text = ""; txtSubDirectory.Text = ""; txtComments.Text = ""; } private void btnNew_Click(object sender, EventArgs e) { New(); } private void btnOpenFile_Click(object sender, EventArgs e) { var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { txtLatestIssueLocation.Text = openFileDialog1.FileName; } } private void Save_Click(object sender, EventArgs e) { Document docSave = new Document(); if (string.IsNullOrEmpty(txtCUID.Text)) { docSave.Comments = txtComments.Text; docSave.Directory = txtDirectory.Text; docSave.LatestIssueLocation = txtLatestIssueLocation.Text; docSave.LatestIssueNumber = txtLatestIssueNumber.Text; docSave.Name = txtName.Text; docSave.SequenceNumber = txtSeqNum.Text; docSave.Subdirectory = txtSubDirectory.Text; docSave.Add(); } else { } } private void txtName_TextChanged(object sender, EventArgs e) { } private void txtDirectory_TextChanged(object sender, EventArgs e) { } private void txtSubDirectory_TextChanged(object sender, EventArgs e) { } private void txtSeqNum_TextChanged(object sender, EventArgs e) { } private void txtLatestIssueNumber_TextChanged(object sender, EventArgs e) { } private void txtLatestIssueLocation_TextChanged(object sender, EventArgs e) { } private void txtComments_TextChanged(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void label6_Click(object sender, EventArgs e) { } private void label8_Click(object sender, EventArgs e) { } private void txtCUID_TextChanged(object sender, EventArgs e) { } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Mail; using System.IO; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary { public class FCMEmail { /// <summary> /// Send Email /// </summary> /// <param name="iFrom"></param> /// <param name="iRecipient"></param> /// <param name="iSubject"></param> /// <param name="iBody"></param> public static ResponseStatus SendEmail( string iFrom, string iPassword, string iRecipient, string iSubject, string iBody, string iAttachmentLocation) { ResponseStatus resp = new ResponseStatus(); resp.Message = "Email has been sent."; try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress(iFrom); mail.To.Add(iRecipient); mail.Subject = iSubject; mail.Body = iBody; if (!File.Exists(iAttachmentLocation)) { // MessageBox.Show("File not found. " + iAttachmentLocation); resp.Message = "File not found. " + iAttachmentLocation; resp.ReturnCode = -0020; resp.ReasonCode = 0001; return resp; } System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(iAttachmentLocation); mail.Attachments.Add(attachment); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential(iFrom, iPassword); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); // MessageBox.Show("Email has been sent"); } catch (Exception e1) { // MessageBox.Show(e1.ToString()); resp.Message = "Exception in FCMEmail.cs >>> " + iAttachmentLocation; resp.ReturnCode = -0030; resp.ReasonCode = 0001; return resp; } return resp; } /// <summary> /// Send Email /// </summary> /// <param name="iFrom"></param> /// <param name="iRecipient"></param> /// <param name="iSubject"></param> /// <param name="iBody"></param> /// <param name="iAttachmentLocation"></param> public static ResponseStatus SendEmailSimple( string iRecipient, string iSubject, string iBody, string iAttachmentLocation = "", string iAttachmentLocation2 = "", string inlineAttachment = "") { string iFrom = "<EMAIL>"; string iPassword = "<PASSWORD>"; ResponseStatus resp = new ResponseStatus(); resp.Message = "Email has been sent."; try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient( "smtp.gmail.com" ); mail.From = new MailAddress( iFrom ); mail.To.Add( iRecipient ); mail.Subject = iSubject; mail.Body = iBody; mail.IsBodyHtml = true; // Only if attachment is passed if (! string.IsNullOrEmpty(iAttachmentLocation)) { if (!File.Exists(iAttachmentLocation)) { // MessageBox.Show("File not found. " + iAttachmentLocation); resp.Message = "File not found. " + iAttachmentLocation; resp.ReturnCode = -0020; resp.ReasonCode = 0001; return resp; } System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(iAttachmentLocation); mail.Attachments.Add(attachment); } if (!string.IsNullOrEmpty(iAttachmentLocation2)) { if (!File.Exists(iAttachmentLocation2)) { // MessageBox.Show("File not found. " + iAttachmentLocation); resp.Message = "File not found. " + iAttachmentLocation2; resp.ReturnCode = -0020; resp.ReasonCode = 0001; return resp; } System.Net.Mail.Attachment attachment2; attachment2 = new System.Net.Mail.Attachment(iAttachmentLocation2); mail.Attachments.Add(attachment2); } // Only if attachment is passed if (!string.IsNullOrEmpty(inlineAttachment)) { System.Net.Mail.Attachment inlineatc; inlineatc = new System.Net.Mail.Attachment(inlineAttachment); string contentID = "inlineattach@host"; inlineatc.ContentId = contentID; inlineatc.ContentDisposition.Inline = true; mail.Attachments.Add(inlineatc); mail.Body += "<html><body><img src=\"cid:" + contentID + "\"></body></html>"; } SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential( iFrom, iPassword ); SmtpServer.EnableSsl = true; SmtpServer.Send( mail ); } catch ( Exception e1 ) { resp.Message = "Exception in FCMEmail.cs >>> "; resp.ReturnCode = -0030; resp.ReasonCode = 0001; return resp; } return resp; } } }<file_sep>using System; using System.Collections.Generic; using System.Windows.Forms; using MackkadoITFramework.ProcessRequest; namespace fcm.Windows { public partial class UIProcessRequest : Form { List<ProcessRequest> processRequestList; List<ProcessRequestResults> processRequestResultList; public UIProcessRequest() { InitializeComponent(); } private void UIProcessRequest_Load(object sender, EventArgs e) { processRequestList = new List<ProcessRequest>(); ListProcessRequest(); } /// <summary> /// List employees /// </summary> private void ListProcessRequest() { processRequestList = ProcessRequest.List(ProcessRequest.StatusValue.ALL); try { bsProcessRequest.DataSource = processRequestList; } catch (Exception ex) { MessageBox.Show("Binding Error: " + ex.ToString()); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dgvRequests_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { } private void dgvRequests_SelectionChanged(object sender, EventArgs e) { RefreshList(); } private void btnRefresh_Click(object sender, EventArgs e) { RefreshList(); } /// <summary> /// Refresh List /// </summary> private void RefreshList() { if (dgvRequests.SelectedRows.Count <= 0) return; var selectedRow = dgvRequests.SelectedRows; var uidString = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.UID].Value.ToString(); var description = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.Description].Value.ToString(); var fkclientuid = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.FKClientUID].Value.ToString(); var type = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.Type].Value.ToString(); var status = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.Status].Value.ToString(); var whentoprocess = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.WhenToProcess].Value.ToString(); var creationDateTime = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.CreationDateTime].Value.ToString(); var statusDateTime = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.StatusDateTime].Value.ToString(); var plannedDateTime = selectedRow[0].Cells["dgv" + ProcessRequest.FieldName.PlannedDateTime].Value.ToString(); processRequestResultList = new List<ProcessRequestResults>(); int uidInt = Convert.ToInt32(uidString); processRequestResultList = ProcessRequestResults.List(uidInt); bsProcessRequestResults.Clear(); bsProcessRequestResults.DataSource = processRequestResultList; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Dispose(); } } } <file_sep>using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using System.Drawing; using System.IO; using System.Reflection; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using HeaderInfo = MackkadoITFramework.Utils.HeaderInfo; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; namespace fcm { /// <summary> /// This class was designed after extracting the business logic from the UI. /// The essential methods from the Utils (in Business layer now) are now listed here. /// </summary> public class ControllerUtils { // ----------------------------------------------------- // Load documents in a tree // The list in tree expects that the list has been // called before to populate the instance // ----------------------------------------------------- public void ListInTree( List<scClientDocSetDocLink> clientDocSetDocLink, TreeView fileList ) { foreach (var docLinkSet in clientDocSetDocLink) { // Check if folder has a parent string cdocumentUID = docLinkSet.clientDocument.UID.ToString(); string cparentIUID = docLinkSet.clientDocument.ParentUID.ToString(); int image = 0; int imageSelected = 0; docLinkSet.clientDocument.RecordType = docLinkSet.clientDocument.RecordType.Trim(); if (docLinkSet.clientDocument.RecordType == FCMConstant.RecordType.DOCUMENT) { //image = FCMConstant.Image.Document; //imageSelected = FCMConstant.Image.Document; image = FCMConstant.Image.Word32; imageSelected = FCMConstant.Image.Word32; } else { image = FCMConstant.Image.Folder; imageSelected = FCMConstant.Image.Folder; } if (docLinkSet.clientDocument.ParentUID == 0) { var treeNode = new TreeNode( docLinkSet.document.Name, image, imageSelected ); treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add( treeNode ); // rootNode.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find( cparentIUID, true ); if (node.Count() > 0) { var treeNode = new TreeNode( docLinkSet.document.Name, image, imageSelected ); treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; node[0].Nodes.Add( treeNode ); } else { // Add Element to the root // var treeNode = new TreeNode( docLinkSet.document.Name, image, imageSelected ); treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add( treeNode ); // rootNode.Nodes.Add(treeNode); } } } } // ----------------------------------------------------- // Load documents in a tree // ----------------------------------------------------- public static void ListInTree( TreeView fileList, ClientDocumentLinkList documentList, Document root ) { // Find root folder // Document rootDocument = new Document(); rootDocument.CUID = root.CUID; rootDocument.RecordType = root.RecordType; rootDocument.UID = root.UID; // rootDocument.Read(); // rootDocument = RepDocument.Read(false, root.UID); // Using Business Layer var documentReadRequest = new DocumentReadRequest(); documentReadRequest.UID = root.UID; documentReadRequest.CUID = root.CUID; documentReadRequest.retrieveVoidedDocuments = false; var docreadresp = BUSDocument.DocumentRead(documentReadRequest); if (docreadresp.response.ReturnCode == 0001) { // all good } else { MessageBox.Show(docreadresp.response.Message); return; } rootDocument = docreadresp.document; // // Create root // var rootNode = new TreeNode(rootDocument.Name, FCMConstant.Image.Folder, FCMConstant.Image.Folder); // Add root node to tree // fileList.Nodes.Add( rootNode ); rootNode.Tag = rootDocument; rootNode.Name = rootDocument.Name; foreach (var document in documentList.clientDocumentLinkList) { // Ignore root folder if (document.childDocument.CUID == "ROOT") continue; // Check if folder has a parent string cdocumentUID = document.UID.ToString(); string cparentIUID = document.childDocument.ParentUID.ToString(); int image = 0; if (document.childDocument.RecordType != null) { document.childDocument.RecordType = document.childDocument.RecordType.Trim(); } image = Utils.ImageSelect( document.childDocument.RecordType ); if (document.childDocument.ParentUID == 0) { var treeNode = new TreeNode( document.childDocument.Name, image, image ); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add( treeNode ); } else { // Find the parent node // var node = fileList.Nodes.Find( cparentIUID, true ); if (node.Count() > 0) { var treeNode = new TreeNode( document.childDocument.Name, image, image ); treeNode.Tag = document; treeNode.Name = cdocumentUID; node[0].Nodes.Add( treeNode ); } else { // Add Element to the root // var treeNode = new TreeNode( document.childDocument.Name, image, image ); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add( treeNode ); } } } } // ------------------------------------------------------ // Return list of images // ------------------------------------------------------ public static ImageList GetImageList() { // Image list // var imageList = new ImageList(); imageList.Images.Add( Properties.Resources.ImageSelected ); // image 0 imageList.Images.Add( Properties.Resources.ImageWordDocument ); // image 1 imageList.Images.Add( Properties.Resources.ImageFolder ); // image 2 imageList.Images.Add( Properties.Resources.ImageClient ); // image 3 imageList.Images.Add( Properties.Resources.Appendix ); // image 4 imageList.Images.Add( Properties.Resources.Excel ); // image 5 imageList.Images.Add( Properties.Resources.PDF ); // image 6 imageList.Images.Add( Properties.Resources.Undefined ); // image 7 imageList.Images.Add( Properties.Resources.Checked ); // image 8 imageList.Images.Add( Properties.Resources.Unchecked ); // image 9 imageList.Images.Add(Properties.Resources.WordFile32); // image 10 imageList.Images.Add(Properties.Resources.WordFileExists32); // image 11 imageList.Images.Add(Properties.Resources.WordFileNotFound32); // image 12 // Word Images imageList.Images.Add(Properties.Resources.WordFileSourceNoDestinationNo); // image 13 imageList.Images.Add(Properties.Resources.WordFileSourceNoDestinationYes); // image 14 imageList.Images.Add(Properties.Resources.WordFileSourceYesDestinationNo); // image 15 imageList.Images.Add(Properties.Resources.WordFileSourceYesDestinationYes); // image 16 // Excel Images imageList.Images.Add(Properties.Resources.ExcelFileSourceNoDestinationNo); // image 17 imageList.Images.Add(Properties.Resources.ExcelFileSourceNoDestinationYes); // image 18 imageList.Images.Add(Properties.Resources.ExcelFileSourceYesDestinationNo); // image 19 imageList.Images.Add(Properties.Resources.ExcelFileSourceYesDestinationYes); // image 20 // PDF Images imageList.Images.Add(Properties.Resources.PDFFileSourceNoDestinationNo); // image 21 imageList.Images.Add(Properties.Resources.PDFFileSourceNoDestinationYes); // image 22 imageList.Images.Add(Properties.Resources.PDFFileSourceYesDestinationNo); // image 23 imageList.Images.Add(Properties.Resources.PDFFileSourceYesDestinationYes); // image 24 Utils.ImageLogoStartsFrom = 25; // load client's logo images // int logoClientNum = 25; foreach (var client in Utils.ClientList) { // Get Company Logo // string logoLocation = RepClient.GetClientLogoLocation(client.UID, HeaderInfo.Instance); // Check if location exists if (!File.Exists(logoLocation)) { LogFile.WriteToTodaysLogFile( " FCMERR00000009 (02)" + " Error. Client logo not found. " + logoLocation + " Client : " + client.UID, Utils.UserID); return imageList; } Bitmap clientImage; clientImage = new Bitmap(logoLocation); imageList.Images.Add((Image)clientImage); client.LogoImageSeqNum = logoClientNum; logoClientNum++; } return imageList; } /// <summary> /// Show error message. /// </summary> /// <param name="errorCode"></param> public static void ShowFCMMessage(ResponseStatus response, string userID, string message = "") { switch (response.XMessageType) { case MessageType.Error: response.Icon = MessageBoxIcon.Error; break; case MessageType.Warning: response.Icon = MessageBoxIcon.Warning; break; case MessageType.Informational: response.Icon = MessageBoxIcon.Information; break; } if (string.IsNullOrEmpty(response.Message)) { response.Message = fcm.Windows.Cache.CachedInfo.GetDescription( FCMConstant.CodeTypeString.ErrorCode, response.UniqueCode); } MessageBox.Show(response.Message + " " + message, response.UniqueCode, MessageBoxButtons.OK, response.Icon); LogFile.WriteToTodaysLogFile(response.Message + " <> " + message, userID); return; } /// <summary> /// Show error message. /// </summary> /// <param name="errorCode"></param> public static void ShowFCMMessage( string errorCode, string userID, string additionalMessage = "", string programName = "") { if (string.IsNullOrEmpty(errorCode)) return; string messageType = errorCode.Substring(3, 3); MessageBoxIcon icon = MessageBoxIcon.Error; switch (messageType) { case "ERR": icon = MessageBoxIcon.Error; break; case "WAR": icon = MessageBoxIcon.Warning; break; case "INF": icon = MessageBoxIcon.Information; break; } string errorDescription = CodeValue.GetCodeValueDescription( FCMConstant.CodeTypeString.ErrorCode, errorCode); MessageBox.Show(errorDescription + " " + additionalMessage, errorCode, MessageBoxButtons.OK, icon); LogFile.WriteToTodaysLogFile( errorDescription + " " + additionalMessage, userID, errorCode, programName); return; } /// <summary> /// Get current assembly version /// </summary> /// <returns></returns> public static string GetCurrentAssemblyVersion() { string localAssembly = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.LocalAssemblyFolder); string serverAssembly = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.ServerAssemblyFolder); string LocalPath = @localAssembly; string LocalPathMainAssembly = @LocalPath + "fcm.exe"; AssemblyName localAssemblyName = new AssemblyName(); string versionLocal = ""; // Get the local version of the assembly if (File.Exists(LocalPathMainAssembly)) { localAssemblyName = AssemblyName.GetAssemblyName(LocalPathMainAssembly); versionLocal = localAssemblyName.Version.ToString(); } return versionLocal; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; namespace MackkadoITFramework.Security { public class SecurityRole { #region Properties public string Role {get;set;} public string Description{get;set;} #endregion Properties #region FieldName public struct FieldName { public const string Role = "Role"; public const string Description = "Description"; } #endregion FieldName /// <summary> /// List user settings for a given user /// </summary> /// <returns></returns> public static List<SecurityRole> List() { List<SecurityRole> roleList = new List<SecurityRole>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + SQLConcat() + " FROM SecurityRole " + " ORDER BY Role ASC " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var docItem = SetDocumentItem(reader); // Check if document exists // roleList.Add(docItem); } } } } return roleList; } /// <summary> /// Set user setting values /// </summary> /// <param name="reader"></param> /// <param name="prefix"></param> /// <returns></returns> private static SecurityRole SetDocumentItem(MySqlDataReader reader) { var role = new SecurityRole(); role.Role = reader[FieldName.Role].ToString(); role.Description = reader[FieldName.Description].ToString(); return role; } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> private static string SQLConcat() { string ret = " " + FieldName.Role + "," + FieldName.Description + " "; return ret; } /// <summary> /// Add role /// </summary> /// <returns></returns> public ResponseStatus Add() { ResponseStatus response = new ResponseStatus(); response.Message = "Role Added Successfully."; response.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; int _uid = 0; DateTime _now = DateTime.Today; if (Role == null) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "Role name is mandatory."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000008; response.Contents = 0; return response; } using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO SecurityRole " + "(Role, Description" + ")" + " VALUES " + "( " + " @Role " + ", @Description " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@Role", MySqlDbType.VarChar).Value = Role; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; connection.Open(); command.ExecuteNonQuery(); } } return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract { public class SCEmployee { public class EmployeeListResponse { public List<Employee> employeeList; public ResponseStatus response; } public class EmployeeReadResponse { public Employee employee; public ResponseStatus response; } public class EmployeeCreateResponse { public Employee employee; public ResponseStatus response; } } } <file_sep>-- UPDATE management.securityuserrole SET ISACTIVE='N' WHERE UNIQUEID=13; SELECT * FROM management.securityuserrole where FK_UserID="GC0001";<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCClientDocument.ServiceContract { public class SCClientDocument { public class ClientDocumentReadRequest { public HeaderInfo headerInfo; public ClientDocument clientDocument; } public class ClientDocumentReadResponse { public ResponseStatus responseStatus; public ClientDocument clientDocument; } public class ClientDocumentUpdateRequest { public HeaderInfo headerInfo; public ClientDocument clientDocument; } public class ClientDocumentUpdateResponse { public ResponseStatus responseStatus; public ClientDocument clientDocument; } } } <file_sep>using System; using System.Drawing; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; namespace fcm.Windows { public partial class UIRelatedReferenceData : Form { public UIRelatedReferenceData() { InitializeComponent(); } private void btnCancel_Click(object sender, EventArgs e) { this.Dispose(); } private void UIRelatedReferenceData_Load(object sender, EventArgs e) { LoadInitialValues(); } private void LoadInitialValues() { cbxRelatedCode.Items.Clear(); cbxTo.Items.Clear(); cbxFrom.Items.Clear(); foreach (var codetype in Cache.CachedInfo.ListOfCodeTypes) { cbxFrom.Items.Add(codetype.Code); cbxTo.Items.Add(codetype.Code); } foreach (var relatedCode in Cache.CachedInfo.ListOfRelatedCodes) { cbxRelatedCode.Items.Add(relatedCode.RelatedCodeID); } cbxRelatedCode.Items.Add("<<New>>"); } private void cbxFrom_SelectedIndexChanged(object sender, EventArgs e) { tvFrom.Nodes.Clear(); TreeNode root = new TreeNode("From " + cbxFrom.Text); tvFrom.Nodes.Add(root); foreach(var fromcode in Cache.CachedInfo.GetListOfCodeValue(cbxFrom.Text)) { TreeNode elementNode = new TreeNode(fromcode.ID); root.Nodes.Add(elementNode); elementNode.Tag = fromcode; // load linked values // var subitems = Cache.CachedInfo.GetListOfRelatedCodeValue(cbxRelatedCode.Text, cbxFrom.Text, fromcode.ID); foreach (var item in subitems) { TreeNode subitemNode = new TreeNode(item.FKCodeValueTo); subitemNode.Tag = item; elementNode.Nodes.Add(subitemNode); } } tvFrom.ExpandAll(); } private void cbxTo_SelectedIndexChanged(object sender, EventArgs e) { tvTo.Nodes.Clear(); TreeNode rootTo = new TreeNode("To " + cbxTo.Text); tvTo.Nodes.Add(rootTo); foreach (var tocode in Cache.CachedInfo.GetListOfCodeValue(cbxTo.Text)) { TreeNode element = new TreeNode(tocode.ID); rootTo.Nodes.Add(element); element.Tag = tocode; } tvTo.ExpandAll(); } private void btnCreate_Click(object sender, EventArgs e) { RelatedCode relcode = new RelatedCode(); relcode.RelatedCodeID = txtNewRelatedCode.Text; relcode.FKCodeTypeFrom = cbxFrom.Text; relcode.FKCodeTypeTo = cbxTo.Text; relcode.Description = txtRelatedCodeDescription.Text; if (string.IsNullOrEmpty(relcode.FKCodeTypeTo)) return; if (string.IsNullOrEmpty(relcode.FKCodeTypeFrom)) return; var response = BUSReferenceData.AddRelatedCodeType(relcode); ControllerUtils.ShowFCMMessage(response,Utils.UserID); // Reload is necessary since new code has been added. // Cache.CachedInfo.LoadRelatedCodeInCache(); LoadInitialValues(); } private void tvFrom_DragDrop(object sender, DragEventArgs e) { LinkValueToCode(sender, e); } private void LinkValueToCode(object sender, DragEventArgs e) { // Get selected document from tree // TreeNode tnDocumentSelectedTo = tvTo.SelectedNode; if (tnDocumentSelectedTo == null) return; var tndocselected = (CodeValue)tnDocumentSelectedTo.Tag; if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvFrom.PointToClient(new Point(e.X, e.Y)); destinationNode = tvFrom.GetNodeAt(pt); if (destinationNode == null) return; tnDocumentSelectedTo.Remove(); destinationNode.Nodes.Add(tnDocumentSelectedTo); // Add link to the database // CodeValue itemSelectedTo = new CodeValue(); itemSelectedTo = (CodeValue)tnDocumentSelectedTo.Tag; CodeValue destination = new CodeValue(); destination = (CodeValue)destinationNode.Tag; // New link to be created RelatedCodeValue rcv = new RelatedCodeValue(); rcv.FKRelatedCodeID = cbxRelatedCode.Text; rcv.FKCodeTypeFrom = destination.FKCodeType; rcv.FKCodeValueFrom = destination.ID; rcv.FKCodeTypeTo = itemSelectedTo.FKCodeType; rcv.FKCodeValueTo = itemSelectedTo.ID; var response = BUSReferenceData.AddRelatedCodeValue(rcv); ControllerUtils.ShowFCMMessage(response, Utils.UserID); Cache.CachedInfo.LoadRelatedCodeInCache(); } } private void tvFrom_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvTo_DragDrop(object sender, DragEventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvTo.SelectedNode; if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvTo.PointToClient(new Point(e.X, e.Y)); destinationNode = tvFrom.GetNodeAt(pt); if (tndocSelected == null) return; // If destination tree is the same as source tree, do nothing if (destinationNode.TreeView == tndocSelected.TreeView) return; } } private void tvTo_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvTo_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void cbxRelatedCode_SelectedIndexChanged(object sender, EventArgs e) { if (cbxRelatedCode.Text == "<<New>>") { txtNewRelatedCode.Focus(); cbxFrom.Enabled = true; cbxTo.Enabled = true; txtRelatedCodeDescription.Enabled = true; } else { cbxFrom.Enabled = false; cbxTo.Enabled = false; txtRelatedCodeDescription.Enabled = false; var relcodeinfo = Cache.CachedInfo.GetRelatedCode(cbxRelatedCode.Text); cbxFrom.Text = relcodeinfo.FKCodeTypeFrom; cbxTo.Text = relcodeinfo.FKCodeTypeTo; } } } } <file_sep>using System; using System.Collections.Generic; using System.Threading; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCFCMBackendStatus.Service; using MackkadoITFramework.Interfaces; using MackkadoITFramework.ProcessRequest; using MackkadoITFramework.Utils; using MackkadoITFramework.Helper; namespace ConsoleGenerateDocument { class Program : IOutputMessage { ProcessRequest processRequest; List<ProcessRequest> activeList; static void Main(string[] args) { Console.WriteLine("Start Time: {0}", DateTime.Now); int sleepMiliseconds = 10000; HeaderInfo.Instance.UserID = "SYSTEM"; HeaderInfo.Instance.CurrentDateTime = DateTime.Now; var arguments = new Arguments( args ); string processName = arguments ["processname"]; if (string.IsNullOrEmpty(processName)) processName = "DEBUG"; Program program = new Program(); ConnString.ConnectionString = ConnString.ConnectionStringServer; ConnString.ConnectionStringFramework = ConnString.ConnectionStringServer; LogFile.WriteToTodaysLogFile("Document Generation Server started " + DateTime.Now); Console.WriteLine("Document Generation Server started " + DateTime.Now); int i = 0; while (i <= 3) { i++; Console.WriteLine( "Running = " + DateTime.Now ); Console.WriteLine( "Process Name = " + processName ); // Check if there is a request // program.activeList = BUSProcessRequest.ListActiveRequests(); GenerateList( program, false, processName ); //program.activeList = BUSProcessRequest.ListUnfinishedRequests(); //GenerateList( program, true ); Console.WriteLine("Iteration # "+i.ToString()); Console.WriteLine("Sleeping for {0} miliseconds.", sleepMiliseconds); BUSFCMBackendStatus.ReportStatus(HeaderInfo.Instance, processName, "Sleeping..."); Thread.Sleep(sleepMiliseconds); } } private static void GenerateList( Program program, bool isRestart, string processName ) { #region startList if (program.activeList.Count > 0) { // If there is a request, process the request // foreach (var request in program.activeList) { request.SetStatusToStarted(); program.processRequest = request; // Update request to completed // if (request.Type == ProcessRequest.TypeValue.DOCUMENTGENERATION.ToString()) { // Find Values // var clientUID = 0; int clientSetID = 0; var overrideDocument = "Yes"; int clientDocumentUID = 0; string filename = " Full Set Generated"; foreach (var argument in request.argumentList) { if (argument.Code == ProcessRequestArguments.ProcessRequestCodeValues.CLIENTUID.ToString()) { clientUID = Convert.ToInt32(argument.Value); } if (argument.Code == ProcessRequestArguments.ProcessRequestCodeValues.CLIENTSETID.ToString()) { clientSetID = Convert.ToInt32(argument.Value); } if ( argument.Code == ProcessRequestArguments.ProcessRequestCodeValues.OVERRIDE.ToString() ) { overrideDocument = argument.Value; } if ( argument.Code == ProcessRequestArguments.ProcessRequestCodeValues.CLIENTDOCUID.ToString() ) { clientDocumentUID = Convert.ToInt32( argument.Value ); if ( clientDocumentUID > 0 ) { var clientDocument = BUSClientDocument.ClientDocumentReadS(clientDocumentUID); filename = " File: " + clientDocument.FileName; } } } var client = BUSClient.ClientRead( new ClientReadRequest() { clientUID = clientUID, headerInfo = HeaderInfo.Instance } ); // Send email to requester // string emailGraham = "<EMAIL>"; string emailDaniel = "<EMAIL>"; string emailSubject = "<> STARTED <> " + DateTime.Now + "<> generation requested by: " + request.RequestedByUser + " Client: " + clientUID + " " + client.client.Name + filename; string emailBody = "Generation Started: " + DateTime.Now + " <> " + emailSubject + " -- " ; if ( request.RequestedByUser.ToUpper() == "GC0001" ) { var resp1 = FCMEmail.SendEmailSimple( iRecipient: emailGraham, iSubject: emailSubject, iBody: emailBody ); } var resp2 = FCMEmail.SendEmailSimple( iRecipient: emailDaniel, iSubject: emailSubject, iBody: emailBody ); // 30.03.2012 // Mudar para processamento paralelo e async // // Generate Document // BUSFCMBackendStatus.ReportStatus( HeaderInfo.Instance, processName, "Before document generation starts." ); if ( clientDocumentUID > 0 ) { program.GenerateDocumentsForClient( clientUID, clientSetID, program, overrideDocument, clientDocumentUID, processName, request.RequestedByUser ); } else { program.GenerateFullSetOfDocumentsForClient( clientUID, clientSetID, program, overrideDocument, isRestart, processName, request.RequestedByUser ); } // Write output to database of logs and allow access online or // Write to a file and allow access online... // We can see the process of the request... request.SetStatusToCompleted(); HeaderInfo.Instance.UserID = request.RequestedByUser; HeaderInfo.Instance.CurrentDateTime = DateTime.Now; // Send email to requester // emailSubject = "<> ENDED <> " + DateTime.Now + "<> generation requested by: " + request.RequestedByUser + " Client: " + clientUID + " " + client.client.Name + filename; emailBody = "Generation Ended: " + DateTime.Now + " <> " + emailSubject + " -- " + "File Generated."; if ( request.RequestedByUser.ToUpper() == "GC0001" ) { var resp3 = FCMEmail.SendEmailSimple( iRecipient: emailGraham, iSubject: emailSubject, iBody: emailBody); } var resp4 = FCMEmail.SendEmailSimple( iRecipient: emailDaniel, iSubject: emailSubject, iBody: emailBody ); } } } #endregion } private void GenerateDocumentsForClient( int clientUID, int clientSetID, Program program, string overrideDocument, int clientDocumentuid, string processName, string userID ) { Console.WriteLine("Timer Time: {0}", DateTime.Now); AddOutputMessage( "Document generation starting...", processName, userID ); DocumentGeneration wdt = new DocumentGeneration(ClientID: clientUID, ClientDocSetID: clientSetID, UIoutput: program, OverrideDocuments: overrideDocument, inprocessName: processName, inuserID: userID ); //Thread t = new Thread(wdt.GenerateDocumentForClient); // Kick off a new thread //t.Start(); // Generate document // if ( clientDocumentuid <= 0 ) { wdt.GenerateDocumentForClient(); } else { wdt.GenerateSingleDocument( clientDocumentuid, isRestart: false, fixDestinationFolder: true ); } AddOutputMessage( "Generation Completed.", processName, userID ); } private void GenerateListDocumentsForClient( int clientUID, int clientSetID, Program program, string overrideDocument, List<int> listDocs, bool isRestart, string processName, string userID ) { Console.WriteLine( "Timer Time: {0}", DateTime.Now ); AddOutputMessage( "Document generation starting...", processName, userID ); DocumentGeneration wdt = new DocumentGeneration( ClientID: clientUID, ClientDocSetID: clientSetID, UIoutput: program, OverrideDocuments: overrideDocument, inprocessName: processName, inuserID: userID ); wdt.GenerateGroupOfDocuments(listDocs, isRestart); AddOutputMessage( "Generation Completed.", processName, userID ); } private void GenerateFullSetOfDocumentsForClient( int clientUID, int clientSetID, Program program, string overrideDocument, bool isRestart, string processName, string userID ) { Console.WriteLine( "Timer Time: {0}", DateTime.Now ); AddOutputMessage( "Document generation starting...", processName, userID ); DocumentGeneration wdt = new DocumentGeneration( ClientID: clientUID, ClientDocSetID: clientSetID, UIoutput: program, OverrideDocuments: overrideDocument, inprocessName: processName, inuserID: userID ); wdt.GenerateFullSetForClient( clientUID, clientSetID, isRestart ); AddOutputMessage( "Generation Completed.", processName, userID ); } public void Activate() { return; } public void AddErrorMessage( string errorMessage, string processName, string userID ) { string msg = processName + ": " + DateTime.Now + ": " + userID + ": " + "Program.cs" + ": " + errorMessage; ProcessRequestResults prr = new ProcessRequestResults(); prr.FKRequestUID = this.processRequest.UID; prr.FKClientUID = this.processRequest.FKClientUID; prr.Type = ProcessRequestResults.TypeValue.ERROR.ToString(); prr.Results = msg; prr.Add(); Console.WriteLine( msg ); LogFile.WriteToTodaysLogFile( errorMessage, processName ); LogFile.WriteToTodaysLogFile( what: errorMessage, userID: userID, messageCode: "", programName: "UIOutputMessage.cs", processname: processName ); } public void AddOutputMessage( string outputMessage, string processName, string userID) { string msg = processName + ": " + DateTime.Now + ": " + userID + ": " + "Program.cs" + ": " + outputMessage; ProcessRequestResults prr = new ProcessRequestResults(); prr.FKRequestUID = this.processRequest.UID; prr.FKClientUID = this.processRequest.FKClientUID; prr.Type = ProcessRequestResults.TypeValue.INFORMATIONAL.ToString(); prr.Results = processName + " " + outputMessage; prr.Add(); Console.WriteLine( msg ); LogFile.WriteToTodaysLogFile( what: outputMessage, userID: userID, messageCode: "", programName: "UIOutputMessage.cs", processname: processName ); } public void UpdateProgressBar(double value, DateTime estimatedTime, int documentsToBeGenerated = 0) { return; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using MackkadoITFramework.APIDocument; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Interfaces; using System.Reflection; namespace MackkadoITFramework.APIDocument { public class VisioTasks { } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIDocumentSetEdit : Form { public UIDocumentSetEdit() { InitializeComponent(); } private void UIDocumentSetEdit_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCClient; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; namespace fcm.Windows { public partial class UIClientDocumentLink : Form { DocumentList docoList; int SelectedParentDocumentUID; private DocumentSetList dsl; private int documentSetUID; private string documentSetText; private Document parentDocument; private ClientDocument selectedClientDocument; private Client selectedClient; private ClientDocumentSet selectedClientDocumentSet; public UIClientDocumentLink(string clientTxt, string clientSetTxt) { InitializeComponent(); parentDocument = new Document(); cbxClient.Text = clientTxt; cbxDocumentSet.Text = clientSetTxt; // Get Client UID selectedClient = new Client(HeaderInfo.Instance); selectedClient.UID = Utils.ClientID; var repclient = RepClient.Read(selectedClient.UID); var response = repclient.responseStatus; // var response = selectedClient.Read(); // Get Client Document Set UID var docSetUID = cbxDocumentSet.Text; string[] docoSet = docSetUID.Split(';'); documentSetUID = Convert.ToInt32(docoSet[1]); selectedClientDocumentSet = new ClientDocumentSet(); selectedClientDocumentSet.UID = documentSetUID; selectedClientDocumentSet.FKClientUID = selectedClient.UID; cbxLinkType.Items.Add(FCMConstant.DocumentLinkType.PROJECTPLAN); cbxLinkType.Items.Add(FCMConstant.DocumentLinkType.APPENDIX); cbxLinkType.Text = FCMConstant.DocumentLinkType.PROJECTPLAN; } // ------------------------------------------------------- // Load Event // ------------------------------------------------------- private void UIClientDocumentLink_Load(object sender, EventArgs e) { // Get client list from background and load into the list // ------------------------------------------------------- foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // Get selected client from the background // ------------------------------------------------------- // cbxClient.SelectedIndex = Utils.ClientIndex; // Load document in the treeview // ------------------------------------------------------- Document root = new Document(); root.CUID = "ROOT"; root.Name = "FCM Documents"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); // Using Business Layer root = BUSDocument.GetRootDocument(); // Populate document list // ------------------------------------------------------- PopulateDocumentCombo('N'); // List Available Documents // ------------------------------------------------------- loadDocumentList(); // List Documents Linked to selected document // ------------------------------------------------------- loadLinkedDocuments(parentDocument); } // ------------------------------------------------------- // Populate combo box with list of client Documents // ------------------------------------------------------- private void PopulateDocumentCombo(char ProjectPlan) { // List documents // ------------------------------------------------------- var documentSetList = new ClientDocument(); // documentSetList.List(Utils.ClientID, Utils.ClientSetID); var cdlr = new BUSClientDocument.ClientDocumentListRequest(); cdlr.clientUID = Utils.ClientID; cdlr.clientDocumentSetUID = Utils.ClientSetID; var response = BUSClientDocument.List( cdlr ); documentSetList.clientDocSetDocLink = response.clientList; cbxDocument.Items.Clear(); cbxDocument.SelectedText = ""; int i = 0; foreach (var doco in documentSetList.clientDocSetDocLink) { string item = doco.document.UID + ";" + doco.document.CUID + ";" + doco.document.Name; cbxDocument.Items.Add(item); if (i == 0) { cbxDocument.ResetText(); cbxDocument.SelectedText = item; } if (i == 0) { cbxDocument.Text = item; } i++; } } // ---------------------------------------------------------------------- // List documents available for selection in list box tvListOfDocuments // ---------------------------------------------------------------------- public void loadDocumentList() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvListOfDocuments.ImageList = imageList; // Clear nodes tvListOfDocuments.Nodes.Clear(); var docoList = new ClientDocument(); // docoList.List(Utils.ClientID, Utils.ClientSetID); var cdlr = new BUSClientDocument.ClientDocumentListRequest(); cdlr.clientUID = Utils.ClientID; cdlr.clientDocumentSetUID = Utils.ClientSetID; var response = BUSClientDocument.List( cdlr ); // Load document in the treeview // // docoList.ListInTree(tvListOfDocuments); Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); root = BUSDocument.GetRootDocument(); // docoList.ListInTree(tvListOfDocuments, "CLIENT"); BUSClientDocument.ListInTree( docoList, tvListOfDocuments, "CLIENT" ); tvListOfDocuments.ExpandAll(); } private void ParentHasChanged() { var x = cbxDocument.Text; if (string.IsNullOrEmpty(x)) return; string[] doco = x.Split(';'); parentDocument.UID = Convert.ToInt32(doco[0]); // parentDocument.Read(); //parentDocument = RepDocument.Read(false, parentDocument.UID); // Using Business Layer var documentReadRequest = new DocumentReadRequest(); documentReadRequest.UID = parentDocument.UID; documentReadRequest.CUID = ""; documentReadRequest.retrieveVoidedDocuments = false; var docreadresp = BUSDocument.DocumentRead(documentReadRequest); if (docreadresp.response.ReturnCode == 0001) { // all good } else { MessageBox.Show(docreadresp.response.Message); return; } parentDocument = docreadresp.document; // // Get document set if (string.IsNullOrEmpty(cbxDocumentSet.Text)) { documentSetUID = 1; } else { var docSetUID = cbxDocumentSet.Text; string[] docoSet = docSetUID.Split(';'); // The first is the client id, the second is the document set id // documentSetUID = Convert.ToInt32(docoSet[1]); } ClientDocumentLinkList list = ClientDocumentLinkList.ListRelatedDocuments( selectedClient.UID, documentSetUID, parentDocument.UID, cbxLinkType.Text); loadLinkedDocuments(parentDocument); } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { ParentHasChanged(); } // ------------------------------------------ // List Documents // ------------------------------------------ public void loadLinkedDocuments(Document document) { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvLinkedDocuments.ImageList = imageList; // Clear nodes tvLinkedDocuments.Nodes.Clear(); var docoList = ClientDocumentLinkList.ListRelatedDocuments( selectedClient.UID, documentSetUID, document.UID, cbxLinkType.Text); // Load document in the treeview // // docoList.ListInTree(tvLinkedDocuments); Document root = new Document(); root.CUID = document.CUID; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = document.UID; // root.Read(); // root = RepDocument.Read(false, document.UID); // Using Business Layer var documentReadRequest = new DocumentReadRequest(); documentReadRequest.UID = document.UID; documentReadRequest.CUID = ""; documentReadRequest.retrieveVoidedDocuments = false; var docreadresp = BUSDocument.DocumentRead(documentReadRequest); if (docreadresp.response.ReturnCode == 0001) { // all good } else { MessageBox.Show(docreadresp.response.Message); return; } root = docreadresp.document; // ControllerUtils.ListInTree( tvLinkedDocuments, docoList, root ); tvLinkedDocuments.ExpandAll(); } private void tvListOfDocuments_DoubleClick(object sender, EventArgs e) { AddSelectedDocument(); } private void AddSelectedDocument() { TreeNode tn = new TreeNode(); tn = tvListOfDocuments.SelectedNode; TreeNode clone = new TreeNode(); clone = (TreeNode)tn.Clone(); tvLinkedDocuments.Nodes[0].Nodes.Add(clone); } private void cbxDocument_SelectedIndexChanged(object sender, EventArgs e) { ParentHasChanged(); } // --------------------------------------------------------------------------------- // Save // --------------------------------------------------------------------------------- private void tsbSave_Click(object sender, EventArgs e) { if (parentDocument.UID <= 0) { MessageBox.Show("Main document is not selected."); return; } foreach (TreeNode tn in tvLinkedDocuments.Nodes[0].Nodes) { var nodeType = tn.Tag.GetType().Name; if (nodeType == "scClientDocSetDocLink") { var doc = new scClientDocSetDocLink(); doc = (scClientDocSetDocLink)tn.Tag; // Add parentClientDocument and childClientDocument... Daniel 17/08/2010 // ClientDocumentLink.LinkDocuments( clientUID: selectedClient.UID, clientDocumentSetUID: selectedClientDocumentSet.UID, parentDocumentUID: parentDocument.UID, childDocumentUID: doc.document.UID, LinkType: cbxLinkType.Text); } if (nodeType == "Document") { Document doc = new Document(); doc = (Document)tn.Tag; ClientDocumentLink.LinkDocuments( clientUID: selectedClient.UID, clientDocumentSetUID: selectedClientDocumentSet.UID, parentDocumentUID: parentDocument.UID, childDocumentUID: doc.UID, LinkType: cbxLinkType.Text); } } MessageBox.Show("Saved successfully."); } private void tsmiExit_Click(object sender, EventArgs e) { this.Close(); } private void tsbtnDelete_Click(object sender, EventArgs e) { RemoveDocument(); } // Remove document from selected list // private void RemoveDocument() { TreeNode tn = new TreeNode(); tn = tvLinkedDocuments.SelectedNode; var nodeType = tn.Tag.GetType().Name; if (nodeType == "Document") { Document doc = new Document(); doc = (Document)tn.Tag; ClientDocumentLink dl = new ClientDocumentLink(); // Logically delete the record if the record is commited. if (dl.Read(ParentID:parentDocument.UID, ChildID: doc.UID, LinkType: cbxLinkType.Text, clientUID: Utils.ClientID, clientDocumentSetUID: Utils.ClientSetID)) dl.Delete(dl.UID); tn.Remove(); } if (nodeType == "ClientDocumentLink") { ClientDocumentLink clientDocLink = new ClientDocumentLink(); clientDocLink = (ClientDocumentLink)tn.Tag; ClientDocumentLink dl = new ClientDocumentLink(); // Logically delete the record if the record is commited. if (dl.Read( parentDocument.UID, clientDocLink.FKChildDocumentUID, cbxLinkType.Text, Utils.ClientID, Utils.ClientSetID)) dl.Delete(dl.UID); tn.Remove(); } } private void tvLinkedDocuments_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvLinkedDocuments.SelectedNode = tvLinkedDocuments.GetNodeAt( e.X, e.Y ); } } private void tvListOfDocuments_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvListOfDocuments.SelectedNode = tvListOfDocuments.GetNodeAt( e.X, e.Y ); } } } } <file_sep>using System; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentLink { public int UID; public int FKParentDocumentUID; public int FKChildDocumentUID; public string LinkType; public Model.ModelDocument.Document documentFrom; public Model.ModelDocument.Document documentTo; // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM DocumentLink"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Add new Link // ----------------------------------------------------- public void Add() { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO DocumentLink " + " ( " + " UID " + ",FKParentDocumentUID " + ",FKChildDocumentUID" + ",LinkType" + ",IsVoid" + ")" + " VALUES " + " ( " + " @UID " + ", @FKParentDocumentUID " + ", @FKChildDocumentUID " + ", @LinkType " + ", @IsVoid" + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add("@FKParentDocumentUID", MySqlDbType.Int32).Value = FKParentDocumentUID; command.Parameters.Add("@FKChildDocumentUID", MySqlDbType.Int32).Value = FKChildDocumentUID; command.Parameters.Add("@LinkType", MySqlDbType.VarChar).Value = LinkType; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'N'; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Logical Delete // ----------------------------------------------------- public void Delete(int UID) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE DocumentLink " + " SET " + " IsVoid = @IsVoid" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Save Links // ----------------------------------------------------- public static void LinkDocuments(int ParentID, int ChildID, string LinkType) { DocumentLink findOne = new DocumentLink(); if (findOne.Read(ParentID, ChildID, LinkType)) { // Already exists } else { findOne.LinkType = LinkType; findOne.FKParentDocumentUID = ParentID; findOne.FKChildDocumentUID = ChildID; findOne.Add(); } } // ----------------------------------------------------- // Get Link details // ----------------------------------------------------- public bool Read(int ParentID, int ChildID, string LinkType) { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKParentDocumentUID " + " ,FKChildDocumentUID " + " ,LinkType " + " FROM DocumentLink" + " WHERE IsVoid = 'N' " + " AND FKParentDocumentUID = '{0}'" + " AND FKChildDocumentUID = '{1}'" + " AND LinkType = '{2}' ", ParentID, ChildID, LinkType); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.FKParentDocumentUID = Convert.ToInt32(reader["FKParentDocumentUID"].ToString()); this.FKChildDocumentUID = Convert.ToInt32(reader["FKChildDocumentUID"].ToString()); this.LinkType = reader["LinkType"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Get Link details // ----------------------------------------------------- public bool Read() { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKParentDocumentUID " + " ,FKChildDocumentUID " + " ,LinkType " + " FROM DocumentLink" + " WHERE CUID = '{0}'", this.UID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.FKParentDocumentUID = Convert.ToInt32(reader["FKParentDocumentUID "].ToString()); this.FKChildDocumentUID = Convert.ToInt32(reader["FKChildDocumentUID"].ToString()); this.LinkType = reader["LinkType"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } } } <file_sep>using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using MackkadoITFramework.APIDocument; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.UserSettingsNS; using MackkadoITFramework.Utils; namespace MackkadoITFramework.Helper { public static class Utils { public static ImageList imageList; private static string userID; private static int clientID; private static int clientSetID; private static string clientSetText; private static string clientName; //private static List<Client.Client> clientList; private static int clientIndex; private static int imageLogoStartsFrom; // private static string fcmenvironment; private static UserSettings _UserSettingsCache; public static DateTime MinDate { get { return new DateTime(1901, 01, 01); } } public static UserSettings UserSettingsCache { set { _UserSettingsCache = value; } get { return _UserSettingsCache; } } /// <summary> /// Read or Write the userID in memory. /// </summary> public static string UserID { set { userID = value; // Save last user id to database CodeValue cv = new CodeValue(); cv.FKCodeType = "LASTINFO"; cv.ID = "USERID"; cv.Read(false); cv.ValueExtended = UserID; cv.Save(); } get { return userID; } } public static string ClientSetText { set { clientSetText = value; } get { return clientSetText; } } public static int ClientSetID { set { clientSetID = value; } get { return clientSetID; } } public static int ClientIndex { // set { clientIndex = value; } get { return clientIndex; } } public static string ClientName { set { clientName = value; } get { return clientName; } } public static int ImageLogoStartsFrom { set { imageLogoStartsFrom = value; } get { return imageLogoStartsFrom; } } //public static List<Client.Client> ClientList //{ // set { clientList = value; } // get { return clientList; } //} public static string FCMenvironment { get; set; } public struct InformationType { public const string IMAGE = "IMAGE"; public const string FIELD = "FIELD"; public const string VARIABLE = "VARIABLE"; } public struct EnvironmentList { public const string WEB = "WEB"; public const string LOCAL = "LOCAL"; } public struct SaveType { public const string NEWONLY = "NEWONLY"; public const string UPDATE = "UPDATE"; } /// <summary> /// Indicates the source of the document. It could be FCM or Client /// </summary> public struct SourceCode { public const string CLIENT = "CLIENT"; public const string FCM = "FCM"; } public struct RecordType { public const string FOLDER = "FOLDER"; public const string DOCUMENT = "DOCUMENT"; public const string APPENDIX = "APPENDIX"; } public struct DocumentType { public const string FOLDER = "FOLDER"; public const string WORD = "WORD"; public const string EXCEL = "EXCEL"; public const string PDF = "PDF"; public const string UNDEFINED = "UNDEFINED"; public const string APPENDIX = "APPENDIX"; } public struct UserRole { public const string Admin = "ADMIN"; public const string PowerUser = "POWERUSER"; public const string Client = "CLIENT"; public const string User = "USER"; } /// <summary> /// Represents action to database /// </summary> public struct SQLAction { public const string CREATE = "CREATE"; public const string UPDATE = "UPDATE"; } public struct SYSTSET { public const string WEBPORT = "%WEBPORT%"; public const string HOSTIPADDRESS = "%HOSTIPADDRESS%"; } public struct DocumentLinkType { public const string PROJECTPLAN = "PROJPLAN"; public const string APPENDIX = "APPENDIX"; } // It transforms the reference path into a physical path and add name to it // public static string getFilePathName( string path, string name = "" ) { string filePathName = path + "\\" + name; string fullPathFileName = ""; var fcmPort = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, SYSTSET.WEBPORT); var fcmHost = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, SYSTSET.HOSTIPADDRESS); // Get template folder var templateFolder = CodeValue.GetCodeValueExtended("SYSTSET", MakConstant.SYSFOLDER.TEMPLATEFOLDER); // Get template folder var clientFolder = CodeValue.GetCodeValueExtended("SYSTSET", MakConstant.SYSFOLDER.CLIENTFOLDER); // Get version folder var versionFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.VERSIONFOLDER); // Get logo folder var logoFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGOFOLDER); // Get log file folder var logFileFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGFILEFOLDER); // WEB if (FCMenvironment == EnvironmentList.WEB) { string rpath = path.Replace(@"\", @"/"); path = rpath; // Different for WEB filePathName = path + @"/" + name; // ---------------------- // Get WEB template folder // ---------------------- templateFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBTEMPLATEFOLDER); templateFolder = templateFolder.Replace(SYSTSET.WEBPORT, fcmPort); templateFolder = templateFolder.Replace(SYSTSET.HOSTIPADDRESS, fcmHost); // ---------------------- // Get WEB client folder // ---------------------- clientFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBCLIENTFOLDER); clientFolder = clientFolder.Replace(SYSTSET.WEBPORT, fcmPort); clientFolder = clientFolder.Replace(SYSTSET.HOSTIPADDRESS, fcmHost); // ---------------------- // Get WEB version folder // ---------------------- versionFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBVERSIONFOLDER); versionFolder = versionFolder.Replace( SYSTSET.WEBPORT, fcmPort ); versionFolder = versionFolder.Replace(SYSTSET.HOSTIPADDRESS, fcmHost); // ---------------------- // Get WEB logo folder // ---------------------- logoFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBLOGOFOLDER); logoFolder = logoFolder.Replace(SYSTSET.WEBPORT, fcmPort); logoFolder = logoFolder.Replace(SYSTSET.HOSTIPADDRESS, fcmHost); // -------------------------------------------------------------- // Get WEB LOG folder - This is LOG for recording what happened // -------------------------------------------------------------- logFileFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGFILEFOLDER); logFileFolder = logFileFolder.Replace(SYSTSET.WEBPORT, fcmPort); logFileFolder = logFileFolder.Replace(SYSTSET.HOSTIPADDRESS, fcmHost); } if (filePathName.Contains(MakConstant.SYSFOLDER.TEMPLATEFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.TEMPLATEFOLDER, templateFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.CLIENTFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.CLIENTFOLDER, clientFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.VERSIONFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.VERSIONFOLDER, versionFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.LOGOFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.LOGOFOLDER, logoFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.LOGFILEFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.LOGFILEFOLDER, logFileFolder); } if (String.IsNullOrEmpty(fullPathFileName)) fullPathFileName = path + "\\" + name; fullPathFileName = fullPathFileName.Replace("\r", ""); return fullPathFileName; } // It transforms the reference path into a physical path and add name to it // public static string getFilePathNameLOCAL( string path, string name = "" ) { string filePathName = ""; if ( string.IsNullOrEmpty( name ) ) { filePathName = path; } else { filePathName = path + "\\" + name; } string fullPathFileName = ""; var fcmPort = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, SYSTSET.WEBPORT ); var fcmHost = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, SYSTSET.HOSTIPADDRESS ); // Get template folder var templateFolder = CodeValue.GetCodeValueExtended( "SYSTSET", MakConstant.SYSFOLDER.TEMPLATEFOLDER ); // Get template folder var clientFolder = CodeValue.GetCodeValueExtended( "SYSTSET", MakConstant.SYSFOLDER.CLIENTFOLDER ); // Get version folder var versionFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.VERSIONFOLDER ); // Get logo folder var logoFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGOFOLDER ); // Get log file folder var logFileFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGFILEFOLDER ); if ( filePathName.Contains( MakConstant.SYSFOLDER.TEMPLATEFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.TEMPLATEFOLDER, templateFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.CLIENTFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.CLIENTFOLDER, clientFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.VERSIONFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.VERSIONFOLDER, versionFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.LOGOFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.LOGOFOLDER, logoFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.LOGFILEFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.LOGFILEFOLDER, logFileFolder ); } if ( String.IsNullOrEmpty( fullPathFileName ) ) fullPathFileName = path + "\\" + name; fullPathFileName = fullPathFileName.Replace( "\r", "" ); return fullPathFileName; } // It transforms the reference path into a physical path and add name to it // public static string getFilePathNameWEB( string path, string name = "" ) { string filePathName = ""; if ( string.IsNullOrEmpty( name ) ) { filePathName = path; } else { filePathName = path + "\\" + name; } string fullPathFileName = ""; var fcmPort = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, SYSTSET.WEBPORT ); var fcmHost = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, SYSTSET.HOSTIPADDRESS ); // Get template folder var templateFolder = CodeValue.GetCodeValueExtended( "SYSTSET", MakConstant.SYSFOLDER.TEMPLATEFOLDER ); // Get template folder var clientFolder = CodeValue.GetCodeValueExtended( "SYSTSET", MakConstant.SYSFOLDER.CLIENTFOLDER ); // Get version folder var versionFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.VERSIONFOLDER ); // Get logo folder var logoFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGOFOLDER ); // Get log file folder var logFileFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGFILEFOLDER ); // Get WEB Paths // string rpath = path.Replace( @"\", @"/" ); path = rpath; // Different for WEB if ( string.IsNullOrEmpty( name ) ) { filePathName = path ; } else { filePathName = path + @"/" + name; } // ---------------------- // Get WEB template folder // ---------------------- templateFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBTEMPLATEFOLDER ); templateFolder = templateFolder.Replace( SYSTSET.WEBPORT, fcmPort ); templateFolder = templateFolder.Replace( SYSTSET.HOSTIPADDRESS, fcmHost ); // ---------------------- // Get WEB client folder // ---------------------- clientFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBCLIENTFOLDER ); clientFolder = clientFolder.Replace( SYSTSET.WEBPORT, fcmPort ); clientFolder = clientFolder.Replace( SYSTSET.HOSTIPADDRESS, fcmHost ); // ---------------------- // Get WEB version folder // ---------------------- versionFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBVERSIONFOLDER ); versionFolder = versionFolder.Replace( SYSTSET.WEBPORT, fcmPort ); versionFolder = versionFolder.Replace( SYSTSET.HOSTIPADDRESS, fcmHost ); // ---------------------- // Get WEB logo folder // ---------------------- logoFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.WEBLOGOFOLDER ); logoFolder = logoFolder.Replace( SYSTSET.WEBPORT, fcmPort ); logoFolder = logoFolder.Replace( SYSTSET.HOSTIPADDRESS, fcmHost ); // -------------------------------------------------------------- // Get WEB LOG folder - This is LOG for recording what happened // -------------------------------------------------------------- logFileFolder = CodeValue.GetCodeValueExtended( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGFILEFOLDER ); logFileFolder = logFileFolder.Replace( SYSTSET.WEBPORT, fcmPort ); logFileFolder = logFileFolder.Replace( SYSTSET.HOSTIPADDRESS, fcmHost ); if ( filePathName.Contains( MakConstant.SYSFOLDER.TEMPLATEFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.TEMPLATEFOLDER, templateFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.CLIENTFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.CLIENTFOLDER, clientFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.VERSIONFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.VERSIONFOLDER, versionFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.LOGOFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.LOGOFOLDER, logoFolder ); } if ( filePathName.Contains( MakConstant.SYSFOLDER.LOGFILEFOLDER ) ) { fullPathFileName = filePathName.Replace( MakConstant.SYSFOLDER.LOGFILEFOLDER, logFileFolder ); } if ( String.IsNullOrEmpty( fullPathFileName ) ) fullPathFileName = path + "\\" + name; fullPathFileName = fullPathFileName.Replace( "\r", "" ); return fullPathFileName; } // It transforms the reference path into a physical path and add name to it // public static string GetPathNameTBD(string path) { string filePathName = path; string fullPathFileName = ""; // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.TEMPLATEFOLDER); // Get main client folder var clientFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.CLIENTFOLDER); // Get version folder var versionFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.VERSIONFOLDER); // Get logo folder var logoFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.LOGOFOLDER); if (filePathName.Contains(MakConstant.SYSFOLDER.TEMPLATEFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.TEMPLATEFOLDER, templateFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.CLIENTFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.CLIENTFOLDER, clientFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.VERSIONFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.VERSIONFOLDER, versionFolder); } if (filePathName.Contains(MakConstant.SYSFOLDER.LOGOFOLDER)) { fullPathFileName = filePathName.Replace(MakConstant.SYSFOLDER.LOGOFOLDER, logoFolder); } return fullPathFileName; } // // It returns a reference path // public static string getReferenceFilePathName(string path) { string filePathName = path; string referencePathFileName = ""; // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.TEMPLATEFOLDER); var templateFolderPhysical = CodeValue.GetCodeValueExtraString( MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.TEMPLATEFOLDER ); // Get template folder var clientFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.CLIENTFOLDER); if (filePathName.Contains(templateFolder)) { referencePathFileName = filePathName.Replace(templateFolder, MakConstant.SYSFOLDER.TEMPLATEFOLDER); } if ( filePathName.Contains( templateFolderPhysical ) ) { referencePathFileName = filePathName.Replace( templateFolderPhysical, MakConstant.SYSFOLDER.TEMPLATEFOLDER ); } if (filePathName.Contains(clientFolder)) { referencePathFileName = filePathName.Replace(clientFolder, MakConstant.SYSFOLDER.CLIENTFOLDER); } if (String.IsNullOrEmpty(referencePathFileName)) referencePathFileName = path; return referencePathFileName; } /// <summary> /// It returns the opposite path (client to template or vice-versa) /// </summary> /// <param name="path"></param> /// <returns></returns> public static string getOppositePath(string path) { string filePathName = path; string opposite = ""; if (filePathName.Contains(MakConstant.SYSFOLDER.TEMPLATEFOLDER)) { opposite = filePathName.Replace(MakConstant.SYSFOLDER.TEMPLATEFOLDER, MakConstant.SYSFOLDER.CLIENTFOLDER); } if (filePathName.Contains(MakConstant.SYSFOLDER.CLIENTFOLDER)) { opposite = filePathName.Replace(MakConstant.SYSFOLDER.CLIENTFOLDER, MakConstant.SYSFOLDER.TEMPLATEFOLDER); } if (String.IsNullOrEmpty(opposite)) opposite = path; return opposite; } /// <summary> /// It returns the path of the document inside the client path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetClientPathInside(string path) { string filePathName = path; string opposite = ""; if (filePathName.Contains(MakConstant.SYSFOLDER.TEMPLATEFOLDER)) { opposite = filePathName.Replace(MakConstant.SYSFOLDER.TEMPLATEFOLDER, ""); } //if (string.IsNullOrEmpty(opposite)) // opposite = path; return opposite; } /// <summary> /// It returns the Client path /// </summary> /// <param name="path"></param> /// <param name="destinationPath"></param> /// <returns></returns> public static string GetClientPath(string path, string destinationPath) { string destination = ""; string ultimateDestination = ""; if (path.Contains(MakConstant.SYSFOLDER.TEMPLATEFOLDER)) { destination = path.Replace(MakConstant.SYSFOLDER.TEMPLATEFOLDER, MakConstant.SYSFOLDER.CLIENTFOLDER); } // path = %TEMPLATEFOLDER%\\something\\ // destinationPath = %CLIENTFOLDER%\\CLIENT01\\ // destination = %CLIENTFOLDER%\\something\\ // // stripDestination = \\something\\ string stripDestination = destination.Replace(MakConstant.SYSFOLDER.CLIENTFOLDER, ""); // ultimateDestination = \\Client01\\ ultimateDestination = destinationPath.Replace(MakConstant.SYSFOLDER.CLIENTFOLDER, ""); ultimateDestination = MakConstant.SYSFOLDER.CLIENTFOLDER + // %CLIENTFOLDER% ultimateDestination + // \\client01\\ stripDestination; // \\something\\ if (String.IsNullOrEmpty(ultimateDestination)) ultimateDestination = path; return ultimateDestination; } /// <summary> /// It returns the Client path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetVersionPath(string path) { string destination = path; if (path.Contains(MakConstant.SYSFOLDER.TEMPLATEFOLDER)) { destination = path.Replace(MakConstant.SYSFOLDER.TEMPLATEFOLDER, MakConstant.SYSFOLDER.VERSIONFOLDER); } return destination; } ///// <summary> ///// Open document for Document type ///// </summary> ///// <param name="document"></param> //public static void OpenDocument(Document.Document document, object vkReadOnly) //{ // if (document.DocumentType == Utils.DocumentType.WORD) // { // string filePathName = // Utils.getFilePathName(document.Location, // document.Name ); // WordDocumentTasks.OpenDocument(filePathName, vkReadOnly); // } //} // Open document for Location and Name // public static ResponseStatus OpenDocument( string Location, string Name, string Type, object vkReadOnly, bool isFromWeb ) { if (Type == DocumentType.WORD) { string filePathName = getFilePathName(Location, Name); var response = WordDocumentTasks.OpenDocument(filePathName, vkReadOnly, isFromWeb); if ( response.ReturnCode < 1 ) { return response; } } if (Type == DocumentType.EXCEL) { string filePathName = getFilePathName(Location, Name); var response = ExcelSpreadsheetTasks.OpenDocument(filePathName); if (response.ReturnCode < 1) { return response; } } if (Type == DocumentType.PDF) { string filePathName = getFilePathName( Location, Name ); Process proc = new Process(); var adobe = CodeValue.GetCodeValueExtended( iCodeType: MakConstant.CodeTypeString.SYSTSET, iCodeValueID: "PDFEXEPATH" ); if (!File.Exists( adobe )) { MessageBox.Show( "I can't find Adobe Reader. Please configure SYSTSET.PDFEXTPATH." ); var error = new ResponseStatus(MessageType.Error); error.Message = "Adobe Reader can't be found. Please configure SYSTSET.PDFEXTPATH."; return error; } proc.StartInfo.FileName = adobe; proc.StartInfo.Arguments = filePathName; proc.Start(); } return new ResponseStatus( MessageType.Informational ); } /// <summary> /// Return image according to Record Type /// </summary> /// <param name="RecordType"></param> /// <returns></returns> public static int ImageSelect(string RecordType) { int image = MakConstant.Image.Document; switch (RecordType) { case Utils.RecordType.DOCUMENT: image = MakConstant.Image.Document; break; case Utils.RecordType.APPENDIX: image = MakConstant.Image.Document; break; case Utils.RecordType.FOLDER: image = MakConstant.Image.Folder; break; default: image = MakConstant.Image.Document; break; } return image; } /// <summary> /// Get Logo location for a client. /// </summary> /// <param name="clientUID"></param> /// <returns></returns> public static string GetImageUrl( string DocumentType, string curEnvironment = EnvironmentList.LOCAL ) { string image = ""; string logoPath = ""; string logoName = ""; string logoPathName = ""; FCMenvironment = curEnvironment; switch (DocumentType) { case Utils.DocumentType.WORD: logoName = MakConstant.ImageFileName.Document; break; case Utils.DocumentType.EXCEL: logoName = MakConstant.ImageFileName.Excel; break; case Utils.DocumentType.FOLDER: logoName = MakConstant.ImageFileName.Folder; break; case Utils.DocumentType.PDF: logoName = MakConstant.ImageFileName.PDF; break; default: logoName = MakConstant.ImageFileName.Document; break; } // Set no icon image if necessary // logoPath = MakConstant.SYSFOLDER.LOGOFOLDER; logoName = logoName.Replace( MakConstant.SYSFOLDER.LOGOFOLDER, String.Empty ); logoPathName = getFilePathName( logoPath, logoName ); return logoPathName; } /// <summary> /// Get image for file /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <returns></returns> public static int GetFileImage(char source, char destination, string documentType ) { int image = MakConstant.Image.WordFileSourceNoDestinationNo; if (source == 'Y') { if (destination == 'Y') { // Source = "Y"; Destination = "Y" switch (documentType) { case DocumentType.WORD: image = MakConstant.Image.WordFileSourceYesDestinationYes; break; case DocumentType.EXCEL: image = MakConstant.Image.ExcelFileSourceYesDestinationYes; break; case DocumentType.PDF: image = MakConstant.Image.PDFFileSourceYesDestinationYes; break; case DocumentType.FOLDER: image = MakConstant.Image.Folder; break; case DocumentType.APPENDIX: image = MakConstant.Image.Appendix; break; } } else { // Source = "Y"; Destination = "N" image = MakConstant.Image.WordFileSourceYesDestinationNo; switch (documentType) { case DocumentType.WORD: image = MakConstant.Image.WordFileSourceYesDestinationNo; break; case DocumentType.EXCEL: image = MakConstant.Image.ExcelFileSourceYesDestinationNo; break; case DocumentType.PDF: image = MakConstant.Image.PDFFileSourceYesDestinationNo; break; case DocumentType.FOLDER: image = MakConstant.Image.Folder; break; case DocumentType.APPENDIX: image = MakConstant.Image.Appendix; break; } } } else { if (destination == 'Y') { // Source = "N"; Destination = "Y" image = MakConstant.Image.WordFileSourceNoDestinationYes; switch (documentType) { case DocumentType.WORD: image = MakConstant.Image.WordFileSourceNoDestinationYes; break; case DocumentType.EXCEL: image = MakConstant.Image.ExcelFileSourceNoDestinationYes; break; case DocumentType.PDF: image = MakConstant.Image.PDFFileSourceNoDestinationYes; break; case DocumentType.FOLDER: image = MakConstant.Image.Folder; break; case DocumentType.APPENDIX: image = MakConstant.Image.Appendix; break; } } else { // Source = "N"; Destination = "N" image = MakConstant.Image.WordFileSourceNoDestinationNo; switch (documentType) { case DocumentType.WORD: image = MakConstant.Image.WordFileSourceNoDestinationNo; break; case DocumentType.EXCEL: image = MakConstant.Image.ExcelFileSourceNoDestinationNo; break; case DocumentType.PDF: image = MakConstant.Image.PDFFileSourceNoDestinationNo; break; case DocumentType.FOLDER: image = MakConstant.Image.Folder; break; case DocumentType.APPENDIX: image = MakConstant.Image.Appendix; break; } } } return image; } /// <summary> /// Retrieves cached value for user settings /// </summary> /// <returns></returns> public static string UserSettingGetCacheValue( UserSettings userSettings) { string valueReturned = ""; if (UserSettingsCache == null) return valueReturned; foreach (var userSet in UserSettingsCache.ListOfUserSettings) { if ( userSet.FKUserID == userSettings.FKUserID && userSet.FKScreenCode == userSettings.FKScreenCode && userSet.FKControlCode == userSettings.FKControlCode && userSet.FKPropertyCode == userSettings.FKPropertyCode ) { valueReturned = userSet.Value; } } valueReturned = valueReturned.Trim(); return valueReturned; } public static string GetFileExtensionString(string filename) { string fileExtension = ""; int pos = filename.IndexOf( '.' ); // Check position // string charExt4 = filename.Substring( filename.Length - 4, 1 ); if ( charExt4 == "." ) { // It has 4 characters // pos = filename.Length - 4; } string charExt3 = filename.Substring( filename.Length - 3, 1 ); if ( charExt3 == "." ) { // It has 4 characters // pos = filename.Length - 4; } if ( pos > 1 ) fileExtension = filename.Substring( pos + 1, filename.Length - pos - 1 ); else fileExtension = "UNK"; return fileExtension; } } } <file_sep>using System; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Interface; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Security; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; using MySql.Data.MySqlClient; using System.Transactions; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public class BUSClient : IBUSClientList, IBUSClientDetails { /// <summary> /// Add client /// </summary> /// <param name="headerInfo"> </param> /// <param name="eventClient"></param> /// <param name="linkInitialSet"> </param> /// <returns></returns> public ClientAddResponse ClientAdd( ClientAddRequest clientAddRequest ) { var response = new ClientAddResponse(); // This is a new client. // if ( string.IsNullOrEmpty( clientAddRequest.eventClient.Name ) ) { response.responseStatus = new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0001, Message = "Client Name is mandatory." }; return response; } // -------------------------------------------------------------- // Check if user ID is already connected to a client // -------------------------------------------------------------- #region Check if user is already connected to a client if ( !string.IsNullOrEmpty( clientAddRequest.eventClient.FKUserID ) ) { var checkLinkedUser = new Client( clientAddRequest.headerInfo ) { FKUserID = clientAddRequest.eventClient.FKUserID }; //var responseLinked = checkLinkedUser.ReadLinkedUser(); var responseLinked = RepClient.ReadLinkedUser( checkLinkedUser ); if ( !responseLinked.Successful ) { response.responseStatus = new ResponseStatus(); response.responseStatus = responseLinked; return response; } if ( responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0001 ) { response.responseStatus = new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0002, Message = "User ID is already linked to another client." }; return response; } } #endregion var newClientUid = 0; using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { using ( var tr = new TransactionScope( TransactionScopeOption.Required ) ) { connection.Open(); // ------------------------------- // Call method to add new client // ------------------------------- //var newClient = clientAddRequest.eventClient.Insert(clientAddRequest.headerInfo, connection); var newClient = RepClient.Insert( clientAddRequest.headerInfo, clientAddRequest.eventClient, connection ); // var newClientX = eventClient.MySQLInsert(headerInfo); newClientUid = Convert.ToInt32( newClient.Contents ); // ------------------------------------------- // Call method to add client extra information // ------------------------------------------- clientAddRequest.eventClient.clientExtraInformation.FKClientUID = clientAddRequest.eventClient.UID; var cei = RepClientExtraInformation.Insert( HeaderInfo.Instance, clientAddRequest.eventClient.clientExtraInformation, connection ); if ( cei.ReturnCode != 1 ) { // Rollback transaction // tr.Dispose(); response.responseStatus = new ResponseStatus(); response.responseStatus = cei; return response; } // -------------------------------------------- // Add first document set // -------------------------------------------- var cds = new ClientDocumentSet(); cds.FKClientUID = newClientUid; // cds.FolderOnly = "CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0'); cds.FolderOnly = "CLIENT" + newClientUid.ToString().Trim().PadLeft( 4, '0' ); // cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + "\\CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0'); cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + @"\" + cds.FolderOnly; cds.SourceFolder = FCMConstant.SYSFOLDER.TEMPLATEFOLDER; cds.Add( clientAddRequest.headerInfo, connection ); // -------------------------------------------- // Apply initial document set // -------------------------------------------- if ( clientAddRequest.linkInitialSet == "Y" ) { BUSClientDocument.AssociateDocumentsToClient( clientDocumentSet: cds, documentSetUID: clientAddRequest.eventClient.FKDocumentSetUID, headerInfo: clientAddRequest.headerInfo ); // Fix Destination Folder Location // BUSClientDocumentGeneration.UpdateLocation( cds.FKClientUID, cds.ClientSetID ); } // Commit transaction // tr.Complete(); } } ClientList( clientAddRequest.headerInfo ); // List(); // Return new client id response.clientUID = newClientUid; response.responseStatus = new ResponseStatus(); return response; } /// <summary> /// Add Employee /// </summary> /// <param name="clientAddRequest"></param> /// <param name="employeeName"> </param> /// <param name="roleType"></param> private static void AddEmployee( string employeeName, string roleType, string userID, int clientUID ) { if ( string.IsNullOrEmpty( employeeName ) ) return; Employee employee = new Employee(); employee.UserIdCreatedBy = userID; employee.UserIdUpdatedBy = userID; employee.FKCompanyUID = clientUID; employee.Name = employeeName; employee.RoleType = roleType; employee.RoleDescription = MackkadoITFramework.ReferenceData.CodeValue.GetCodeValueDescription( "ROLETYPE", employee.RoleType ); employee.Insert(); } /// <summary> /// Update Employee /// </summary> /// <param name="clientAddRequest"></param> /// <param name="employeeName"> </param> /// <param name="roleType"></param> private static void UpdateEmployee( string employeeName, string roleType, string userID, int clientUID ) { if ( string.IsNullOrEmpty( employeeName ) ) return; Employee employee = new Employee(); employee.UserIdCreatedBy = userID; employee.UserIdUpdatedBy = userID; employee.FKCompanyUID = clientUID; employee.Name = employeeName; employee.RoleType = roleType; employee.RoleDescription = MackkadoITFramework.ReferenceData.CodeValue.GetCodeValueDescription( "ROLETYPE", employee.RoleType ); employee.Update(); } /// <summary> /// Add Employee /// </summary> /// <param name="clientAddRequest"></param> /// <param name="employeeName"> </param> /// <param name="roleType"></param> private static void SaveEmployees( int clientUID, ClientEmployee inClientEmployee, string userID ) { ClientEmployee clientEmployee = new ClientEmployee(); clientEmployee = RepEmployee.ReadEmployees( clientUID ); // ManagingDirector if ( string.IsNullOrEmpty( clientEmployee.ManagingDirector ) ) AddEmployee( inClientEmployee.ManagingDirector, FCMConstant.RoleTypeCode.ManagingDirector, userID, clientUID ); else UpdateEmployee( inClientEmployee.ManagingDirector, FCMConstant.RoleTypeCode.ManagingDirector, userID, clientUID ); // ProjectManager if ( string.IsNullOrEmpty( clientEmployee.ProjectManager ) ) AddEmployee( inClientEmployee.ProjectManager, FCMConstant.RoleTypeCode.ProjectManager, userID, clientUID ); else UpdateEmployee( inClientEmployee.ProjectManager, FCMConstant.RoleTypeCode.ProjectManager, userID, clientUID ); // ProjectOHSRepresentative if ( string.IsNullOrEmpty( clientEmployee.ProjectOHSRepresentative ) ) AddEmployee( inClientEmployee.ProjectOHSRepresentative, FCMConstant.RoleTypeCode.ProjectOHSRepresentative, userID, clientUID ); else UpdateEmployee( inClientEmployee.ProjectOHSRepresentative, FCMConstant.RoleTypeCode.ProjectOHSRepresentative, userID, clientUID ); // OHSEAuditor if ( string.IsNullOrEmpty( clientEmployee.OHSEAuditor ) ) AddEmployee( inClientEmployee.ProjectOHSRepresentative, FCMConstant.RoleTypeCode.OHSEAuditor, userID, clientUID ); else UpdateEmployee( inClientEmployee.ProjectOHSRepresentative, FCMConstant.RoleTypeCode.OHSEAuditor, userID, clientUID ); // SystemsManager if ( string.IsNullOrEmpty( clientEmployee.SystemsManager ) ) AddEmployee( inClientEmployee.SystemsManager, FCMConstant.RoleTypeCode.SystemsManager, userID, clientUID ); else UpdateEmployee( inClientEmployee.SystemsManager, FCMConstant.RoleTypeCode.SystemsManager, userID, clientUID ); // SiteManager if ( string.IsNullOrEmpty( clientEmployee.SiteManager ) ) AddEmployee( inClientEmployee.SiteManager, FCMConstant.RoleTypeCode.SiteManager, userID, clientUID ); else UpdateEmployee( inClientEmployee.SiteManager, FCMConstant.RoleTypeCode.SiteManager, userID, clientUID ); // Supervisor if ( string.IsNullOrEmpty( clientEmployee.Supervisor ) ) AddEmployee( inClientEmployee.Supervisor, FCMConstant.RoleTypeCode.Supervisor, userID, clientUID ); else UpdateEmployee( inClientEmployee.Supervisor, FCMConstant.RoleTypeCode.Supervisor, userID, clientUID ); // LeadingHand1 if ( string.IsNullOrEmpty( clientEmployee.LeadingHand1 ) ) AddEmployee( inClientEmployee.LeadingHand1, FCMConstant.RoleTypeCode.LeadingHand1, userID, clientUID ); else UpdateEmployee( inClientEmployee.LeadingHand1, FCMConstant.RoleTypeCode.LeadingHand1, userID, clientUID ); // LeadingHand2 if ( string.IsNullOrEmpty( clientEmployee.LeadingHand2 ) ) AddEmployee( inClientEmployee.LeadingHand1, FCMConstant.RoleTypeCode.LeadingHand2, userID, clientUID ); else UpdateEmployee( inClientEmployee.LeadingHand1, FCMConstant.RoleTypeCode.LeadingHand2, userID, clientUID ); // LeadingHand2 if ( string.IsNullOrEmpty( clientEmployee.HealthAndSafetyRep ) ) AddEmployee( inClientEmployee.LeadingHand1, FCMConstant.RoleTypeCode.HealthAndSafetyRep, userID, clientUID ); else UpdateEmployee( inClientEmployee.LeadingHand1, FCMConstant.RoleTypeCode.HealthAndSafetyRep, userID, clientUID ); // AdministrationPerson if ( string.IsNullOrEmpty( clientEmployee.HealthAndSafetyRep ) ) AddEmployee( inClientEmployee.AdministrationPerson, FCMConstant.RoleTypeCode.AdministrationPerson, userID, clientUID ); else UpdateEmployee( inClientEmployee.AdministrationPerson, FCMConstant.RoleTypeCode.AdministrationPerson, userID, clientUID ); // WorkersCompensationCoordinator if ( string.IsNullOrEmpty( clientEmployee.HealthAndSafetyRep ) ) AddEmployee( inClientEmployee.WorkersCompensationCoordinator, FCMConstant.RoleTypeCode.WorkersCompensationCoordinator, userID, clientUID ); else UpdateEmployee( inClientEmployee.WorkersCompensationCoordinator, FCMConstant.RoleTypeCode.WorkersCompensationCoordinator, userID, clientUID ); } /// <summary> /// List of clients /// </summary> public ClientListResponse ClientList( HeaderInfo headerInfo ) { var clientListResponse = new ClientListResponse(); clientListResponse.response = new ResponseStatus(); // clientListResponse.clientList = Client.List(headerInfo); try { clientListResponse.clientList = RepClient.List(headerInfo); } catch (Exception ex) { string s = ex.ToString(); } return clientListResponse; } /// <summary> /// Update client details /// </summary> /// <param name="headerInfo"> </param> /// <param name="eventClient"> </param> public ClientUpdateResponse ClientUpdate( ClientUpdateRequest clientUpdateRequest ) { var clientUpdateResponse = new ClientUpdateResponse(); clientUpdateResponse.response = new ResponseStatus(); // -------------------------------------------------------------- // Check if user ID is already connected to a client // -------------------------------------------------------------- //var checkLinkedUser = new Client(clientUpdateRequest.headerInfo) //{ FKUserID = clientUpdateRequest.eventClient.FKUserID }; var checkLinkedUser = new Model.ModelClient.Client( clientUpdateRequest.headerInfo ) { FKUserID = clientUpdateRequest.eventClient.FKUserID, UID = clientUpdateRequest.eventClient.UID }; if ( !string.IsNullOrEmpty( checkLinkedUser.FKUserID ) ) { var responseLinked = RepClient.ReadLinkedUser( checkLinkedUser ); // var responseLinked = checkLinkedUser.ReadLinkedUser(); if ( responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0001 ) { clientUpdateResponse.response = new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0001, Message = "User ID is already linked to another client." }; return clientUpdateResponse; } if ( responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0003 ) { // All good. User ID is connected to Client Supplied. // } } using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { using ( var tr = new TransactionScope( TransactionScopeOption.Required ) ) { connection.Open(); var newClient = RepClient.Update( clientUpdateRequest.headerInfo, clientUpdateRequest.eventClient, connection ); //var responseClientUpdate = clientUpdateRequest.eventClient.Update(); var responseClientUpdate = newClient; if ( !responseClientUpdate.Successful ) { // Rollback tr.Dispose(); clientUpdateResponse.response = new ResponseStatus( MessageType.Error ); clientUpdateResponse.response.Message = responseClientUpdate.Message; clientUpdateResponse.response.ReturnCode = responseClientUpdate.ReturnCode; clientUpdateResponse.response.ReasonCode = responseClientUpdate.ReasonCode; return clientUpdateResponse; } // ------------------------------------------- // Call method to add client extra information // ------------------------------------------- var ceiRead = new RepClientExtraInformation( clientUpdateRequest.headerInfo ); ceiRead.FKClientUID = clientUpdateRequest.eventClient.UID; // var ceiResponse = ceiRead.Read(); var ceiResponse = RepClientExtraInformation.Read( ceiRead ); if ( ceiResponse.ReturnCode != 1 ) { // Rollback tr.Dispose(); clientUpdateResponse.response = new ResponseStatus( MessageType.Error ); return clientUpdateResponse; } // Return Code = 1, Reason Code = 2 means "Record not found" // if ( ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 1 ) { clientUpdateRequest.eventClient.clientExtraInformation.RecordVersion = ceiRead.RecordVersion; var cei = RepClientExtraInformation.Update( clientUpdateRequest.headerInfo, clientUpdateRequest.eventClient. clientExtraInformation, connection ); // var cei = clientUpdateRequest.eventClient.clientExtraInformation.Update(); if ( !cei.Successful ) { clientUpdateResponse.response = new ResponseStatus(); clientUpdateResponse.response = cei; return clientUpdateResponse; } } // Return Code = 1, Reason Code = 2 means "Record not found" // if ( ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 2 ) { // Create new record // ------------------------------------------- // Call method to add client extra information // ------------------------------------------- clientUpdateRequest.eventClient.clientExtraInformation.FKClientUID = clientUpdateRequest.eventClient.UID; var cei = RepClientExtraInformation.Insert( HeaderInfo.Instance, clientUpdateRequest.eventClient.clientExtraInformation, connection ); if ( cei.ReturnCode != 1 ) { // Rollback transaction // tr.Dispose(); clientUpdateResponse.response = new ResponseStatus(); clientUpdateResponse.response = cei; return clientUpdateResponse; } } tr.Complete(); } } return clientUpdateResponse; } /// <summary> /// Client Delete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="eventClient"> </param> public ClientDeleteResponse ClientDelete( ClientDeleteRequest clientDeleteRequest ) { // Using model Model.ModelClient.Client clientToBeDeleted = new Model.ModelClient.Client( clientDeleteRequest.headerInfo ); clientToBeDeleted.UID = clientDeleteRequest.clientUID; // Using Repository ClientDeleteResponse response = new ClientDeleteResponse(); response.responseStatus = RepClient.Delete( clientToBeDeleted ); return response; } /// <summary> /// /// </summary> /// <param name="readFieldRequest"></param> /// <returns></returns> public ReadFieldResponse ReadFieldClient( ReadFieldRequest readFieldRequest ) { var response = RepClient.ReadFieldClient( readFieldRequest ); return response; } /// <summary> /// Client Read /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="eventClient"> </param> public static ClientReadResponse ClientRead( ClientReadRequest clientReadRequest ) { var clientReadResponse = RepClient.Read( clientReadRequest.clientUID ); clientReadResponse.client.clientExtraInformation = new ClientExtraInformation(); clientReadResponse.client.clientExtraInformation.FKClientUID = clientReadResponse.client.UID; // clientReadResponse.client.clientExtraInformation.Read(); RepClientExtraInformation.Read( clientReadResponse.client.clientExtraInformation ); return clientReadResponse; } /// <summary> /// /// </summary> /// <param name="readFieldRequest"></param> /// <returns></returns> public static string GetClientName( int clientUID ) { var response = RepClient.GetClientName( clientUID ); return response; } /// <summary> /// /// </summary> /// <param name="readFieldRequest"></param> /// <returns></returns> public static int GetLinkedClient( string userID ) { var clientUID = RepClient.ReadLinkedClient( userID ); return clientUID; } /// <summary> /// Add client /// </summary> /// <param name="headerInfo"> </param> /// <param name="eventClient"></param> /// <param name="linkInitialSet"> </param> /// <returns></returns> public ClientAddResponse ClientAddFull( ClientAddRequest clientAddRequest ) { var response = new ClientAddResponse(); // This is a new client. // if ( string.IsNullOrEmpty( clientAddRequest.eventClient.Name ) ) { response.responseStatus = new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0001, Message = "Client Name is mandatory." }; return response; } // -------------------------------------------------------------- // Check if user ID is already connected to a client // -------------------------------------------------------------- #region Check if user is already connected to a client if ( !string.IsNullOrEmpty( clientAddRequest.eventClient.FKUserID ) ) { var checkLinkedUser = new Client( clientAddRequest.headerInfo ) { FKUserID = clientAddRequest.eventClient.FKUserID }; //var responseLinked = checkLinkedUser.ReadLinkedUser(); var responseLinked = RepClient.ReadLinkedUser( checkLinkedUser ); if ( !responseLinked.Successful ) { response.responseStatus = new ResponseStatus(); response.responseStatus = responseLinked; return response; } if ( responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0001 ) { response.responseStatus = new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0002, Message = "User ID is already linked to another client." }; return response; } } #endregion var newClientUid = 0; using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { using ( var tr = new TransactionScope( TransactionScopeOption.Required ) ) { connection.Open(); // ------------------------------- // Call method to add new client // ------------------------------- //var newClient = clientAddRequest.eventClient.Insert(clientAddRequest.headerInfo, connection); var newClient = RepClient.Insert( clientAddRequest.headerInfo, clientAddRequest.eventClient, connection ); // var newClientX = eventClient.MySQLInsert(headerInfo); newClientUid = Convert.ToInt32( newClient.Contents ); // ------------------------------------------- // Call method to add client extra information // ------------------------------------------- clientAddRequest.eventClient.clientExtraInformation.FKClientUID = clientAddRequest.eventClient.UID; var cei = RepClientExtraInformation.Insert( HeaderInfo.Instance, clientAddRequest.eventClient.clientExtraInformation, connection ); if ( cei.ReturnCode != 1 ) { // Rollback transaction // tr.Dispose(); response.responseStatus = new ResponseStatus(); response.responseStatus = cei; return response; } // Add user role // SecurityUserRole securityUserRole = new SecurityUserRole(); securityUserRole.FK_Role = FCMConstant.UserRoleType.CLIENT; securityUserRole.FK_UserID = clientAddRequest.headerInfo.UserID; securityUserRole.IsActive = "Y"; securityUserRole.IsVoid = "N"; securityUserRole.StartDate = System.DateTime.Today; securityUserRole.EndDate = Convert.ToDateTime("9999-12-31"); securityUserRole.Add(); // -------------------------------------------- // Add List of Employees // -------------------------------------------- SaveEmployees( clientAddRequest.eventClient.UID, clientAddRequest.eventClient.clientEmployee, clientAddRequest.headerInfo.UserID ); // 14/04/2013 // Not adding sets when client is created because the client is created just after the user ID is registered! // // 17/04/2013 // If the ADMINistrator creates the client the document set has to be created and documents added. // if ( clientAddRequest.linkInitialSet == "Y" ) { // -------------------------------------------- // Add first document set // -------------------------------------------- var cds = new ClientDocumentSet(); cds.FKClientUID = newClientUid; // cds.FolderOnly = "CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0'); cds.FolderOnly = "CLIENT" + newClientUid.ToString().Trim().PadLeft(4, '0'); // cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + "\\CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0'); cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + @"\" + cds.FolderOnly; cds.SourceFolder = FCMConstant.SYSFOLDER.TEMPLATEFOLDER; cds.Add(clientAddRequest.headerInfo, connection); // -------------------------------------------- // Apply initial document set // -------------------------------------------- BUSClientDocument.AssociateDocumentsToClient( clientDocumentSet: cds, documentSetUID: clientAddRequest.eventClient.FKDocumentSetUID, headerInfo: clientAddRequest.headerInfo ); // Fix Destination Folder Location // BUSClientDocumentGeneration.UpdateLocation( cds.FKClientUID, cds.ClientSetID ); } // Commit transaction tr.Complete(); } } ClientList( clientAddRequest.headerInfo ); // List(); // Return new client id response.clientUID = newClientUid; response.responseStatus = new ResponseStatus(); return response; } /// <summary> /// Client Read /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="eventClient"> </param> public static ClientReadResponse ClientReadFull( ClientReadRequest clientReadRequest ) { // Check if the user can access the client record // bool isadmin = false; string userid = clientReadRequest.headerInfo.UserID; var sur = new SecurityUserRole(); var clientReadResponse = RepClient.Read( clientReadRequest.clientUID ); if ( sur.UserHasAccessToRole( userid, FCMConstant.UserRoleType.ADMIN ) ) { // ok } else { if ( sur.UserHasAccessToRole( userid, FCMConstant.UserRoleType.CLIENT ) ) { if ( clientReadResponse.client.FKUserID.ToUpper() == clientReadRequest.headerInfo.UserID.ToUpper() ) { //ok } else return new ClientReadResponse(); } else return new ClientReadResponse(); } clientReadResponse.client.clientExtraInformation = new ClientExtraInformation(); clientReadResponse.client.clientExtraInformation.FKClientUID = clientReadResponse.client.UID; RepClientExtraInformation.Read( clientReadResponse.client.clientExtraInformation ); clientReadResponse.client.clientEmployee = RepEmployee.ReadEmployees( clientReadRequest.clientUID ); return clientReadResponse; } /// <summary> /// Update client details /// </summary> /// <param name="headerInfo"> </param> /// <param name="eventClient"> </param> public ClientUpdateResponse ClientUpdateFull( ClientUpdateRequest clientUpdateRequest ) { var clientUpdateResponse = new ClientUpdateResponse(); bool contractorSizeFirstTime = false; // Check if contractor size has been set before // var clientRead = RepClient.Read(clientUpdateRequest.eventClient.UID); if ( clientRead.client.FKDocumentSetUID == 0) contractorSizeFirstTime = true; clientUpdateResponse.response = new ResponseStatus(); // -------------------------------------------------------------- // Check if user ID is already connected to a client // -------------------------------------------------------------- //var checkLinkedUser = new Client(clientUpdateRequest.headerInfo) //{ FKUserID = clientUpdateRequest.eventClient.FKUserID }; var checkLinkedUser = new Model.ModelClient.Client( clientUpdateRequest.headerInfo ) { FKUserID = clientUpdateRequest.eventClient.FKUserID, UID = clientUpdateRequest.eventClient.UID }; if ( !string.IsNullOrEmpty( checkLinkedUser.FKUserID ) ) { var responseLinked = RepClient.ReadLinkedUser( checkLinkedUser ); // var responseLinked = checkLinkedUser.ReadLinkedUser(); if ( responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0001 ) { clientUpdateResponse.response = new ResponseStatus() { ReturnCode = -0010, ReasonCode = 0001, Message = "User ID is already linked to another client." }; return clientUpdateResponse; } if ( responseLinked.ReturnCode == 0001 && responseLinked.ReasonCode == 0003 ) { // All good. User ID is connected to Client Supplied. // } } using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { using ( var tr = new TransactionScope( TransactionScopeOption.Required ) ) { connection.Open(); var newClient = RepClient.Update( clientUpdateRequest.headerInfo, clientUpdateRequest.eventClient, connection ); //var responseClientUpdate = clientUpdateRequest.eventClient.Update(); var responseClientUpdate = newClient; if ( !responseClientUpdate.Successful ) { // Rollback tr.Dispose(); clientUpdateResponse.response = new ResponseStatus( MessageType.Error ); clientUpdateResponse.response.Message = responseClientUpdate.Message; clientUpdateResponse.response.ReturnCode = responseClientUpdate.ReturnCode; clientUpdateResponse.response.ReasonCode = responseClientUpdate.ReasonCode; return clientUpdateResponse; } // ------------------------------------------- // Call method to add client extra information // ------------------------------------------- var ceiRead = new RepClientExtraInformation( clientUpdateRequest.headerInfo ); ceiRead.FKClientUID = clientUpdateRequest.eventClient.UID; // var ceiResponse = ceiRead.Read(); var ceiResponse = RepClientExtraInformation.Read( ceiRead ); if ( ceiResponse.ReturnCode != 1 ) { // Rollback tr.Dispose(); clientUpdateResponse.response = new ResponseStatus( MessageType.Error ); return clientUpdateResponse; } // Return Code = 1, Reason Code = 2 means "Record not found" // if ( ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 1 ) { clientUpdateRequest.eventClient.clientExtraInformation.RecordVersion = ceiRead.RecordVersion; var cei = RepClientExtraInformation.Update( clientUpdateRequest.headerInfo, clientUpdateRequest.eventClient. clientExtraInformation, connection ); // var cei = clientUpdateRequest.eventClient.clientExtraInformation.Update(); if ( !cei.Successful ) { clientUpdateResponse.response = new ResponseStatus(); clientUpdateResponse.response = cei; return clientUpdateResponse; } } // Return Code = 1, Reason Code = 2 means "Record not found" // if ( ceiResponse.ReturnCode == 1 && ceiResponse.ReasonCode == 2 ) { // Create new record // ------------------------------------------- // Call method to add client extra information // ------------------------------------------- clientUpdateRequest.eventClient.clientExtraInformation.FKClientUID = clientUpdateRequest.eventClient.UID; var cei = RepClientExtraInformation.Insert( HeaderInfo.Instance, clientUpdateRequest.eventClient.clientExtraInformation, connection ); if ( cei.ReturnCode != 1 ) { // Rollback transaction // tr.Dispose(); clientUpdateResponse.response = new ResponseStatus(); clientUpdateResponse.response = cei; return clientUpdateResponse; } } //tr.Complete(); // If this is the first time the users sets the contractor size, add documents. // if ( contractorSizeFirstTime ) { // -------------------------------------------- // Add first document set // -------------------------------------------- var cds = new ClientDocumentSet(); cds.FKClientUID = clientUpdateRequest.eventClient.UID; // cds.FolderOnly = "CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0'); cds.FolderOnly = "CLIENT" + clientUpdateRequest.eventClient.UID.ToString().Trim().PadLeft( 4, '0' ); // cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + "\\CLIENT" + newClientUID.ToString().Trim().PadLeft(4, '0'); cds.Folder = FCMConstant.SYSFOLDER.CLIENTFOLDER + @"\" + cds.FolderOnly; cds.SourceFolder = FCMConstant.SYSFOLDER.TEMPLATEFOLDER; // cds.Add( clientUpdateRequest.headerInfo, connection ); cds.Add( clientUpdateRequest.headerInfo ); // -------------------------------------------- // Apply initial document set // -------------------------------------------- BUSClientDocument.AssociateDocumentsToClient( clientDocumentSet: cds, documentSetUID: clientUpdateRequest.eventClient.FKDocumentSetUID, headerInfo: clientUpdateRequest.headerInfo ); // Fix Destination Folder Location // BUSClientDocumentGeneration.UpdateLocation( cds.FKClientUID, cds.ClientSetID ); } SaveEmployees( clientUpdateRequest.eventClient.UID, clientUpdateRequest.eventClient.clientEmployee, clientUpdateRequest.headerInfo.UserID ); } } return clientUpdateResponse; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.ProcessRequest { public class ProcessRequestResults { public int FKRequestUID { get; set; } public int FKClientUID { get; set; } public int SequenceNumber { get; set; } public string Type { get; set; } public string Results { get; set; } public string LongText { get; set; } /// <summary> /// Database fields /// </summary> public struct FieldName { public const string FKRequestUID = "FKRequestUID"; public const string FKClientUID = "FKClientUID"; public const string SequenceNumber = "SequenceNumber"; public const string Type = "Type"; public const string Results = "Results"; } #region Permitted Values public enum TypeValue { INFORMATIONAL, ERROR } #endregion Permitted Values // ----------------------------------------------------- // Retrieve last ProcessRequest UID // ----------------------------------------------------- public int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = "SELECT MAX(SEQUENCENUMBER) LASTUID FROM ProcessRequestResults WHERE FKRequestUID = " + this.FKRequestUID.ToString(); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Add new Process Request Results row // ----------------------------------------------------- public ResponseStatus Add() { ResponseStatus responseSuccessful = new ResponseStatus(); ResponseStatus responseError = new ResponseStatus(messageType: MessageType.Error); string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; this.SequenceNumber = _uid; DateTime _now = DateTime.Today; if (SequenceNumber == 0) { responseError.Message = "Sequence Number Not Supplied."; responseError.Contents = this; return responseError; } if (string.IsNullOrEmpty(Results)) Results = "Empty"; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO ProcessRequestResults " + "( " + FieldString() + ")" + " VALUES " + "( " + " @" + FieldName.FKRequestUID + ", @" + FieldName.FKClientUID + ", @" + FieldName.SequenceNumber + ", @" + FieldName.Type + ", @" + FieldName.Results + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKRequestUID", MySqlDbType.Int32).Value = FKRequestUID; command.Parameters.Add("@FKClientUID", MySqlDbType.Int32).Value = FKClientUID; command.Parameters.Add("@SequenceNumber", MySqlDbType.Int32).Value = SequenceNumber; command.Parameters.Add("@Type", MySqlDbType.VarChar).Value = Type; command.Parameters.Add("@Results", MySqlDbType.VarChar).Value = Results; connection.Open(); command.ExecuteNonQuery(); } } return responseSuccessful; } /// <summary> /// List Request Results /// </summary> /// <param name="FKRequestUID"></param> /// <returns></returns> public static List<ProcessRequestResults> List(int FKRequestUID) { var result = new List<ProcessRequestResults>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + FieldString() + " FROM ProcessRequestResults " + " WHERE " + " FKRequestUID = " + FKRequestUID.ToString() + " ORDER BY 1 ASC " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _ProcessRequest = new ProcessRequestResults(); ProcessRequestResults.LoadFromReader(_ProcessRequest, reader); result.Add(_ProcessRequest); } } } } return result; } /// <summary> /// Load from Reader /// </summary> /// <param name="processRequest"></param> /// <param name="tablePrefix"></param> /// <param name="reader"></param> public static void LoadFromReader( ProcessRequestResults processRequest, MySqlDataReader reader) { processRequest.FKRequestUID = Convert.ToInt32(reader[FieldName.FKRequestUID].ToString()); processRequest.FKClientUID = Convert.ToInt32(reader[FieldName.FKClientUID].ToString()); processRequest.SequenceNumber = Convert.ToInt32(reader[FieldName.SequenceNumber].ToString()); processRequest.Type = reader[FieldName.Type].ToString(); processRequest.Results = reader[FieldName.Results].ToString(); return; } /// <summary> /// Document string of fields. /// </summary> /// <returns></returns> private static string FieldString() { return ( FieldName.FKRequestUID + "," + FieldName.FKClientUID + "," + FieldName.SequenceNumber + "," + FieldName.Type + "," + FieldName.Results ); } } } <file_sep>using System.Windows.Forms; using FCMMySQLBusinessLibrary; using MackkadoITFramework.Utils; namespace MackkadoITFramework.ErrorHandling { public class ResponseStatus { public int ReturnCode { set { returnCode = value; if (returnCode <= 0) { Successful = false; XMessageType = MessageType.Error; Icon = MessageBoxIcon.Error; UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000001; } else { Successful = true; XMessageType = MessageType.Informational; Icon = MessageBoxIcon.Information; UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; if (ReasonCode > 1) { Successful = true; XMessageType = MessageType.Warning; Icon = MessageBoxIcon.Warning; UniqueCode = ResponseStatus.MessageCode.Warning.FCMWAR00000001; } } } get { return returnCode; } } public int ReasonCode { set { reasonCode = value; if (returnCode <= 0) { Successful = false; XMessageType = MessageType.Error; Icon = MessageBoxIcon.Error; } else { Successful = true; XMessageType = MessageType.Informational; Icon = MessageBoxIcon.Information; if (ReasonCode > 1) { XMessageType = MessageType.Warning; Icon = MessageBoxIcon.Warning; } } } get { return reasonCode; } } public string UniqueCode { get { return uniqueCode; } set { uniqueCode = value; } } public string Message { get; set; } public MessageType XMessageType { get; set; } public object Contents { get; set; } public MessageBoxIcon Icon { get; set; } public bool Successful { get; set; } private int returnCode; private int reasonCode; private string uniqueCode; public ResponseStatus() { ReturnCode = 0001; ReasonCode = 0001; Message = "Successful"; Successful = true; XMessageType = MessageType.Informational; UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; Icon = MessageBoxIcon.Information; } public ResponseStatus(MessageType messageType) { if (messageType == MessageType.Error) { ReturnCode = -10; ReasonCode = 1; Successful = false; Message = "Error"; XMessageType = MessageType.Error; UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00009999; Icon = MessageBoxIcon.Error; } if (messageType == MessageType.Informational) { ReturnCode = 1; ReasonCode = 1; Message = "Successful"; Successful = true; XMessageType = MessageType.Informational; UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; Icon = MessageBoxIcon.Information; } if (messageType == MessageType.Warning) { ReturnCode = 1; ReasonCode = 2; Message = "Warning."; Successful = true; XMessageType = MessageType.Warning; UniqueCode = ResponseStatus.MessageCode.Warning.FCMWAR00000001; Icon = MessageBoxIcon.Warning; } } public void WriteToLog(HeaderInfo headerInfo) { LogFile.WriteToTodaysLogFile(this.UniqueCode + this.Message, headerInfo.UserID); } /// <summary> /// List of error codes /// </summary> public struct MessageCode { public struct Informational { // ---------------------- // // INFORMATIONAL MESSAGES // // ---------------------- // /// <summary> /// Generic Successful. /// </summary> public const string FCMINF00000001 = "FCMINF00.00.0001"; /// <summary> /// User role added successfully. /// </summary> public const string FCMINF00000002 = "FCMINF00.00.0002"; /// <summary> /// User role deleted successfully. /// </summary> public const string FCMINF00000003 = "FCMINF00.00.0003"; /// <summary> /// User added successfully. /// </summary> public const string FCMINF00000004 = "FCMINF00.00.0004"; /// <summary> /// User updated successfully. /// </summary> public const string FCMINF00000005 = "FCMINF00.00.0005"; /// <summary> /// User added successfully. /// </summary> public const string FCMINF00000006 = "FCMINF00.00.0006"; /// <summary> /// Client deleted successfully. /// </summary> public const string FCMINF00000007 = "FCMINF00.00.0007"; } public struct Error { // ---------------------- // // ERROR MESSAGES // // ---------------------- // /// <summary> /// Invalid logon. /// </summary> public const string FCMERR00000001 = "FCMERR00.00.0001"; /// <summary> /// Error deleting User Role. /// </summary> public const string FCMERR00000002 = "FCMERR00.00.0002"; /// <summary> /// User ID is mandatory. /// </summary> public const string FCMERR00000003 = "FCMINF00.00.0003"; /// <summary> /// Password is mandatory. /// </summary> public const string FCMERR00000004 = "<PASSWORD>"; /// <summary> /// Salt is mandatory. /// </summary> public const string FCMERR00000005 = "FCMINF00.00.0005"; /// <summary> /// Error creating new version. Source file not found. /// </summary> public const string FCMERR00000006 = "FCMINF00.00.0006"; /// <summary> /// Client name is mandatory. /// </summary> public const string FCMERR00000007 = "FCMINF00.00.0007"; /// <summary> /// Role Name is mandatory. /// </summary> public const string FCMERR00000008 = "FCMINF00.00.0008"; /// <summary> /// Client logo or icon not found. /// </summary> public const string FCMERR00000009 = "FCMINF00.00.0009"; /// <summary> /// Error. /// </summary> public const string FCMERR00009999 = "FCMINF00.00.9999"; } public struct Warning { // ---------------------- // // WARNING MESSAGES // // ---------------------- // /// <summary> /// Generic Warning. /// </summary> public const string FCMWAR00000001 = "FCMWAR00.00.0001"; /// <summary> /// No valid contract was found for client. /// </summary> public const string FCMWAR00000002 = "FCMWAR00.00.0002"; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace fcm { public class ControllerEmployee { public Employee model { get; set; } public IEmployee view { get; set; } /// <summary> /// Constructor of the presenter /// </summary> public ControllerEmployee(IEmployee iEmployeeView) { view = iEmployeeView; model = new Employee(); iEmployeeView.EmployeeList += ViewEmployeeList; iEmployeeView.EmployeeAdd += ViewEmployeeAdd; iEmployeeView.EmployeeUpdate += ViewEmployeeUpdate; iEmployeeView.EmployeeDelete += ViewEmployeeDelete; } public void ViewEmployeeList(object sender, EventArgs e) { var model = new Employee(); view.employeeList = Employee.List(view.employee.FKCompanyUID); return; } public void ViewEmployeeAdd(object sender, EventArgs e) { var model = new Employee(); LoadEmployeeFromController(model); view.response = model.Insert(); view.DisplayMessage(view.response.Message); view.ResetScreen(); return; } public void ViewEmployeeUpdate(object sender, EventArgs e) { var model = new Employee(); LoadEmployeeFromController(model); view.response = model.Update(); view.DisplayMessage(view.response.Message); return; } public void ViewEmployeeDelete(object sender, EventArgs e) { var model = new Employee(); view.response = model.Delete(); view.DisplayMessage(view.response.Message); return; } /// <summary> /// Populate employee object from controller object /// </summary> /// <param name="model"></param> private void LoadEmployeeFromController(Employee model) { model.UID = view.employee.UID; model.FKCompanyUID = view.employee.FKCompanyUID; model.Name = view.employee.Name; model.RoleType = view.employee.RoleType; model.Address = view.employee.Address; model.EmailAddress = view.employee.EmailAddress; model.Phone = view.employee.Phone; model.Fax = view.employee.Fax; model.IsAContact = view.employee.IsAContact; model.UserIdCreatedBy = Utils.UserID; model.UserIdUpdatedBy = Utils.UserID; model.UpdateDateTime = view.employee.UpdateDateTime; model.CreationDateTime = view.employee.CreationDateTime; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCDocument.Service { public class BUSDocumentSet { /// <summary> /// List of documents /// </summary> public static List<DocumentSet> DocumentSetList() { return DocumentSet.ListS(); } /// <summary> /// List of documents /// </summary> public static DocumentSet DocumentSetRead(int documentSetUID) { DocumentSet documentSet = new DocumentSet(); documentSet.UID = documentSetUID; documentSet.Read('Y'); return documentSet; } /// <summary> /// List of documents /// </summary> public static DocumentSet ListDocumentSets() { var documentSet = new DocumentSet(); documentSet.documentSetList = DocumentSet.ListS(); return documentSet; } /// <summary> /// List of documents /// </summary> public static List<Document> ListDocumentsNotInSet( HeaderInfo headerInfo, int documentSetUID ) { DocumentSet documentSet = new DocumentSet(); documentSet.UID = documentSetUID; var documentsNotInSet = documentSet.ListDocumentsNotInSet(headerInfo, documentSetUID); return documentsNotInSet; } public static ResponseStatus AddDocumentToSet( HeaderInfo headerInfo, int documentSetUID, int documentUID) { // Find Document // DocumentReadRequest documentReadRequest = new DocumentReadRequest(); documentReadRequest.headerInfo = headerInfo; documentReadRequest.retrieveVoidedDocuments = false; documentReadRequest.UID = documentUID; var documentReadResponse = BUSDocument.DocumentRead(documentReadRequest); var documentSelected = new Document(); documentSelected = documentReadResponse.document; // Find parent of the document // var folderReadRequestParent = new DocumentReadRequest(); folderReadRequestParent.headerInfo = headerInfo; folderReadRequestParent.retrieveVoidedDocuments = false; folderReadRequestParent.UID = documentSelected.ParentUID; // Reading parent var folderParentResponse = BUSDocument.DocumentRead( folderReadRequestParent ); var folderParent = new Document(); folderParent = folderParentResponse.document; // Find DocumentSet // var documentSet = new DocumentSet(); documentSet.UID = documentSetUID; documentSet.Read('N'); // Create link // DocumentSetDocument dsd = new DocumentSetDocument(); dsd.FKDocumentSetUID = documentSet.UID; dsd.FKDocumentUID = documentSelected.UID; dsd.EndDate = System.DateTime.MaxValue; dsd.StartDate = System.DateTime.Today; dsd.UID = 0; dsd.Location = documentSelected.Location; dsd.SequenceNumber = 1; dsd.IsVoid = 'N'; dsd.FKParentDocumentSetUID = documentSet.UID; dsd.FKParentDocumentUID = folderReadRequestParent.UID; // Is this the ID of the parent on the document table or the id of the document on this table? dsd.Add(); return new ResponseStatus(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; namespace fcm.Windows { public partial class UIProjectPlan : Form { public UIProjectPlan() { InitializeComponent(); } private void UIProjectPlan_Load(object sender, EventArgs e) { } // ------------------------------------------ // List Documents // ------------------------------------------ public void loadDocumentList() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvProjectPlanDoco.ImageList = imageList; // Clear nodes tvProjectPlanDoco.Nodes.Clear(); var docoList = new DocumentList(); docoList.List(); // Load document in the treeview // //docoList.ListInTree(tvProjectPlanDoco); Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); // Using Business Layer root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvProjectPlanDoco, docoList, root); tvProjectPlanDoco.ExpandAll(); } private void tvProjectPlanDoco_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvProjectPlanDoco.SelectedNode = tvProjectPlanDoco.GetNodeAt( e.X, e.Y ); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using ConnString = MackkadoITFramework.Utils.ConnString; namespace FCMMySQLBusinessLibrary.Model.ModelClient { public class ClientContract { public int FKCompanyUID { get; set; } public int UID { get; set; } public string ExternalID { get; set; } public string Status { get; set; } public string Type { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string UserIdCreatedBy { get; set; } public string UserIdUpdatedBy { get; set; } public DateTime CreationDateTime { get; set; } public DateTime UpdateDateTime { get; set; } } } <file_sep>using System; using System.Collections.Generic; // using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Reflection; // using System.Security.Principal; using System.Windows.Forms; using FCMBusinessLibrary; namespace FCMApplicationLoader { public class AssemblyLoader { private Assembly _assembly; private string ServerPath { get; set; } private string LocalPath { get; set; } private string ServerPathMainAssembly { get; set; } private string LocalPathMainAssembly { get; set; } public bool AssemblyIsLoaded { get; set; } public bool AssemblyCanBeLoaded { get; set; } public AssemblyLoader() { AssemblyIsLoaded = false; string localAssembly = FCMXmlConfig.Read(fcmConfigXml.LocalAssemblyFolder); string serverAssembly = FCMXmlConfig.Read(fcmConfigXml.ServerAssemblyFolder); if (string.IsNullOrEmpty(localAssembly)) { MessageBox.Show("FCMConfig.xml is not setup correctly - missing Local Assembly Folder."); return; } if (string.IsNullOrEmpty(serverAssembly)) { MessageBox.Show("FCMConfig.xml is not setup correctly - missing Server Assembly Folder."); return; } // Get local assemblies folder location // LocalPath = @"C:\Program Files\fcm\"; LocalPath = @localAssembly; // LocalPathMainAssembly = @"C:\Program Files\fcm\fcm.exe"; LocalPathMainAssembly = @LocalPath+"fcm.exe"; // Get server assemblies folder location // ServerPath = @"C:\Users\MACHADO\Dropbox\FCM\fcm\bin\Debug\"; ServerPath = @serverAssembly; // ServerPathMainAssembly = @"C:\Users\MACHADO\Dropbox\FCM\fcm\bin\Debug\fcm.exe"; ServerPathMainAssembly = @ServerPath + "fcm.exe"; AssemblyName localAssemblyName = new AssemblyName(); AssemblyName serverAssemblyName = new AssemblyName(); string versionLocal = ""; string versionServer = ""; // Get the local version of the assembly if (File.Exists(LocalPathMainAssembly)) { localAssemblyName = AssemblyName.GetAssemblyName(LocalPathMainAssembly); versionLocal = localAssemblyName.Version.ToString(); } // Get the server version of the assembly if (!File.Exists(ServerPathMainAssembly)) { MessageBox.Show("Error. Server version not found. Path= " + ServerPathMainAssembly); return; } serverAssemblyName = AssemblyName.GetAssemblyName(ServerPathMainAssembly); versionServer = serverAssemblyName.Version.ToString(); if (versionLocal == versionServer) { // All good AssemblyCanBeLoaded = true; return; } MessageBox.Show("Version will be upgraded. " + versionServer); // At this point the files are not the same, need to replace the local files. // // Check if files are there var filesInServer = Directory.GetFiles(ServerPath); foreach (var serverfile in filesInServer) { string sfile = serverfile.Replace("\\", ","); var partsOfFile = sfile.Split(','); var filename = partsOfFile[partsOfFile.Length-1]; string localFilePathName = LocalPath + filename; string serverFilePathName = ServerPath + filename; if (File.Exists(localFilePathName)) { // Copy Server files // try { File.Delete(localFilePathName); } catch (Exception ex) { MessageBox.Show("Error deleting file " + localFilePathName + " " + ex.ToString()); } } try { File.Copy(serverFilePathName, localFilePathName); } catch (Exception ex) { MessageBox.Show("Error copying file " + serverFilePathName + " " + ex.ToString()); } } AssemblyCanBeLoaded = true; } public void LoadFCMClient() { try { _assembly = Assembly.LoadFrom(LocalPathMainAssembly); string typeAssembly = "fcm.Windows.UIfcm"; Type type = _assembly.GetType(typeAssembly); var _addIn = (Form)Activator.CreateInstance(type); _addIn.Tag = LocalPathMainAssembly; _addIn.ShowDialog(); var version = _addIn.ProductVersion; AssemblyIsLoaded = true; } catch (Exception ex) { MessageBox.Show(ex.ToString()); AssemblyIsLoaded = false; throw; } } } public class fcmConfigXml { public static string ConnectionString = "ConnectionString"; public static string ConnectionStringServer = "ConnectionStringServer"; public static string ConnectionStringLocal = "ConnectionStringLocal"; public static string LocalAssemblyFolder = "LocalAssemblyFolder"; public static string ServerAssemblyFolder = "ServerAssemblyFolder"; } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using MackkadoITFramework.APIDocument; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.Interfaces; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary; namespace fcm.Windows { public partial class UIClientDocumentSet : Form, IOutputMessage { private DocumentSet documentSet; private System.Windows.Forms.NotifyIcon notifyIcon1; private string taskBarMessage; private string overrideDocuments; private TreeNode tndocSelected; private List<ClientDocumentSet> ListOfDocumentSets; ImageList imageList; ImageList imageList32; public string ScreenCode; float tvClientDocumentListFontSize; int tvClientDocumentListIconSize; float tvClientDocumentListADFontSize; int tvClientDocumentListADIconSize; static BackgroundWorker _backgroundWorker = new BackgroundWorker(); //private int documentSetUID; public UIClientDocumentSet() { InitializeComponent(); ScreenCode = FCMConstant.ScreenCode.ClientDocumentSet; CreateClientMetadataTable(); documentSet = new DocumentSet(); //_backgroundWorker.DoWork += GenerateDocument; //this.components = new System.ComponentModel.Container(); //// Set up how the form should be displayed. //this.ClientSize = new System.Drawing.Size( 292, 266 ); //this.Text = "FCM Report Generator"; //this.notifyIcon1 = new System.Windows.Forms.NotifyIcon( this.components ); //notifyIcon1.Icon = new Icon( "FCMIcon.ico" ); //notifyIcon1.Text = "Form1 (NotifyIcon example)"; //notifyIcon1.Visible = true; //// notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick); //// notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click); //notifyIcon1.MouseMove += new MouseEventHandler( notifyIcon1_MouseMove ); //notifyIcon1.ContextMenuStrip = contextMenuStrip2; this.Icon = new Icon( "FCMIcon.ico" ); ListOfDocumentSets = new List<ClientDocumentSet>(); tvFileList.Refresh(); } // ------------------------------------------ // Load event // ------------------------------------------ private void UIClientDocumentSet_Load(object sender, EventArgs e) { if (! Cache.CachedInfo.IsUserAllowedToScreen(Utils.UserID, FCMConstant.ScreenCode.ClientDocumentSet)) { MessageBox.Show("User does not have access to this screen."); this.Dispose(); return; } // Disable buttons tsbtnDelete.Enabled = false; tsbtnDown.Enabled = false; tsbtnUp.Enabled = false; tsbtnDelete.Enabled = false; tsbtnCopyAll.Enabled = false; // Image list // // 32 x 32 imageList32 = ControllerUtils.GetImageList(); imageList32.ImageSize = new Size(32, 32); // 16 x 16 imageList = ControllerUtils.GetImageList(); tvFileList.ImageList = imageList; // Clear nodes tvFileList.Nodes.Clear(); // // Get client list from background and load into the list // foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // // Get selected client from the background // cbxClient.SelectedIndex = Utils.ClientIndex; // List all documents // // ImageList imageList2 = Utils.GetImageList(); tvDocumentsAvailable.ImageList = imageList; // Clear nodes tvDocumentsAvailable.Nodes.Clear(); var docoList = new DocumentList(); docoList.List(); // Load document in the treeview // //docoList.ListInTree(tvDocumentsAvailable); Document root = new Document(); // root.GetRoot(HeaderInfo.Instance); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvDocumentsAvailable, docoList, root); if (tvDocumentsAvailable.Nodes.Count >= 0) { tvDocumentsAvailable.Nodes[0].Expand(); } // Load document set list // DocumentSetList dsl = new DocumentSetList(); dsl.ListInComboBox(cbxDocSet); if (cbxDocSet.Items.Count <= 0) return; cbxDocSet.SelectedIndex = 0; cbxDocSet.Items.Add("99; Client Specific"); // Retrieve values from cache // GetValuesFromCache(); // Load client document list // indexChanged(); } public UIClientDocumentSet(string ClientID): this() { InitializeComponent(); cbxClient.Enabled = false; } // ------------------------------------------ // Client Metadata datatable // ------------------------------------------ public void CreateClientMetadataTable() { // // Create datatable // var Enabled = new DataColumn("Enabled", typeof(String)); var FieldCode = new DataColumn("FieldCode", typeof(String)); var RecordType = new DataColumn("RecordType", typeof(String)); var InformationType = new DataColumn("InformationType", typeof(String)); var Condition = new DataColumn("Condition", typeof(String)); var Description = new DataColumn("Description", typeof(String)); var ClientType = new DataColumn("ClientType", typeof(String)); var ClientUID = new DataColumn("ClientUID", typeof(String)); var UID = new DataColumn("UID", typeof(String)); var CompareWith = new DataColumn("CompareWith", typeof(String)); //// Client Metadata //// //clientMetadataTable = new DataTable("clientMetadataTable"); //clientMetadataTable.Columns.Add(Enabled); //clientMetadataTable.Columns.Add(FieldCode); //clientMetadataTable.Columns.Add(InformationType); //clientMetadataTable.Columns.Add(Condition); //clientMetadataTable.Columns.Add(Description); //clientMetadataTable.Columns.Add(RecordType); //clientMetadataTable.Columns.Add(ClientType); //clientMetadataTable.Columns.Add(ClientUID); //clientMetadataTable.Columns.Add(UID); //clientMetadataTable.Columns.Add(CompareWith); //dgvClientMetadata.DataSource = clientMetadataTable; } // ------------------------------------------- // Load project plan // ------------------------------------------- private void LoadProjectPlan() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); tvProjectPlan.ImageList = imageList; // Clear nodes tvProjectPlan.Nodes.Clear(); var cdl = new ClientDocument(); // cdl.ListProjectPlanInTree(Utils.ClientID, Utils.ClientSetID, tvProjectPlan); BUSClientDocument.ListProjectPlanInTree( cdl, Utils.ClientID, Utils.ClientSetID, tvProjectPlan ); } /// <summary> /// When client is changed or the client document set is changed /// </summary> private void indexChanged() { txtSourceFolder.Text = ""; txtDestinationFolder.Text = ""; txtFolderOnly.Text = ""; txtDocumentSetDesc.Text = ""; cbxDocumentSet.Text = ""; // Get selected client // string[] part = cbxClient.SelectedItem.ToString().Split(';'); Utils.ClientID = Convert.ToInt32(part[0]); // Retrieve list of document sets for the selected client // var documentSetList = ClientDocumentSet.List(Utils.ClientID, sortOrder: "DESC"); cbxDocumentSet.Items.Clear(); ListOfDocumentSets.Clear(); int currentDocSetID = 1; if (documentSetList.Count > 1) { var lastDocSet = (ClientDocumentSet)documentSetList[0]; currentDocSetID = lastDocSet.ClientSetID; } foreach (ClientDocumentSet cds in documentSetList) { // cbxDocumentSet.Items.Add(cds.FKClientUID + ";" + cds.ClientSetID + "; " + cds.Description + "; " + cds.Status); cbxDocumentSet.Items.Add(cds.CombinedIDName); ListOfDocumentSets.Add(cds); } if (cbxDocumentSet.Items.Count >= 1) { // Set full text for the client document set including id and description // Utils.ClientSetText = cbxDocumentSet.Items[0].ToString(); // // Force first item to be selected // cbxDocumentSet.SelectedIndex = 0; cbxDocumentSet.SelectedItem = 0; // Get Client UID // string[] p = cbxDocumentSet.SelectedItem.ToString().Split(';'); Utils.ClientSetID = Convert.ToInt32(p[0]); // Retrieve document set for a client // ClientDocumentSet clientDocSet = new ClientDocumentSet(); // Utils.ClientSetID = 1; Utils.ClientSetID = currentDocSetID; clientDocSet.Get(Utils.ClientID, Utils.ClientSetID); cbxDocumentSet.SelectedIndex = 0; txtSourceFolder.Text = clientDocSet.SourceFolder; txtDestinationFolder.Text = clientDocSet.Folder; txtFolderOnly.Text = clientDocSet.FolderOnly; txtDocumentSetDesc.Text = clientDocSet.Description; labelStatus.Text = ListOfDocumentSets[cbxDocumentSet.SelectedIndex].Status; EnableDisableFields(); } // // Load documents for a Client Document Set // loadDocumentList(); loadClientMetadataList(); LoadProjectPlan(); RemoveDocumentsAlreadySelected(tvDocumentsAvailable); } /// <summary> /// Load documents for a Client Document Set /// </summary> [Obsolete("No longer used", true)] private void loadDocumentList2() { // List client document list // var documentSetList = new ClientDocument(); //documentSetList.List(Utils.ClientID, Utils.ClientSetID); var cdlr = new BUSClientDocument.ClientDocumentListRequest(); cdlr.clientUID = Utils.ClientID; cdlr.clientDocumentSetUID = Utils.ClientSetID; var response = BUSClientDocument.List(cdlr); documentSetList.clientDocSetDocLink = response.clientList; // List documents in background and show message // tvFileList.Nodes.Clear(); // documentSetList.ListInTree(tvFileList, "CLIENT"); BUSClientDocument.ListInTree(documentSetList, tvFileList, "CLIENT" ); if (tvFileList.Nodes.Count > 0) tvFileList.Nodes[0].Expand(); } /// <summary> /// Load documents for a Client Document Set /// </summary> private void loadDocumentList() { var clientDocumentListRequest = new BUSClientDocument.ClientDocumentListRequest(); clientDocumentListRequest.clientDocumentSetUID = Utils.ClientSetID; clientDocumentListRequest.clientUID = Utils.ClientID; var clientDocumentListResponse = BUSClientDocument.List(clientDocumentListRequest); tvFileList.Nodes.Clear(); UIHelper.ClientDocumentUIHelper.ListInTree(tvFileList, "CLIENT", clientDocumentListResponse.clientList); if (tvFileList.Nodes.Count > 0) tvFileList.Nodes[0].Expand(); } /// <summary> /// Remove documents already selected from client list /// </summary> /// <param name="treeView"></param> private void RemoveDocumentsAlreadySelected(TreeView treeView) { foreach (TreeNode node in treeView.Nodes) { var key = (Document)node.Tag; TreeNode[] tn = tvFileList.Nodes.Find(key.Name, true); if (tn.Count() > 0) { tn[0].Remove(); } } } // // Load metadata // private void loadClientMetadataList() { //clientMetadataTable.Rows.Clear(); // Load client metadata ReportMetadataList rmd = new ReportMetadataList(); rmd.ListMetadataForClient( Utils.ClientID ); //foreach (ReportMetadata metadata in rmd.reportMetadataList) //{ // DataRow elementRow = clientMetadataTable.NewRow(); // elementRow["Enabled"] = metadata.Enabled; // elementRow["UID"] = metadata.UID; // elementRow["RecordType"] = metadata.RecordType; // elementRow["FieldCode"] = metadata.FieldCode; // elementRow["Description"] = metadata.Description; // elementRow["ClientType"] = metadata.ClientType; // elementRow["ClientUID"] = metadata.ClientUID; // elementRow["InformationType"] = metadata.InformationType; // elementRow["Condition"] = metadata.Condition; // elementRow["CompareWith"] = metadata.CompareWith; // clientMetadataTable.Rows.Add(elementRow); //} // Load in tree // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding // tvMetadata.ImageList = imageList; // Clear nodes // tvMetadata.Nodes.Clear(); TreeNode root = new TreeNode("Metadata", FCMConstant.Image.Checked, FCMConstant.Image.Checked); root.Name = "Metadata"; //tvMetadata.Nodes.Add( root ); foreach (ReportMetadata metadata in rmd.reportMetadataList) { ReportMetadata report = new ReportMetadata(); report.Enabled = metadata.Enabled; report.UID = metadata.UID; report.RecordType = metadata.RecordType; report.FieldCode = metadata.FieldCode; report.Description = metadata.Description; report.ClientType = metadata.ClientType; report.ClientUID = metadata.ClientUID; report.InformationType = metadata.InformationType; report.Condition = metadata.Condition; report.CompareWith = metadata.CompareWith; var image = report.Enabled == 'Y' ? 8 : 9; TreeNode tn = new TreeNode( metadata.FieldCode, image, image ); tn.Name = metadata.FieldCode; tn.Tag = report; root.Nodes.Add( tn ); } //tvMetadata.ExpandAll(); } private void removeToolStripMenuItem_Click(object sender, EventArgs e) { //if (dgvDocumentList.SelectedRows.Count <= 0) // return; //var selectedRow = dgvDocumentList.SelectedRows; //foreach (var row in selectedRow) //{ // DataGridViewRow dgvr = (DataGridViewRow)row; // dgvr.Cells["Void"].Value = 'Y'; //} } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { cbxDocumentSet.Items.Clear(); cbxDocumentSet.Text = ""; indexChanged(); if (string.IsNullOrEmpty(cbxDocumentSet.Text)) { tsbtnLinks.Enabled = false; tsmiLinks.Enabled = false; } else { tsbtnLinks.Enabled = true; tsmiLinks.Enabled = true; } } // // Index change on client document set // private void cbxDocumentSet_SelectedIndexChanged(object sender, EventArgs e) { SelectedIndexChange(); } /// <summary> /// Refresh list /// </summary> private void SelectedIndexChange() { // Get document set UID // string[] part = cbxDocumentSet.SelectedItem.ToString().Split(';'); // documentSetUID = Convert.ToInt32(part[1]); Utils.ClientSetID = Convert.ToInt32(part[1]); // Retrieve document set for a client // var clientDocSet = new ClientDocumentSet(); // documentSetUID = 1; clientDocSet.Get(Utils.ClientID, Utils.ClientSetID); txtSourceFolder.Text = clientDocSet.SourceFolder; txtDestinationFolder.Text = clientDocSet.Folder; txtFolderOnly.Text = clientDocSet.FolderOnly; txtDocumentSetDesc.Text = clientDocSet.Description; // Load documents for a Client Document Set // loadDocumentList(); loadClientMetadataList(); labelStatus.Text = ListOfDocumentSets[cbxDocumentSet.SelectedIndex].Status; EnableDisableFields(); } private void btnSelectSource_Click(object sender, EventArgs e) { folderBrowserDialog1.ShowNewFolderButton = true; folderBrowserDialog1.ShowDialog(); txtSourceFolder.Text = folderBrowserDialog1.SelectedPath; if (folderBrowserDialog1.SelectedPath == String.Empty) return; var folderSource = ""; var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); if (txtSourceFolder.Text.Contains(templateFolder)) { folderSource = txtSourceFolder.Text.Replace(templateFolder, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); txtSourceFolder.Text = folderSource; } } private void btnSelectDestination_Click(object sender, EventArgs e) { folderBrowserDialog1.ShowNewFolderButton = true; folderBrowserDialog1.ShowDialog(); if (folderBrowserDialog1.SelectedPath == String.Empty) return; txtDestinationFolder.Text = folderBrowserDialog1.SelectedPath; var folderDestination = ""; var clientFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.CLIENTFOLDER); if (txtDestinationFolder.Text.Contains(clientFolder)) { folderDestination = txtDestinationFolder.Text.Replace(clientFolder, FCMConstant.SYSFOLDER.CLIENTFOLDER); txtDestinationFolder.Text = folderDestination; } } // Save Click private void btnSave_Click(object sender, EventArgs e) { Save(); UpdateDocumentLocation(); MessageBox.Show("Client document set saved successfully."); } // ---------------------------------------------------------- // Save client documents // ---------------------------------------------------------- private void Save() { ClientDocument cdsl = new ClientDocument(); ClientDocumentSet docSet = new ClientDocumentSet(); var lodsl = new ListOfscClientDocSetDocLink(); lodsl.list = new List<scClientDocSetDocLink>(); // Move data into views.. if (string.IsNullOrEmpty( cbxDocumentSet.Text ) ) { MessageBox.Show("Document set not selected or created."); return; } string[] docSetUIDrude = cbxDocumentSet.Text.Split(';'); string docSetUIDText = docSetUIDrude[1]; int selUID = Convert.ToInt32(docSetUIDText); docSet.Get(Utils.ClientID, selUID); docSet.ClientSetID = selUID; docSet.Folder = txtDestinationFolder.Text; docSet.SourceFolder = txtSourceFolder.Text; if (string.IsNullOrEmpty(txtSourceFolder.Text)) { MessageBox.Show("Source Folder is Empty. Please fix and save again."); } docSet.Description = txtDocumentSetDesc.Text; var response = docSet.Update(); if (response.ReturnCode <= 0) { MessageBox.Show("Error saving document. " + response.Message); return; } // Save complete tree... SaveTreeNodeToClient(tvFileList, 0); // Save all the document types // loadDocumentList(); loadClientMetadataList(); } // ------------------------------------------------------------------- // Saves each node of a client tree // ------------------------------------------------------------------- private void SaveTreeNodeToClient(TreeView treeView, int parentID) { foreach (TreeNode node in treeView.Nodes) { var documentLink = (scClientDocSetDocLink)node.Tag; SaveTreeNodeToClient(node, documentLink.clientDocument.UID); } } private TreeNode SaveTreeNodeToClient(TreeNode treeNode, int parentID) { TreeNode ret = new TreeNode(); ClientDocument cdsl = new ClientDocument(); var t = treeNode.Tag.GetType(); // If the type is not document, it is an existing document // // var documentLink = new FCMStructures.scClientDocSetDocLink(); var documentLink = new scClientDocSetDocLink(); if (t.Name == "scClientDocSetDocLink") { documentLink = (scClientDocSetDocLink)treeNode.Tag; documentLink.clientDocument.SequenceNumber = treeNode.Index; if (documentLink.document.UID == 0) { LogFile.WriteToTodaysLogFile("Document UID is empty." + documentLink.clientDocument.FKClientUID); return ret; } } // // If the type is Document, it means a new document added to the client // list // if (t.Name == "Document") #region Document { documentLink.document = new Document(); documentLink.document = (Document)treeNode.Tag; documentLink.clientDocument = new ClientDocument(); documentLink.clientDocumentSet = new ClientDocumentSet(); // Fill in the extra details... // documentLink.clientDocument.EndDate = System.DateTime.MaxValue; documentLink.clientDocument.FKClientDocumentSetUID = Utils.ClientSetID; documentLink.clientDocument.FKClientUID = Utils.ClientID; if (Utils.ClientID <= 0) { MessageBox.Show("Client ID is invalid."); return null; } documentLink.clientDocument.FKDocumentUID = documentLink.document.UID; documentLink.clientDocument.Generated = 'N'; documentLink.clientDocument.SourceIssueNumber = documentLink.document.IssueNumber; documentLink.clientDocument.ClientIssueNumber = 00; // When the source is client, the name will have already all the numbers // //if (documentLink.document.SourceCode == Utils.SourceCode.CLIENT) //{ // documentLink.clientDocument.ComboIssueNumber = documentLink.document.CUID; //} //else //{ //} if (documentLink.document.RecordType == FCMConstant.RecordType.FOLDER) { documentLink.clientDocument.ComboIssueNumber = documentLink.document.CUID; documentLink.clientDocument.FileName = documentLink.document.SimpleFileName; } else { //documentLink.clientDocument.ComboIssueNumber = //ClientDocument.GetComboIssueNumber(documentLink.document.CUID, // documentLink.document.IssueNumber, // Utils.ClientID); documentLink.clientDocument.ComboIssueNumber = BUSClientDocument.GetComboIssueNumber( documentLink.document.CUID, documentLink.document.IssueNumber, Utils.ClientID ); documentLink.clientDocument.FileName = documentLink.clientDocument.ComboIssueNumber + " " + documentLink.document.SimpleFileName; } documentLink.clientDocument.IsProjectPlan = documentLink.document.IsProjectPlan; documentLink.clientDocument.DocumentCUID = documentLink.document.CUID; documentLink.clientDocument.DocumentType = documentLink.document.DocumentType; // The client document location includes the client path (%CLIENTFOLDER%) plus the client document set id // %CLIENTFOLDER%\CLIENTSET201000001R0001\ // How to identify the parent folder // // documentLink.clientDocument.ParentUID = destFolder.clientDocument.UID; documentLink.clientDocument.ParentUID = parentID; // documentLink.clientDocument.Location = txtDestinationFolder.Text + // Utils.GetClientPathInside(documentLink.document.Location); // documentLink.clientDocument.Location = GetClientDocumentLocation( parentID ); documentLink.clientDocument.Location = BUSClientDocument.GetClientDocumentLocation( parentID ); documentLink.clientDocument.RecordType = documentLink.document.RecordType; documentLink.clientDocument.SequenceNumber = treeNode.Index; documentLink.clientDocument.SourceFileName = documentLink.document.FileName; documentLink.clientDocument.SourceLocation = documentLink.document.Location; documentLink.clientDocument.StartDate = System.DateTime.Today; documentLink.clientDocument.UID = 0; documentLink.clientDocumentSet.UID = Utils.ClientSetID; documentLink.clientDocumentSet.SourceFolder = txtSourceFolder.Text; documentLink.clientDocumentSet.ClientSetID = Utils.ClientSetID; documentLink.clientDocumentSet.FKClientUID = Utils.ClientID; documentLink.clientDocumentSet.Folder = txtDestinationFolder.Text; } #endregion Document // Save link to database // // documentLink.clientDocument.UID = cdsl.LinkDocumentToClientSet(documentLink); documentLink.clientDocument.UID = BUSClientDocument.LinkDocumentToClientSet( documentLink ); foreach (TreeNode children in treeNode.Nodes) { SaveTreeNodeToClient(children, documentLink.clientDocument.UID); } return ret; } private void btnNew_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; var response = BUSClientDocumentSet.ClientDocumentSetAdd(HeaderInfo.Instance); indexChanged(); SelectedIndexChange(); MessageBox.Show( response.Message, "No password", MessageBoxButtons.OK, response.Icon ); Cursor.Current = Cursors.Arrow; } private void UIClientDocumentSet_FormClosed(object sender, FormClosedEventArgs e) { } public void RefreshMetadata() { loadClientMetadataList(); } /// <summary> /// Generate document /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGenerate_Click(object sender, EventArgs e) { GenerateDocument("ONLINE"); } /// <summary> /// Generate documents. /// </summary> /// <param name="how"></param> public void GenerateDocument(string how) { // Initial checks if (string.IsNullOrEmpty(txtDestinationFolder.Text)) { MessageBox.Show("Destination folder for client documents not defined."); return; } var answer = MessageBox.Show("Would you like to proceed with the document generation?", "Generate Documents", MessageBoxButtons.YesNo); overrideDocuments = "No"; if (answer == DialogResult.Yes) { var over = MessageBox.Show("Would you like to replace generated documents?", "Override Documents", MessageBoxButtons.YesNo); if (over == DialogResult.Yes) { overrideDocuments = "Yes"; } } else return; if (how == "ONLINE") GenerateDocumentOnline(); if (how == "BACKGROUND") GenerateDocumentBackground(); } /// <summary> /// Online Document Generation /// </summary> public void GenerateDocumentOnline() { var uioutput = new Windows.UIOutputMessage(); uioutput.Show(); uioutput.WindowState = FormWindowState.Maximized; uioutput.AddOutputMessage( "Document generation starting...", "UI", Utils.UserID ); DocumentGeneration wdt = new DocumentGeneration(ClientID: Utils.ClientID, ClientDocSetID: Utils.ClientSetID, UIoutput: uioutput, OverrideDocuments: overrideDocuments, inprocessName:"UI", inuserID: Utils.UserID); tndocSelected = tvFileList.SelectedNode; if (tndocSelected == null) { // Try to select the root folder when no item has been selected // tndocSelected = tvDocumentsAvailable.Nodes[0]; // MessageBox.Show( "Folder not selected in tree" ); // return; } // If document selected is SRG-01 - Generate System Register var document = new scClientDocSetDocLink(); document = (scClientDocSetDocLink) tndocSelected.Tag; // toolStripStatusLabel1.Text = "Please wait while documents are generated..."; uioutput.AddOutputMessage( "Please wait...", "UI", Utils.UserID ); Cursor.Current = Cursors.WaitCursor; // Save first or make // uioutput.AddOutputMessage( "Saving documents...", "UI", Utils.UserID ); Save(); // Update Location // uioutput.AddOutputMessage( "Fixing document location...", "UI", Utils.UserID ); UpdateDocumentLocation(); // Generate document // wdt.GenerateDocumentsForClient( tndocSelected ); //// Generate Register of Systems Documents //// //if ( document.document.CUID == "SRG-01" ) //{ // WordReport wr = new WordReport( ClientID: Utils.ClientID, ClientDocSetID: Utils.ClientSetID, // UIoutput: uioutput, // OverrideDocuments: overrideDocuments ); // // var response = wr.RegisterOfSytemDocuments2( tvFileList, txtDestinationFolder.Text, wr.FullFileNamePath, document ); // var response = wr.RegisterOfSytemDocuments2( tvFileList, txtDestinationFolder.Text, wr.FullFileNamePath ); // uioutput.AddOutputMessage( response.Message ); //} Cursor.Current = Cursors.Arrow; toolStripStatusLabel1.Text = "Document generation completed."; // Update list SelectedIndexChange(); // uioutput.AddOutputMessage( "Generation completed." ); } public void GenerateDocumentBackground() { Cursor.Current = Cursors.WaitCursor; BUSProcessRequest.GenerateDocumentClient(Utils.ClientID, Utils.ClientSetID, overrideDocuments,0, HeaderInfo.Instance.UserID); Cursor.Current = Cursors.Arrow; MessageBox.Show("Document Process Requested."); } /// <summary> /// This process will initiate a thread to run the report. Under construction. /// </summary> private void GenerateDocument(object sender, DoWorkEventArgs e) { var uioutput = new Windows.UIOutputMessage(); uioutput.Show(); // uioutput.WindowState = FormWindowState.Maximized; //DocumentGeneration wdt = new DocumentGeneration( ClientID: Utils.ClientID, ClientDocSetID: Utils.ClientSetID, // UIoutput: uioutput, // OverrideDocuments: overrideDocuments); DocumentGeneration wdt = new DocumentGeneration( ClientID: Utils.ClientID, ClientDocSetID: Utils.ClientSetID, UIoutput: this, OverrideDocuments: overrideDocuments, inprocessName:"UI", inuserID:Utils.UserID ); wdt.GenerateDocumentsForClient( tndocSelected ); return; } // It shows the progress of the generation on the taskbar // private void ShowInTaskBar() { return; } private void notifyIcon1_MouseMove( object sender, MouseEventArgs e ) { // notifyIcon1.Text = "it will be updated..."; return; } // ----------------------------------------------------- // This method replicates folders and files for a given // folder structure (source and destination) // ----------------------------------------------------- private void ReplicateFolderFilesReplace() { Cursor.Current = Cursors.WaitCursor; Word.Application vkWordApp = new Word.Application(); string sourceFolder = txtSourceFolder.Text; string destinationFolder = txtDestinationFolder.Text; if (sourceFolder == "" || destinationFolder == "") { return; } // Retrieve client metadata // // 1... // 2... // Find client metadata ReportMetadataList clientMetadata = new ReportMetadataList(); clientMetadata.ListMetadataForClient(Utils.ClientID); var ts = new List<WordDocumentTasks.TagStructure>(); // Load variables/ metadata into memory // foreach (ReportMetadata metadata in clientMetadata.reportMetadataList) { // Source Information // Create a class to source the information //... // string value = DataColector.Get(metadata); string value = metadata.GetValue(); ts.Add(new WordDocumentTasks.TagStructure() { Tag = metadata.FieldCode, TagValue = value }); } return; //WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder); //WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp); //Cursor.Current = Cursors.Arrow; //MessageBox.Show("Project Successfully Created."); } // ----------------------------------------------------- // This method replicates folders and files for a given // folder structure (source and destination) // ----------------------------------------------------- private void ReplicateFolderFilesReplaceOld() { Cursor.Current = Cursors.WaitCursor; Word.Application vkWordApp = new Word.Application(); // The source comes from the document set // The destination is selected and stored also // string sourceFolder = txtSourceFolder.Text; string destinationFolder = txtDestinationFolder.Text; if (sourceFolder == "" || destinationFolder == "") { return; } var ts = new List<WordDocumentTasks.TagStructure>(); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<XX>>", TagValue = "VV1" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<YY>>", TagValue = "VV2" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<VV>>", TagValue = "VV3" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientNAME>>", TagValue = "Client 2" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientADDRESS>>", TagValue = "St Street" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientEMAILADDRESS>>", TagValue = "Email@com" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientPHONE>>", TagValue = "09393893" }); WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder); WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp); Cursor.Current = Cursors.Arrow; MessageBox.Show("Project Successfully Created."); } private void btnDefineClient_Click(object sender, EventArgs e) { UIClientMetadata ucm = new UIClientMetadata(this); ucm.Show(); } private void UIClientDocumentSet_Leave(object sender, EventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Dispose(); } private void dgvDocumentList_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void btnDelete_DragDrop(object sender, DragEventArgs e) { TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; if (tndocSelected == null) return; tndocSelected.Remove(); // Update database with new sequence numbers // // UpdateSequence(parent); // Delete element (If it is already commited // The scClientDocSetDocLink is only stored for commited documents // The "Document" type is new one, so just ignore // if (tndocSelected.Tag.GetType().Name == "scClientDocSetDocLink") { SetToVoid( tndocSelected ); } tvFileList.SelectedNode = parent; } // -------------------------------------------------- // Each element under the main node should be deleted // -------------------------------------------------- private void SetToVoid(TreeNode node) { var document = new scClientDocSetDocLink(); document = (scClientDocSetDocLink)node.Tag; BUSClientDocument.SetToVoid( clientUID: Utils.ClientID, clientDocumentSetUID: document.clientDocumentSet.UID, documentUID: document.clientDocument.FKDocumentUID ); BUSClientDocument.DeleteFile( document.clientDocument.UID ); //document.clientDocument.SetToVoid( clientUID: Utils.ClientID, clientDocumentSetUID: document.clientDocumentSet.UID, documentUID: document.clientDocument.FKDocumentUID ); //document.clientDocument.DeleteFile(); ClientDocumentLinkList.VoidLinks( Utils.ClientID, document.clientDocumentSet.UID, document.clientDocument.FKDocumentUID ); // Daniel: 01/06/2010 // Remover/ Inabilitar todos os links // foreach (TreeNode nodeToDelete in node.Nodes) { SetToVoid(nodeToDelete); } } // -------------------------------------------------- // Each element under the main node should be deleted // -------------------------------------------------- private void DeleteClientDocument( TreeNode node ) { var document = new scClientDocSetDocLink(); if ( node.Tag.GetType().Name != "scClientDocSetDocLink" ) return; document = (scClientDocSetDocLink)node.Tag; ClientDocumentLinkList.DeleteLinks( Utils.ClientID, document.clientDocumentSet.UID, document.clientDocument.FKDocumentUID ); // try physical delete first. // //var deleteResponse = document.clientDocument.Delete( clientUID: Utils.ClientID, clientDocumentSetUID: document.clientDocumentSet.UID, documentUID: document.clientDocument.FKDocumentUID ); var deleteResponse = BUSClientDocument.ClientDocumentDelete( HeaderInfo.Instance, clientUID: Utils.ClientID, clientDocumentSetUID: document.clientDocumentSet.UID, clientDocumentUID: document.clientDocument.UID ); if (deleteResponse.ReturnCode < 0001) { // If it can't be physically delete, void it. // // document.clientDocument.SetToVoid( clientUID: Utils.ClientID, clientDocumentSetUID: document.clientDocumentSet.UID, documentUID: document.clientDocument.FKDocumentUID ); BUSClientDocument.SetToVoid( clientUID: Utils.ClientID, clientDocumentSetUID: document.clientDocumentSet.UID, documentUID: document.clientDocument.FKDocumentUID ); // If the document can't be physically deleted it is likely that is has versions (issues). // In this scenario the document will be set to void but the issues will remain active. } // Determine file location // //document.clientDocument.DeleteFile(); BUSClientDocument.DeleteFile(document.clientDocument.UID); // Daniel: 01/06/2010 // Remover/ Inabilitar todos os links // foreach (TreeNode nodeToDelete in node.Nodes) { DeleteClientDocument( nodeToDelete ); } } private void tvDocumentsAvailable_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvFileList_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvFileList_DragDrop(object sender, DragEventArgs e) { AddDocumentToClient(sender, e); } private void AddDocumentToClient(object sender, DragEventArgs e) { // Get selected document from tree // TreeNode tnDocumentAvailableSelected = tvDocumentsAvailable.SelectedNode; if (tnDocumentAvailableSelected == null) return; tndocSelected = tvFileList.SelectedNode; Document documentSelected = (Document)tnDocumentAvailableSelected.Tag; // tndocselected.ComboIssueNumber = tndocselected.CUID + "-00-" + Utils.ClientID.ToString( "0000" ) + "-00"; // Only if client document is selected // If it is a document from the regular set, keep it // if ( documentSelected.Name.Substring( 0, 3 ) == "CLI" ) { documentSelected.Name = documentSelected.CUID + "-00-" + Utils.ClientID.ToString("0000") + "-00" + " " + documentSelected.SimpleFileName; } // tndocselected.FileName = tndocselected.Name; documentSelected.FileName = documentSelected.FileName; tnDocumentAvailableSelected.Text = documentSelected.Name; #region Available Selected // If root hasn't been created // if (tvFileList.Nodes.Count == 0) #region Create Root Node { // Add root node // ClientDocument clientDocument = new ClientDocument(); // clientDocument.AddRootFolder(Utils.ClientID, Utils.ClientSetID, txtDestinationFolder.Text); BUSClientDocument.AddRootFolder( clientDocument, Utils.ClientID, Utils.ClientSetID, txtDestinationFolder.Text ); loadDocumentList(); // Remove from available tree // tnDocumentAvailableSelected.Remove(); // Save to client tree // tvFileList.TopNode.Nodes.Add(tnDocumentAvailableSelected); } #endregion Create Root Node else #region Root Node Exists { if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvFileList.PointToClient(new Point(e.X, e.Y)); destinationNode = tvFileList.GetNodeAt(pt); if (destinationNode == null) return; var destFolder = new scClientDocSetDocLink(); destFolder = (scClientDocSetDocLink)destinationNode.Tag; if (tnDocumentAvailableSelected != null) { // Remove from available tree // tnDocumentAvailableSelected.Remove(); // Save to client tree // destinationNode.Nodes.Add(tnDocumentAvailableSelected); } else { if (tndocSelected != null) { // Remove from available tree // tndocSelected.Remove(); // Save to client tree // destinationNode.Nodes.Add(tndocSelected); } } } #endregion Root Node Exists } #endregion Available Selected } private void tvDocumentsAvailable_DragDrop(object sender, DragEventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvDocumentsAvailable.SelectedNode; if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvDocumentsAvailable.PointToClient(new Point(e.X, e.Y)); destinationNode = tvFileList.GetNodeAt(pt); if (tndocSelected == null) return; // If destination tree is the same as source tree, do nothing if (destinationNode.TreeView == tndocSelected.TreeView) return; // If the destination folder is the same, just move the order of // elements tndocSelected.Remove(); destinationNode.Nodes.Add(tndocSelected); } } private void tvFileList_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void tvDocumentsAvailable_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void tvFileList_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e) { var t = e.Node.Tag.GetType(); if (t.Name == "scClientDocSetDocLink") { var document = (scClientDocSetDocLink)e.Node.Tag; string info = "Document \n" + "Index: " + e.Node.Index + " \n" + "Sequence Number : " + document.clientDocument.SequenceNumber + " \n" + "Client Doco UID: " + document.clientDocument.UID + "\n" + "Document UID: " + document.document.UID + "\n" + "Document CUID: " + document.document.CUID + "\n" + "Parent UID: " + document.clientDocument.ParentUID + "\n" + "Client Source File Name: " + document.clientDocument.SourceFileName + "\n" + "Client Report Type: " + document.clientDocument.RecordType; toolTip1.Show(info, tvFileList, 400, 10, 20000); } if (t.Name == "Document") { var document = (Document)e.Node.Tag; string info = "Document \n" + "Document UID: " + document.UID + "\n" + "Document CUID: " + document.CUID + "\n"; toolTip1.Show(info, tvFileList, 400, 10, 20000); } } private void addRootToolStripMenuItem_Click(object sender, EventArgs e) { var clientDocument = new ClientDocument(); //clientDocument.AddRootFolder(Utils.ClientID, Utils.ClientSetID, txtDestinationFolder.Text); BUSClientDocument.AddRootFolder( clientDocument, Utils.ClientID, Utils.ClientSetID, txtDestinationFolder.Text ); loadDocumentList(); } private void picUp_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; if (tndocSelected.Index > 0) { int i = tndocSelected.Index - 1; tndocSelected.Remove(); parent.Nodes.Insert(i, tndocSelected); tvFileList.SelectedNode = tndocSelected; // Update sequence number var document = new scClientDocSetDocLink(); document = (scClientDocSetDocLink)tndocSelected.Tag; document.clientDocument.SequenceNumber = tndocSelected.Index; } } private void picDown_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; int i = tndocSelected.Index + 1; tndocSelected.Remove(); parent.Nodes.Insert(i, tndocSelected); tvFileList.SelectedNode = tndocSelected; // Update sequence number var document = new scClientDocSetDocLink(); document = (scClientDocSetDocLink)tndocSelected.Tag; document.clientDocument.SequenceNumber = tndocSelected.Index; } private void btnDelete_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } // ------------------------------------------------------ // Select all documents for a client // ------------------------------------------------------ private void btnCopyAll_Click(object sender, EventArgs e) { CopyAll(); SelectedIndexChange(); // Clear nodes tvDocumentsAvailable.Nodes.Clear(); var docoList = new DocumentList(); docoList.List(); // Reload Available Documents // Document root = new Document(); // root.GetRoot(HeaderInfo.Instance); // root = RepDocument.GetRoot(HeaderInfo.Instance); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvDocumentsAvailable, docoList, root); } // This method copies all documents to a client // private void CopyAll() { tsbtnDelete.Enabled = false; tsbtnCopyAll.Enabled = false; if (tvFileList.Nodes.Count <= 0) { ClientDocument clientDocument = new ClientDocument(); // clientDocument.AddRootFolder(Utils.ClientID, Utils.ClientSetID, txtDestinationFolder.Text); //clientDocument.AddRootFolder(Utils.ClientID, Utils.ClientSetID, txtFolderOnly.Text); BUSClientDocument.AddRootFolder( clientDocument, Utils.ClientID, Utils.ClientSetID, txtFolderOnly.Text ); loadDocumentList(); } while (tvDocumentsAvailable.Nodes[0].Nodes.Count > 0) { TreeNode tn = tvDocumentsAvailable.Nodes[0].Nodes[0]; tn.Remove(); //TreeNode clone = new TreeNode(); //clone = (TreeNode)tn.Clone(); tvFileList.Nodes[0].Nodes.Add(tn); } tvFileList.SelectedNode = tvFileList.Nodes[0]; // ------------------------------------------------------------------- // The documents have been moved from the available to client's tree // Now it is time to save the documents // ------------------------------------------------------------------- Save(); ClientDocumentLink cloneLinks = new ClientDocumentLink(); cloneLinks.ReplicateDocSetDocLinkToClient(Utils.ClientID, Utils.ClientSetID, documentSet.UID); indexChanged(); } private void viewDocumentToolStripMenuItem_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast Utils.OpenDocument( rm.clientDocument.Location, rm.clientDocument.FileName, rm.clientDocument.DocumentType, vkReadOnly: true); } private void documentsToolStripMenuItem_Click(object sender, EventArgs e) { } private void tsbtnRemoveDocument_Click(object sender, EventArgs e) { TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; if (tndocSelected == null) { return; } else { var results = MessageBox.Show("Are you sure?", "Confirm document delete", MessageBoxButtons.YesNo); if (results == DialogResult.Yes) { tndocSelected.Remove(); // Delete element (If it is already commited // The scClientDocSetDocLink is only stored for commited documents // The "Document" type is new one, so just ignore // if (tndocSelected.Tag.GetType().Name == "scClientDocSetDocLink") { SetToVoid(tndocSelected); } tvFileList.SelectedNode = parent; } } } private void RemoveDocument(object sender, EventArgs e) { TreeNode tndocSelected = tvFileList.SelectedNode; if (tndocSelected == null) return; TreeNode parent = tndocSelected.Parent; if (tndocSelected == null) { return; } else { // Check if document set is completed. Do not allow changes. // if (labelStatus.Text == "COMPLETED") { MessageBox.Show("Document set is finalised. It can't be changed."); return; } var results = MessageBox.Show("Are you sure?", "Confirm document delete", MessageBoxButtons.YesNo); if (results == DialogResult.Yes) { // Delete element (If it is already commited // The scClientDocSetDocLink is only stored for commited documents // The "Document" type is new one, so just ignore // if (tndocSelected.Tag.GetType().Name == "scClientDocSetDocLink") { // SetToVoid(tndocSelected); DeleteClientDocument( tndocSelected ); } tvFileList.SelectedNode = parent; // Remove after // tndocSelected.Remove(); } } // Refresh screen indexChanged(); } private void tvFileList_AfterSelect(object sender, TreeViewEventArgs e) { if (labelStatus.Text != "COMPLETED") { tsbtnDelete.Enabled = true; tsbtnDown.Enabled = true; tsbtnUp.Enabled = true; } // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; if (docSelected.Tag is scClientDocSetDocLink) { rm = (scClientDocSetDocLink)docSelected.Tag; // Cast if (rm.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.PDF) { string filePathName = Utils.getFilePathName( rm.clientDocument.Location, rm.clientDocument.FileName ); // webBrowser1.Url = new Uri( filePathName ); //webBrowser1.Navigate( filePathName ); //webBrowser1.AllowWebBrowserDrop = true; } // Display full path on status bar // var parentLocation = BUSClientDocument.GetClientDocumentLocation(rm.clientDocument.ParentUID); // toolStripStatusLabel1.Text = rm.clientDocument.Location; // toolStripStatusLabel1.Text = "CD: " + rm.clientDocument.Location + " >> PL: " + parentLocation; toolStripStatusLabel1.Text = rm.clientDocument.Location; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tvFileList_Leave(object sender, EventArgs e) { tsbtnDelete.Enabled = false; tsbtnDown.Enabled = false; tsbtnUp.Enabled = false; } // // Delete action - toolbar // private void toolStripButton3_Click(object sender, EventArgs e) { } private void viewDocumentToolStripMenuItem1_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvProjectPlan.SelectedNode; var rm = new ClientDocumentLink(); if (docSelected == null) return; rm = (ClientDocumentLink)docSelected.Tag; // Cast if (rm.childClientDocument.RecordType.Trim() == FCMConstant.RecordType.DOCUMENT) { string filePathName = Utils.getFilePathName(txtDestinationFolder.Text + rm.childClientDocument.Location, rm.childClientDocument.FileName); WordDocumentTasks.OpenDocument(filePathName, vkReadOnly: true); } } // Document List index change // private void cbxDocSet_SelectedIndexChanged(object sender, EventArgs e) { SelectIndexChanged(); } // This index handles the document list // private void SelectIndexChanged() { int documentSetUID = 0; if (string.IsNullOrEmpty(cbxDocSet.Text) || cbxDocumentSet.Visible == false) { documentSetUID = 0; } else { string[] ArrayDocSetText = cbxDocSet.Text.Split(';'); documentSetUID = Convert.ToInt32(ArrayDocSetText[0]); } if (documentSetUID == 0) loadDocumentList(); else { if (documentSetUID == 99) { // Load document specific for a client // loadDocumentListClient(); } else { loadDocumentList(documentSetUID); } } } // // Load document list for a client set // public void loadDocumentList(int documentSetUID = 0) { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvDocumentsAvailable.ImageList = imageList; // Clear nodes tvDocumentsAvailable.Nodes.Clear(); // List Document Set documentSet.UID = documentSetUID; documentSet.Read(IncludeDocuments: 'Y'); // Load document in the treeview // Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvDocumentsAvailable, documentSet.documentList, root); tvDocumentsAvailable.Nodes[0].Expand(); } // // Load document list for a client // // ------------------------------------------ // List Documents // ------------------------------------------ public void loadDocumentListClient() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvDocumentsAvailable.ImageList = imageList; // Clear nodes tvDocumentsAvailable.Nodes.Clear(); var docoList = new DocumentList(); docoList.ListClient(Utils.ClientID); // Load document in the treeview // // docoList.ListInTree(tvFileList); Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvDocumentsAvailable, docoList, root); tvDocumentsAvailable.ExpandAll(); } private void tsmiLinks_Click(object sender, EventArgs e) { UIClientDocumentLink uicdl = new UIClientDocumentLink(cbxClient.Text, cbxDocumentSet.Text); uicdl.ShowDialog(); } private void tsmiAddDocument_Click(object sender, EventArgs e) { UIDocumentEdit uide = new UIDocumentEdit(this, Utils.ClientID); uide.ShowDialog(); } private void newVersionToolStripMenuItem_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast if (rm.clientDocument.RecordType == FCMConstant.RecordType.DOCUMENT) { if (rm.clientDocument.Generated != 'Y') { MessageBox.Show("A version can only be created after the file is generated."); return; } //var results = rm.clientDocument.NewVersion(); var results = BUSClientDocument.NewVersion( rm.clientDocument ); if ( !string.IsNullOrEmpty( results ) ) { MessageBox.Show("New version created: " + results); } } indexChanged(); } private void tvDocumentsAvailable_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e) { return; // Enable if necessary var t = e.Node.Tag.GetType(); if (t.Name == "scClientDocSetDocLink") { var document = (scClientDocSetDocLink)e.Node.Tag; string info = "Document \n" + "Index: " + e.Node.Index + " \n" + "Sequence Number : " + document.clientDocument.SequenceNumber + " \n" + "Client Doco UID: " + document.clientDocument.UID + "\n" + "Document UID: " + document.document.UID + "\n" + "Document CUID: " + document.document.CUID + "\n" + "Parent UID: " + document.clientDocument.ParentUID + "\n" + "Client Source File Name: " + document.clientDocument.SourceFileName + "\n" + "Client Report Type: " + document.clientDocument.RecordType; toolTip1.Show(info, tvFileList, 400, 10, 20000); } if (t.Name == "Document") { var document = (Document)e.Node.Tag; string info = "Document \n" + "Document UID: " + document.UID + "\n" + "Document CUID: " + document.CUID + "\n"+ "Simple Name: " + document.SimpleFileName + "\n"+ "Name: " + document.FileName + "\n"; toolTip1.Show(info, tvFileList, 400, 10, 20000); } } private void enableToolStripMenuItem_Click(object sender, EventArgs e) { //ReportMetadata rmd = new ReportMetadata(); //var selected = dgvClientMetadata.SelectedRows; //if (selected.Count > 0) //{ // GetSelectedRow(rmd, 0); // rmd.Enabled = 'Y'; // rmd.Save(); // // Update selected row // selected[0].Cells["Enabled"].Value = 'Y'; //} } /// <summary> /// Retrieve selected row from client metadata /// </summary> /// <param name="rm"></param> /// <param name="rowSubscript"></param> private void GetSelectedRow(ReportMetadata rm, int rowSubscript) { //if (dgvClientMetadata.SelectedRows.Count <= 0) // return; //if (dgvClientMetadata.SelectedRows.Count < rowSubscript) // return; //var selectedRow = dgvClientMetadata.SelectedRows; //ConvertSelectedRow(rm, selectedRow[rowSubscript]); //return; } private void ConvertSelectedRow(ReportMetadata rm, DataGridViewRow selectedRow) { rm.UID = Convert.ToInt32(selectedRow.Cells["UID"].Value.ToString()); rm.RecordType = selectedRow.Cells["RecordType"].Value.ToString(); rm.FieldCode = selectedRow.Cells["FieldCode"].Value.ToString(); rm.Description = selectedRow.Cells["Description"].Value.ToString(); rm.ClientType = selectedRow.Cells["ClientType"].Value.ToString(); rm.ClientUID = Convert.ToInt32(selectedRow.Cells["ClientUID"].Value.ToString()); rm.InformationType = selectedRow.Cells["InformationType"].Value.ToString(); rm.Condition = selectedRow.Cells["Condition"].Value.ToString(); rm.CompareWith = selectedRow.Cells["CompareWith"].Value.ToString(); rm.Enabled = Convert.ToChar(selectedRow.Cells["Enabled"].Value); return; } private void disableToolStripMenuItem_Click(object sender, EventArgs e) { //ReportMetadata rmd = new ReportMetadata(); //var selected = dgvClientMetadata.SelectedRows; //if (selected.Count > 0) //{ // GetSelectedRow(rmd, 0); // rmd.Enabled = 'N'; // rmd.Save(); // // Update selected row // selected[0].Cells["Enabled"].Value = 'N'; //} } private void selectToolStripMenuItem_Click( object sender, EventArgs e ) { // // Get selected document from tree // // 01-Jan-2012 - Commented out after removal of client metadata // //TreeNode docSelected = tvMetadata.SelectedNode; //var rmd = new ReportMetadata(); //if (docSelected == null) // return; //rmd = (ReportMetadata)docSelected.Tag; //rmd.Enabled = 'Y'; //rmd.Save(); //docSelected.ImageIndex = FCMConstant.Image.Checked; //docSelected.SelectedImageIndex = FCMConstant.Image.Checked; } private void unselectToolStripMenuItem_Click( object sender, EventArgs e ) { // // Get selected document from tree // // 01-Jan-2012 // Removed after client metadata // //TreeNode docSelected = tvMetadata.SelectedNode; //var rmd = new ReportMetadata(); //if (docSelected == null) // return; //rmd = (ReportMetadata)docSelected.Tag; //rmd.Enabled = 'N'; //rmd.Save(); //docSelected.ImageIndex = FCMConstant.Image.Unchecked; //docSelected.SelectedImageIndex = FCMConstant.Image.Unchecked; } /// <summary> /// Double click to change the state of the field /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tvMetadata_DoubleClick( object sender, EventArgs e ) { // // Get selected document from tree // //TreeNode docSelected = tvMetadata.SelectedNode; //var rmd = new ReportMetadata(); //if (docSelected == null) // return; //rmd = (ReportMetadata)docSelected.Tag; //if (rmd == null) // return; //if (rmd.Enabled == 'Y') //{ // rmd.Enabled = 'N'; // docSelected.Checked = false; // docSelected.ImageIndex = FCMConstant.Image.Unchecked; // docSelected.SelectedImageIndex = FCMConstant.Image.Unchecked; //} //else //{ // rmd.Enabled = 'Y'; // docSelected.ImageIndex = FCMConstant.Image.Checked; // docSelected.SelectedImageIndex = FCMConstant.Image.Checked; //} //rmd.Save(); } private void printToolStripMenuItem_Click( object sender, EventArgs e ) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; PrintDocument( docSelected ); } /// <summary> /// Print document or complete folder list /// </summary> /// <param name="document"></param> public void PrintDocument( TreeNode docSelected ) { var rm = new scClientDocSetDocLink(); rm = (scClientDocSetDocLink)docSelected.Tag; // Cast if (rm.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.FOLDER) { foreach (TreeNode tn in docSelected.Nodes) { // Print Document var docToPrint = new scClientDocSetDocLink(); docToPrint = (scClientDocSetDocLink)docSelected.Tag; PrintDocument( tn ); } } else { Utils.PrintDocument( rm.clientDocument.Location, rm.clientDocument.FileName, rm.clientDocument.DocumentType ); } } private void tvProjectPlan_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvProjectPlan.SelectedNode = tvProjectPlan.GetNodeAt( e.X, e.Y ); } } private void tvFileList_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvFileList.SelectedNode = tvFileList.GetNodeAt( e.X, e.Y ); } } private void tvDocumentsAvailable_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvDocumentsAvailable.SelectedNode = tvDocumentsAvailable.GetNodeAt( e.X, e.Y ); } } private void tvMetadata_MouseDown( object sender, MouseEventArgs e ) { //if (e.Button == MouseButtons.Right) //{ // tvMetadata.SelectedNode = tvMetadata.GetNodeAt( e.X, e.Y ); //} } private void gbDocuments_Enter( object sender, EventArgs e ) { } private void tsbtnRefresh_Click( object sender, EventArgs e ) { indexChanged(); } private void showDetailsToolStripMenuItem_Click( object sender, EventArgs e ) { } // // Implementing UIOutput implementation // public void AddOutputMessage( string outputMessage, string processName, string userID) { string msg = userID + " > " + processName + " > " + DateTime.Now + " > " + outputMessage; if (outputMessage.Length > 63) msg = outputMessage.Substring( 0, 63 ); //notifyIcon1.Text = msg; toolStripStatusLabel1.Text = msg; LogFile.WriteToTodaysLogFile( msg ); return; } public void AddErrorMessage( string errorMessage, string processName, string userID ) { return; } public void UpdateProgressBar( double value, DateTime estimatedTime, int documentsToBeGenerated = 0 ) { // toolStripProgressBar1.Value = (int)value; return; } private void googleDocsToolStripMenuItem_Click( object sender, EventArgs e ) { UIGoogleDocs uigoogledocs = new UIGoogleDocs( txtDestinationFolder.Text ); uigoogledocs.Show(); } private void locateInExploreToolStripMenuItem_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast // Show file dialog string filePathName = Utils.getFilePathName(rm.clientDocument.Location, rm.clientDocument.FileName); string filePath = Utils.GetPathName(rm.clientDocument.Location); openFileDialog1.FileName = rm.clientDocument.FileName; openFileDialog1.InitialDirectory = filePath; var file = openFileDialog1.ShowDialog(); } private void EnableDisableFields() { saveToolStripMenuItem.Enabled = true; removeToolStripMenuItem1.Enabled = true; addToolStripMenuItem.Enabled = true; generateToolStripMenuItem.Enabled = true; defineElementsToolStripMenuItem.Enabled = true; // Context removeToolStripMenuItem.Enabled = true; generateToolStripMenuItem1.Enabled = true; // Toolbar tsbtnGenerateDocument.Enabled = true; tsbtnNew.Enabled = true; tsbtnSave.Enabled = true; if (tvFileList.Nodes.Count == 0) { tsbtnDelete.Enabled = true; tsbtnCopyAll.Enabled = true; } if (labelStatus.Text == FCMConstant.DocumentSetStatus.COMPLETED) { saveToolStripMenuItem.Enabled = false; removeToolStripMenuItem1.Enabled = false; addToolStripMenuItem.Enabled = false; generateToolStripMenuItem.Enabled = false; defineElementsToolStripMenuItem.Enabled = false; // Context removeToolStripMenuItem.Enabled = false; generateToolStripMenuItem1.Enabled = false; // Toolbar tsbtnGenerateDocument.Enabled = false; tsbtnCopyAll.Enabled = false; tsbtnDelete.Enabled = false; tsbtnNew.Enabled = false; tsbtnSave.Enabled = false; } } private void menuItemGenerateMOS_Click(object sender, EventArgs e) { // Generate master of system documents // //var answer = MessageBox.Show( // "Would you like to proceed? (Y/N)", //"Register of System Documents", //MessageBoxButtons.YesNo); //if (answer != DialogResult.Yes) //{ // return; //} //var uioutput = new Windows.UIOutputMessage(); //uioutput.Show(); //uioutput.WindowState = FormWindowState.Maximized; //WordReport wr = new WordReport(ClientID: Utils.ClientID, ClientDocSetID: Utils.ClientSetID, // UIoutput: uioutput, // OverrideDocuments: overrideDocuments); //var fileName = wr.RegisterOfSytemDocuments(tvFileList, txtDestinationFolder.Text, wr.FullFileNamePath); //UIDocumentEdit uide = new UIDocumentEdit(fileName: wr.FileName, // fullPathFileName: wr.FullFileNamePath, // clientUID: Utils.ClientID); //uide.Show(); } private void showFullPathToolStripMenuItem_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; UpdateDocumentLocation(); Cursor.Current = Cursors.Arrow; } /// <summary> /// Update document location /// </summary> private void UpdateDocumentLocation() { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast var pathResult = BUSClientDocumentGeneration.UpdateLocation(rm.clientDocument.FKClientUID, rm.clientDocument.FKClientDocumentSetUID); string path = pathResult.Contents.ToString(); MessageBox.Show(path); } private void editDocumentToolStripMenuItem_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast Utils.OpenDocument( rm.clientDocument.Location, rm.clientDocument.FileName, rm.clientDocument.DocumentType, vkReadOnly: false); } /// <summary> /// Retrieve values from cache /// </summary> private void GetValuesFromCache() { // Get screen values from cache // #region ClientDocumentList // ---------------------------------------- // Get font size for client document list // ---------------------------------------- var userSettingsCache = new UserSettings(); userSettingsCache.FKUserID = Utils.UserID; userSettingsCache.FKScreenCode = ScreenCode; userSettingsCache.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentList; userSettingsCache.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; var stringValue = Utils.UserSettingGetCacheValue(userSettingsCache); if (string.IsNullOrEmpty(stringValue)) stringValue = "8.25"; // Convert to float tvClientDocumentListFontSize = float.Parse(stringValue); tvFileList.Font = new System.Drawing.Font("Microsoft Sans Serif", tvClientDocumentListFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // ---------------------------------------- // ---------------------------------------- // Get icon size for client document list // ---------------------------------------- userSettingsCache.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; var stringIconSize = Utils.UserSettingGetCacheValue(userSettingsCache); if (string.IsNullOrEmpty(stringIconSize)) stringIconSize = "16"; if (stringIconSize == "16") tvFileList.ImageList = imageList; if (stringIconSize == "32") tvFileList.ImageList = imageList32; #endregion ClientDocumentList #region Available Documents // ---------------------------------------- // Get font size for Available Documents List // ---------------------------------------- var userSettingsCacheAD = new UserSettings(); userSettingsCacheAD.FKUserID = Utils.UserID; userSettingsCacheAD.FKScreenCode = ScreenCode; userSettingsCacheAD.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentListDocSet; userSettingsCacheAD.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; var stringValueAD = Utils.UserSettingGetCacheValue(userSettingsCacheAD); if (string.IsNullOrEmpty(stringValueAD)) stringValueAD = "8.25"; // Convert to float tvClientDocumentListADFontSize = float.Parse(stringValueAD); tvDocumentsAvailable.Font = new System.Drawing.Font("Microsoft Sans Serif", tvClientDocumentListADFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // ---------------------------------------- // ---------------------------------------- // Get icon size for client document list // ---------------------------------------- userSettingsCacheAD.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; var stringADIconSize = Utils.UserSettingGetCacheValue(userSettingsCacheAD); if (string.IsNullOrEmpty(stringADIconSize)) stringADIconSize = "16"; if (stringADIconSize == "16") tvDocumentsAvailable.ImageList = imageList; if (stringADIconSize == "32") tvDocumentsAvailable.ImageList = imageList32; #endregion Available Documents } //-------------------------------------------------------------------- // // ICON and FONT sizes // //-------------------------------------------------------------------- /// <summary> /// Update font size for AVAILABLE DOCUMENTS /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tsmTVAvailableDocumentsListFontSizeSet(object sender, EventArgs e) { float size = 8.25F; ToolStripMenuItem b = (ToolStripMenuItem)sender; switch (b.Name) { case "tsmDocSetFontSize825": size = 8.25F; break; case "tsmDocSetFontSize12": size = 12F; break; case "tsmDocSetFontSize14": size = 14F; break; } tvDocumentsAvailable.Font = new System.Drawing.Font("Microsoft Sans Serif", size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // Save setting (Font Size to 8.25) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentListDocSet; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; userSetting.Value = size.ToString(); BUSUserSetting.Save(userSetting); } /// <summary> /// Set icon size for AVAILABLE DOCUMENTS /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tsmTVAvailableDocumentsListIconSizeSet(object sender, EventArgs e) { var userSetting = new UserSettings(); userSetting.Value = "16"; ToolStripMenuItem b = (ToolStripMenuItem)sender; switch (b.Name) { case "tsmDocumentSetVIewIconSize16": tvDocumentsAvailable.ImageList = imageList; tvDocumentsAvailable.Refresh(); userSetting.Value = "16"; break; case "tsmDocumentSetVIewIconSize32": tvDocumentsAvailable.ImageList = imageList32; tvDocumentsAvailable.Refresh(); userSetting.Value = "32"; break; } // Save setting // userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentListDocSet; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; BUSUserSetting.Save(userSetting); } /// <summary> /// Update font size for client document list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tsmTVFileListFontSizeSet_Click(object sender, EventArgs e) { float size = 8.25F; ToolStripMenuItem b = (ToolStripMenuItem)sender; switch (b.Name) { case "tsmFontSize825": size = 8.25F; break; case "tsmFontSize12": size = 12F; break; case "tsmFontSize14": size = 14F; break; } tvFileList.Font = new System.Drawing.Font("Microsoft Sans Serif", size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // Save setting (Font Size to 8.25) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; userSetting.Value = size.ToString(); BUSUserSetting.Save(userSetting); } /// <summary> /// Set icon size for File List Tree View /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tsmTVFileListIconSizeSet(object sender, EventArgs e) { var userSetting = new UserSettings(); userSetting.Value = "16"; ToolStripMenuItem b = (ToolStripMenuItem)sender; switch (b.Name) { case "x16DefaultToolStripMenuItem": tvFileList.ImageList = imageList; tvFileList.Refresh(); userSetting.Value = "16"; break; case "x32ToolStripMenuItem": tvFileList.ImageList = imageList32; tvFileList.Refresh(); userSetting.Value = "32"; break; } // Save setting // userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; BUSUserSetting.Save(userSetting); } private void menuItemGenerateDocBackground_Click(object sender, EventArgs e) { GenerateDocument("BACKGROUND"); } private void viewClientDocumentRecordToolStripMenuItem_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast UIClientDocumentEdit uicd = new UIClientDocumentEdit(rm.clientDocument); uicd.ShowDialog(); } private void tsEditClientDocument_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast Utils.OpenDocument( rm.clientDocument.Location, rm.clientDocument.FileName, rm.clientDocument.DocumentType, vkReadOnly: false); } private void tsViewSourceDocument_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (docSelected == null) return; rm = (scClientDocSetDocLink)docSelected.Tag; // Cast // Show Document Screen // UIDocumentEdit uide = new UIDocumentEdit(this, rm.document, docSelected); uide.ShowDialog(); } /// <summary> /// Check if source/ destination file exists /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tvFileList_Click(object sender, EventArgs e) { // Turn the source file on if the source file exists, also, turn the client destination file on // // // // Get selected document from tree // //TreeNode docSelected = tvFileList.SelectedNode; //var docItem = new scClientDocSetDocLink(); //if (docSelected == null) // return; //docItem = (scClientDocSetDocLink)docSelected.Tag; // Cast //bool CheckForSourceFile = true; //bool CheckForDestinationFile = true; //if (CheckForSourceFile) //{ // // SOURCE FILE is present? // // // docItem.clientDocument.SourceFilePresent = 'N'; // if (string.IsNullOrEmpty(docItem.clientDocument.SourceLocation)) // { // docItem.clientDocument.SourceFilePresent = 'N'; // } // else // { // string filePathName = Utils.getFilePathName(docItem.clientDocument.SourceLocation, // docItem.clientDocument.SourceFileName); // // This is the source client file name // // // string clientSourceFileLocationName = Utils.getFilePathName( // docItem.clientDocument.SourceLocation.Trim(), // docItem.clientDocument.SourceFileName.Trim()); // if (File.Exists(clientSourceFileLocationName)) // { // docItem.clientDocument.SourceFilePresent = 'Y'; // } // } //} //if (CheckForDestinationFile) //{ // // DESTINATION FILE is present? // // // docItem.clientDocument.DestinationFilePresent = 'N'; // if (string.IsNullOrEmpty(docItem.clientDocument.Location)) // { // docItem.clientDocument.DestinationFilePresent = 'N'; // } // else // { // string filePathName = Utils.getFilePathName(docItem.clientDocument.Location, // docItem.clientDocument.FileName); // // This is the destination client file name // // // string clientDestinationFileLocationName = Utils.getFilePathName( // docItem.clientDocument.Location.Trim(), // docItem.clientDocument.FileName.Trim()); // if (File.Exists(clientDestinationFileLocationName)) // { // docItem.clientDocument.DestinationFilePresent = 'Y'; // } // } //} //int image = Utils.GetFileImage(docItem.clientDocument.SourceFilePresent, docItem.clientDocument.DestinationFilePresent, docItem.clientDocument.DocumentType); //docSelected.ImageIndex = image; } private void addNewDocumentToolStripMenuItem_Click( object sender, EventArgs e ) { // Get selected document and add to the client set // This client document will not be related to a Document // var file = openFileDialog1.ShowDialog(); // Set the name of the client document // string filenameext = openFileDialog1.SafeFileName; var parts = filenameext.Split( '.' ); string filenameonly = parts[0]; string filenamefinal = "CLA" + "-00-" + Utils.ClientID.ToString( "0000" ) + "-00" + " " + filenameonly; ClientDocument clientDocument = new ClientDocument(); clientDocument.IsLocked = 'Y'; clientDocument.IsChecked = false; clientDocument.IsRoot = 'N'; clientDocument.FileName = filenameext; clientDocument.ClientIssueNumber = 0; clientDocument.DocumentCUID = ""; // It is not related to a document. It is client specific. clientDocument.DocumentType = "WORD"; // Add condition, it could be EXCEL, FOLDER, // Add document to tree // Wait for save action to save the document // Make sure the Document UID is not mandatory when saving the client document // This can cause problems in some specific file retrieves, in case of joins, // which I think it happens // Should I force the document to be added initially to the document list? // Maybe not because it will force unique number CLA-01, CLA-02 etc // } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIDocument : Form { public UIDocument() { InitializeComponent(); } private void UIDocumentSett_Load(object sender, EventArgs e) { //loadDocumentList(); //// Template Set //CodeValueList propTypeList = new CodeValueList(); //propTypeList.ListInCombo(true, "TEMPSET", cbxTemplateSet); //cbxTemplateSet.SelectedIndex = 0; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.ReferenceData { public class RelatedCode { public string RelatedCodeID { get; set; } public string Description { get; set; } public string FKCodeTypeFrom { get; set; } public string FKCodeTypeTo { get; set; } public void Add() { string ret = "Item updated successfully"; int _uid = 0; DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO rdRelatedCode " + "(RelatedCodeID, Description, FKCodeTypeFrom, FKCodeTypeTo" + ")" + " VALUES " + "( " + " @RelatedCodeID " + ", @Description " + ", @FKCodeTypeFrom " + ", @FKCodeTypeTo " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@RelatedCodeID", MySqlDbType.VarChar).Value = RelatedCodeID; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@FKCodeTypeFrom", MySqlDbType.VarChar).Value = FKCodeTypeFrom; command.Parameters.Add("@FKCodeTypeTo", MySqlDbType.VarChar).Value = FKCodeTypeTo; connection.Open(); command.ExecuteNonQuery(); } } return; } public static List<RelatedCode> List() { List<RelatedCode> listRelcode = new List<RelatedCode>(); try { using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " RelatedCodeID " + " ,Description " + " ,FKCodeTypeFrom " + " ,FKCodeTypeTo " + " FROM rdRelatedCode "); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { RelatedCode _codeType = new RelatedCode(); _codeType.RelatedCodeID = reader["RelatedCodeID"].ToString(); _codeType.Description = reader["Description"].ToString(); _codeType.FKCodeTypeFrom = reader["FKCodeTypeFrom"].ToString(); _codeType.FKCodeTypeTo = reader["FKCodeTypeTo"].ToString(); listRelcode.Add(_codeType); } } } } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Related Code List Error: " + ex.ToString(), Helper.Utils.UserID, "RelatedCode.cs"); } return listRelcode; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using ServiceStack.Redis; using ServiceStack.Redis.Generic; namespace MackkadoITFramework.ReferenceData { public class CodeType { [Display(Name = "Code Type")] [Required(AllowEmptyStrings = false, ErrorMessage = "Code Type must be supplied.")] [StringLength(20, MinimumLength = 4, ErrorMessage = "Code Type must be between 4 and 20 characters")] public string Code { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Description must be supplied.")] [Display(Name = "Description")] [StringLength(50, MinimumLength = 4)] public string Description { get; set; } [Display(Name = "ShortCodeType")] [StringLength(3, MinimumLength = 3)] public string ShortCodeType { get; set; } public List<CodeType> codeTypeList; private HeaderInfo _headerInfo; /// <summary> /// Add code type /// </summary> public ResponseStatus Add() { // ConnString.ConnectionStringFramework // ConnString.ConnectionStringFramework using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO rdCodeType " + "(CodeType, Description, ShortCodeType" + ")" + " VALUES " + "( " + " @CodeType " + ", @Description " + ", @ShortCodeType " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.AddWithValue("@CodeType", Code); command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@ShortCodeType", MySqlDbType.VarChar).Value = ShortCodeType; connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus(); } public ResponseStatus Read() { using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT CodeType " + " ,Description " + " ,ShortCodeType " + " FROM rdCodeType" + " WHERE CodeType = '{0}' ", Code); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { Code = reader["CodeType"].ToString(); Description = reader["Description"].ToString(); ShortCodeType = reader["ShortCodeType"].ToString(); } catch (Exception ex) { Description = ex.ToString(); } } } } return new ResponseStatus(); } public ResponseStatus Update() { var ret = new ResponseStatus {Message = "Item updated successfully"}; if (string.IsNullOrEmpty( Code )) { ret.ReturnCode = -0010; ret.ReasonCode = 0001; ret.Message = "Update Error - Code field not supplied."; return ret; } if (string.IsNullOrEmpty( Description )) { ret.ReturnCode = -0010; ret.ReasonCode = 0002; ret.Message = "Update Error - Description field not supplied."; return ret; } using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format ( "UPDATE rdCodeType " + "SET " + " Description = @Description " + " ,ShortCodeType = @ShortCodeType " + "WHERE " + " CodeType = @CodeType ", Description, Code ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@CodeType", MySqlDbType.VarChar).Value = Code; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@ShortCodeType", MySqlDbType.VarChar).Value = ShortCodeType; connection.Open(); command.ExecuteNonQuery(); } } return ret; } public void Delete() { if (Code == null) return; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = "DELETE FROM rdCodeType WHERE CodeType = @CodeType "; using (var command = new MySqlCommand( commandString, connection) ) { command.Parameters.Add("@CodeType", MySqlDbType.VarChar).Value = Code; connection.Open(); command.ExecuteNonQuery(); } } } public ResponseStatus List(HeaderInfo headerInfo) { codeTypeList = new List<CodeType>(); try { using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " CodeType " + " ,Description " + " FROM rdCodeType "); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { CodeType _codeType = new CodeType(); _codeType.Code = reader["CodeType"].ToString(); _codeType.Description = reader["Description"].ToString(); codeTypeList.Add(_codeType); } } } } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Error adding new document." + ex, headerInfo.UserID, "Document.cs" ); return new ResponseStatus(MessageType.Error) {Message = ex.ToString()}; } return new ResponseStatus(); } public struct CodeTypeValue { public const string ContractStatus = "CONTRACTSTATUS"; public const string ContractType = "CONTRACTTYPE"; public const string ProposalType = "PROPTYPE"; public const string ProposalStatus = "PROPSTATUS"; public const string ClientOtherField = "CLIENTOTHERFIELD"; } /// <summary> /// List Code Types /// </summary> public ResponseStatus List( List<CodeType> ctList ) { try { using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " CodeType " + " ,Description " + " FROM rdCodeType "); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _codeType = new CodeType(); _codeType.Code = reader["CodeType"].ToString(); _codeType.Description = reader["Description"].ToString(); // Instance Variable codeTypeList.Add(_codeType); // Input variable ctList.Add(_codeType); } } } } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Error adding new document." + ex, "", "CodeType.cs" ); return new ResponseStatus(MessageType.Error) {ReturnCode = -0020, ReasonCode = 0001, Message = ex.ToString()}; } return new ResponseStatus(); } public void Redis_StoreCodeTypes() { List<CodeType> list; list = new List<CodeType>(); this.codeTypeList = new List<CodeType>(); this.List(list); string host = "172.16.0.17"; using (RedisClient redisClient = new RedisClient(host)) { foreach (var codetype in list) { // store code type IRedisTypedClient<CodeType> codetypes = redisClient.As<CodeType>(); redisClient.ChangeDb(0); codetypes.SetEntryIfNotExists(codetype.Code, codetype); CodeValue cv = new CodeValue(); ResponseStatus rs = cv.List(codetype.Code); foreach (var codevalue in cv.codeValueList) { // store values IRedisTypedClient<CodeValue> codevalues = redisClient.As<CodeValue>(); redisClient.ChangeDb(1); codevalues.SetEntryIfNotExists(codevalue.FKCodeType+codevalue.ID, codevalue); } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; using FCMMySQLBusinessLibrary.Repository; using MackkadoITFramework.Utils; namespace fcm.Windows { public partial class UIClientContract : Form { private List<ClientContract> clientContractList { set; get; } private ClientContract clientContract { set; get; } private Client client; private Form _comingFromForm; public UIClientContract(Form comingFromForm, Client iclient) { InitializeComponent(); _comingFromForm = comingFromForm; client = iclient; txtContractID.Enabled = false; txtContractID.ReadOnly = true; txtClientName.Text = client.UID + " " + client.Name; clientContractList = new List<ClientContract>(); clientContract = new ClientContract(); } private void UIClientContract_Load(object sender, EventArgs e) { ListClientContract(); var contractStatus = new CodeValue(); contractStatus.ListInCombo(CodeType.CodeTypeValue.ContractStatus, comboBoxContractStatus); var contractType = new CodeValue(); contractType.ListInCombo(CodeType.CodeTypeValue.ContractType, comboBoxContractType); } /// <summary> /// List client contract /// </summary> private void ListClientContract() { var response = BUSClientContract.ClientContractList(Utils.ClientID); clientContractList = (List<ClientContract>)response.Contents; try { clientContractBindingSource.DataSource = clientContractList; } catch (Exception ex) { MessageBox.Show("P2 " + ex.ToString()); } return; } /// <summary> /// Reset screen from IClientContract /// </summary> public void ResetScreen() { // not implemented } /// <summary> /// Display message on client /// </summary> /// <param name="msg"></param> public void DisplayMessage(string msg) { MessageBox.Show(msg); return; } private void btnNew_Click(object sender, EventArgs e) { txtContractID.Text = ""; txtExternalID.Text = ""; dtpStartDate.Text = System.DateTime.Today.ToString( "yyyyMMdd" ); dtpEndDate.Text = System.DateTime.Now.AddDays(365).ToString(); dtpStartDate.Focus(); } private void btnSave_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; if (string.IsNullOrEmpty( txtContractID.Text )) { clientContract.UID = 0; clientContract.CreationDateTime = System.DateTime.Now; clientContract.UserIdCreatedBy = Utils.UserID; } else { clientContract.UID = Convert.ToInt32(txtContractID.Text); // clientContract.CreationDateTime = Convert.ToDateTime( txtCreationDate.Text ); // Compare fields if ( clientContract.ExternalID == txtExternalID.Text && clientContract.StartDate == dtpStartDate.Value && clientContract.EndDate == dtpEndDate.Value && clientContract.Type == comboBoxContractType.Text && clientContract.Status == comboBoxContractStatus.Text ) { MessageBox.Show("Data has not been updated."); return; } } // Fill in current data. // if (clientContract.UID > 0) { var boxedClientContract = BUSClientContract.Read(clientContract.UID); clientContract = (ClientContract) boxedClientContract.Contents; } clientContract.FKCompanyUID = Utils.ClientID; clientContract.ExternalID = txtExternalID.Text; clientContract.StartDate = dtpStartDate.Value; clientContract.EndDate = dtpEndDate.Value; clientContract.Type = comboBoxContractType.Text; clientContract.Status = comboBoxContractStatus.Text; clientContract.UpdateDateTime = System.DateTime.Now; clientContract.UserIdUpdatedBy = Utils.UserID; if (clientContract.UID == 0) { ClientContractAddRequest clientContractAddRequest = new ClientContractAddRequest(); clientContractAddRequest.clientContract = clientContract; clientContractAddRequest.headerInfo = HeaderInfo.Instance; var response = new BUSClientContract().ClientContractAdd(clientContractAddRequest); MessageBox.Show(response.responseStatus.Message); } else { ClientContractUpdateRequest clientContractUpdateRequest = new ClientContractUpdateRequest(); clientContractUpdateRequest.clientContract = clientContract; clientContractUpdateRequest.headerInfo = HeaderInfo.Instance; var response = new BUSClientContract().ClientContractUpdate(clientContractUpdateRequest); MessageBox.Show(response.responseStatus.Message); } Cursor.Current = Cursors.Arrow; ListClientContract(); } private void dgvClientContract_SelectionChanged(object sender, EventArgs e) { SetScreenFieldsFromObject(clientContract); } private void SetScreenFieldsFromObject(ClientContract clientContract) { if (dgvClientContract.SelectedRows.Count <= 0) return; var selectedRow = dgvClientContract.SelectedRows; txtContractID.Text = selectedRow[0].Cells[FCMDBFieldName.ClientContract.UID].Value.ToString(); txtExternalID.Text = selectedRow[0].Cells[FCMDBFieldName.ClientContract.ExternalID].Value.ToString(); dtpStartDate.Value = Convert.ToDateTime(selectedRow[0].Cells[FCMDBFieldName.ClientContract.StartDate].Value); dtpEndDate.Value = Convert.ToDateTime(selectedRow[0].Cells[FCMDBFieldName.ClientContract.EndDate].Value); comboBoxContractType.Text = selectedRow[0].Cells[FCMDBFieldName.ClientContract.Type].Value.ToString(); comboBoxContractStatus.Text = selectedRow[0].Cells[FCMDBFieldName.ClientContract.Status].Value.ToString(); //txtCreationDate.Text = selectedRow[0].Cells[ClientContract.FieldName.CreationDateTime].Value.ToString(); //txtUpdatedDate.Text = selectedRow[0].Cells[ClientContract.FieldName.UpdateDateTime].Value.ToString(); //txtCreatedBy.Text = selectedRow[0].Cells[ClientContract.FieldName.UserIdCreatedBy].Value.ToString(); //txtUpdatedBy.Text = selectedRow[0].Cells[ClientContract.FieldName.UserIdUpdatedBy].Value.ToString(); // Load current object // LoadObjectFromUIFields(); } private void txtCancel_Click(object sender, EventArgs e) { _comingFromForm.Activate(); this.Dispose(); } /// <summary> /// Load object from UI fields /// </summary> private void LoadObjectFromUIFields() { clientContract.FKCompanyUID = Utils.ClientID; clientContract.UID = Convert.ToInt32(txtContractID.Text); clientContract.ExternalID = txtExternalID.Text; clientContract.StartDate = dtpStartDate.Value; clientContract.EndDate = dtpEndDate.Value; clientContract.Type = comboBoxContractType.Text; clientContract.Status = comboBoxContractStatus.Text; //clientContract.UpdateDateTime = Convert.ToDateTime(txtUpdatedDate.Text); //clientContract.UserIdUpdatedBy = txtUpdatedBy.Text; //clientContract.CreationDateTime = Convert.ToDateTime(txtCreationDate.Text); // clientContract.UserIdCreatedBy = txtCreatedBy.Text; } private void btnDelete_Click(object sender, EventArgs e) { ClientContractDeleteRequest clientContractDeleteRequest = new ClientContractDeleteRequest(); clientContractDeleteRequest.clientContract = clientContract; clientContractDeleteRequest.headerInfo = HeaderInfo.Instance; var response = BUSClientContract.ClientContractDelete(clientContractDeleteRequest); MessageBox.Show(response.responseStatus.Message); ListClientContract(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { _comingFromForm.Activate(); this.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelMetadata { public class ReportMetadataList { public List<ReportMetadata> reportMetadataList; private int _clientUID; // ----------------------------------------------------- // Constructor using userId and connection string // ----------------------------------------------------- public ReportMetadataList() { } // ----------------------------------------------------- // List Global Fields // ----------------------------------------------------- public void ListDefault() { this.reportMetadataList = new List<ReportMetadata>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,Description " + " ,RecordType " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ,UseAsLabel " + " FROM ReportMetadata " + " WHERE RecordType = '{0}'", "DF"); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ReportMetadata _reportMetadata = new ReportMetadata(); _reportMetadata.UID = Convert.ToInt32(reader["UID"].ToString()); _reportMetadata.Description = reader["Description"].ToString(); _reportMetadata.RecordType = reader["RecordType"].ToString(); _reportMetadata.FieldCode = reader["FieldCode"].ToString(); _reportMetadata.ClientType = reader["ClientType"].ToString(); _reportMetadata.Condition = reader["ConditionX"].ToString(); _reportMetadata.CompareWith = reader["CompareWith"].ToString(); _reportMetadata.Enabled = Convert.ToChar(reader["Enabled"]); try { _reportMetadata.UseAsLabel = Convert.ToChar(reader["UseAsLabel"]); } catch (Exception ex) { _reportMetadata.UseAsLabel = 'N'; } try { _reportMetadata.ClientUID = Convert.ToInt32(reader["ClientUID"]); } catch (Exception ex) { _reportMetadata.ClientUID = 0; } _reportMetadata.InformationType = reader["InformationType"].ToString(); this.reportMetadataList.Add(_reportMetadata); } } } } } // ----------------------------------------------------- // List available report metadata // ----------------------------------------------------- public void ListAvailableForClient(int clientUID) { this.reportMetadataList = new List<ReportMetadata>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,Description " + " ,RecordType " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " FROM ReportMetadata " + " WHERE RecordType = 'DF' " + " AND FieldCode not in " + " ( select FieldCode from reportmetadata where ClientUID = {0}) ", clientUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ReportMetadata _reportMetadata = new ReportMetadata(); _reportMetadata.UID = Convert.ToInt32(reader["UID"].ToString()); _reportMetadata.Description = reader["Description"].ToString(); _reportMetadata.RecordType = reader["RecordType"].ToString(); _reportMetadata.FieldCode = reader["FieldCode"].ToString(); _reportMetadata.ClientType = reader["ClientType"].ToString(); try { _reportMetadata.ClientUID = Convert.ToInt32(reader["ClientUID"]); } catch (Exception ex) { _reportMetadata.ClientUID = 0; } _reportMetadata.InformationType = reader["InformationType"].ToString(); _reportMetadata.Condition = reader["ConditionX"].ToString(); _reportMetadata.CompareWith = reader["CompareWith"].ToString(); this.reportMetadataList.Add(_reportMetadata); } } } } } // ----------------------------------------------------- // List metadata for a given client // ----------------------------------------------------- public void ListMetadataForClient(int clientUID, bool onlyEnabled = false) { this.reportMetadataList = new List<ReportMetadata>(); var enabledOnlyCriteria = ""; if (onlyEnabled) { enabledOnlyCriteria = " AND Enabled = 'Y' "; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,Description " + " ,RecordType " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " FROM ReportMetadata " + " WHERE RecordType = 'CL' " + enabledOnlyCriteria + " AND ClientUID = {0} ", clientUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ReportMetadata _reportMetadata = new ReportMetadata(); _reportMetadata.UID = Convert.ToInt32(reader["UID"].ToString()); _reportMetadata.Description = reader["Description"].ToString(); _reportMetadata.RecordType = reader["RecordType"].ToString(); _reportMetadata.FieldCode = reader["FieldCode"].ToString(); _reportMetadata.ClientType = reader["ClientType"].ToString(); _reportMetadata.InformationType = reader["InformationType"].ToString(); _reportMetadata.Enabled = Convert.ToChar(reader["Enabled"]); try { _reportMetadata.ClientUID = Convert.ToInt32(reader["ClientUID"]); } catch (Exception ex) { _reportMetadata.ClientUID = 0; } _reportMetadata.InformationType = reader["InformationType"].ToString(); _reportMetadata.Condition = reader["ConditionX"].ToString(); _reportMetadata.CompareWith = reader["CompareWith"].ToString(); this.reportMetadataList.Add(_reportMetadata); } } } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIProposal : Form { public DataTable elementSourceDataTable; public UIProposal() { InitializeComponent(); // _connectionString = connectionString; // // Create datatable // var CUID = new DataColumn("CUID", typeof(String)); var Name = new DataColumn("Name", typeof(String)); var Directory = new DataColumn("Directory", typeof(String)); var Subdirectory = new DataColumn("Subdirectory", typeof(String)); var SequenceNumber = new DataColumn("SequenceNumber", typeof(Int32)); var LatestIssueNumber = new DataColumn("LatestIssueNumber", typeof(String)); var LatestIssueLocation = new DataColumn("LatestIssueLocation", typeof(String)); var Comments = new DataColumn("Comments", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(CUID); elementSourceDataTable.Columns.Add(Name); elementSourceDataTable.Columns.Add(Directory); elementSourceDataTable.Columns.Add(Subdirectory); elementSourceDataTable.Columns.Add(SequenceNumber); elementSourceDataTable.Columns.Add(LatestIssueNumber); elementSourceDataTable.Columns.Add(LatestIssueLocation); dgvDocumentList.DataSource = elementSourceDataTable; } private void UIProposal_Load(object sender, EventArgs e) { loadDocumentList(); foreach (Client c in Utils.ClientList.clientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } cbxClient.SelectedIndex = Utils.ClientIndex; // Proposal Type CodeValueList propTypeList = new CodeValueList(); propTypeList.ListInCombo("PROPTYPE", cbxProposalType); // Status CodeValueList propStatusList = new CodeValueList(); propTypeList.ListInCombo("PROPSTATUS", cbxStatus); } // // List companies // private void loadDocumentList() { elementSourceDataTable.Clear(); var docoList = new DocumentList(); docoList.List(); foreach (Document doco in docoList.documentList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["CUID"] = doco.CUID; elementRow["Name"] = doco.Name; elementRow["Directory"] = doco.Directory; elementRow["Subdirectory"] = doco.Subdirectory; elementRow["SequenceNumber"] = doco.SequenceNumber; elementRow["LatestIssueNumber"] = doco.LatestIssueNumber; elementRow["LatestIssueLocation"] = doco.LatestIssueLocation; elementSourceDataTable.Rows.Add(elementRow); } } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { Utils.ClientID = Utils.ClientList.clientList[cbxClient.SelectedIndex].UID; Utils.ClientIndex = cbxClient.SelectedIndex; } private void removeToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var selRows in dgvDocumentList.SelectedRows) { dgvDocumentList.Rows.Remove((DataGridViewRow)selRows); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Security.Cryptography; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.Security { public class UserAccess { #region Properties [Required( ErrorMessage = "User ID is mandatory. You can use your email address." )] [Display( Name = "Enter User ID" )] public string UserID { get { return _UserID; } set { _UserID = value; } } [Display( Name = "Enter Name" )] public string UserName { get { return _UserName; } set { _UserName = value; } } public int LogonAttempts { get { return _LogonAttempts; } set { _LogonAttempts = value; } } [Required( ErrorMessage = "Password is required." )] [Display( Name = "Enter Password" )] public string Password { set { _Password = value; } get { return _Password; } } public int ClientUID { set { _ClientUID = value; } get { return _ClientUID; } } [Display( Name = "Re-enter Password" )] public string PasswordRetype { get; set; } public string ConfirmPassword { get; set; } public string Salt { set { _Salt = value; } get { return _Salt; } } public List<UserAccess> ListOfUsers; #endregion Properties #region Attributes private string _UserID; private int _ClientUID; private string _UserName; private string _Password; private string _EncryptedPassword; private string _Salt; private int _LogonAttempts; #endregion Attributes #region FieldName public struct FieldName { public const string UserID = "UserID"; public const string Password = "<PASSWORD>"; public const string Salt = "Salt"; public const string UserName = "UserName"; public const string LogonAttempts = "LogonAttempts"; } #endregion FieldName public UserAccess() { } /// <summary> /// List user users /// </summary> /// <returns></returns> public static List<UserAccess> List(string xConnectionStringUsed = null) { if (string.IsNullOrEmpty(xConnectionStringUsed)) { if (string.IsNullOrEmpty(ConnString.ConnectionStringFramework)) { return null; } xConnectionStringUsed = ConnString.ConnectionStringFramework; } List<UserAccess> userAccessList = new List<UserAccess>(); using (var connection = new MySqlConnection(xConnectionStringUsed)) { var commandString = string.Format( " SELECT " + SQLConcat() + " FROM SecurityUser " + " ORDER BY UserID ASC " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var docItem = SetDocumentItem(reader); // Check if document exists // userAccessList.Add(docItem); } } } } return userAccessList; } /// <summary> /// List user users /// </summary> /// <returns></returns> public ResponseStatus ListUsers() { ListOfUsers = new List<UserAccess>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + SQLConcat() + " FROM SecurityUser " + " ORDER BY UserID ASC " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var docItem = SetDocumentItem(reader); // Check if document exists // ListOfUsers.Add(docItem); } } } } return new ResponseStatus(); } public bool IsUserAllowed() { return false; } public ResponseStatus Read(string userID) { var ret = new ResponseStatus(); // // EA SQL database // using (var connection = new MySqlConnection( ConnString.ConnectionStringFramework )) { // TODO // SqlParameter useId = new var commandString = string.Format( " SELECT UserID " + " ,UserName " + " ,Password " + " ,Salt " + " ,LogonAttempts " + " FROM SecurityUser" + " WHERE UserID = '{0}' ", userID ); using (var command = new MySqlCommand( commandString, connection )) { try { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { _UserID = reader["UserID"].ToString(); _UserName = reader["UserName"].ToString(); _Password = reader["Password"].ToString(); _Salt = reader["Salt"].ToString(); _LogonAttempts = Convert.ToInt32(reader["LogonAttempts"]); //var client = new Client.Client(HeaderInfo.Instance); //client.FKUserID = _UserID; //client.ReadLinkedUser(); //_ClientUID = client.UID; // ret.ReturnCode = 0001; ret.ReasonCode = 0001; ret.Message = "Record found."; return ret; } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "GetCodeValueExtended error retrieving extended value. " + ex, programName: "ProcessRequestCodeValues.cs" ); return new ResponseStatus(MessageType.Error) {Message = ex.ToString()}; } } } ret.ReturnCode = 0001; ret.ReasonCode = 0002; ret.Message = "Record not found."; return ret; } public ResponseStatus AuthenticateUser(string userID, string inputPassword) { var UserDB = new UserAccess(); var readuser = UserDB.Read(userID); if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0001) { // Ok } if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0002) { return new ResponseStatus(MessageType.Error) {Message = "Credentials are not correct."}; } if (readuser.ReturnCode <= 0000 ) { return readuser; } if (UserDB.LogonAttempts > 4) { return new ResponseStatus(MessageType.Error) { Message = "User locked due to logon attempts. Please contact system support." }; } if (string.IsNullOrWhiteSpace( inputPassword )) { return new ResponseStatus(MessageType.Error) { Message = "Credentials are not correct. Spaces or Nulls." }; } string passValue = EncryptX( UserDB.Salt, inputPassword ); if (UserDB.Password == passValue) { // // Logon successfull // UpdateLogonAttempts( "reset" ); return new ResponseStatus(); } UpdateLogonAttempts( "add" ); return new ResponseStatus(MessageType.Error) { Message = "Credentials are not correct. Spaces or Nulls." }; } public void test() { String s; // s.GetHashCode(); binary 20 posicoes // Daniel - back here } public string EncryptX( string salt, string password ) { int result = 0; // int salt = System.DateTime.Now.Hour; List <int> passwordChar = new List<int>(); int desc = password.Length; double finalResult = 0.00; foreach (char c in password) { int value = Convert.ToInt32( c ); passwordChar.Add( value ); finalResult += Math.Sqrt( Convert.ToDouble( value * desc ) ); desc--; } return Convert.ToInt32( finalResult ).ToString(); } public string DecryptX( string salt, string password ) { string ret = ""; int result = 0; // int salt = System.DateTime.Now.Hour; List <int> passwordChar = new List<int>(); int desc = password.Length; double finalResult = 0.00; foreach( char c in password) { int value = Convert.ToInt32( c ) ; passwordChar.Add( value ); finalResult += Math.Sqrt( Convert.ToDouble( value * finalResult ) ); } result = Convert.ToInt32( finalResult ); ret = Password; return ret; } public ResponseStatus AddUser() { ResponseStatus response = new ResponseStatus(); response.Message = "User Added Successfully."; response.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000004; int _uid = 0; DateTime _now = DateTime.Today; if (_UserID == null) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "User ID is mandatory."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000003; response.Contents = 0; return response; } if (_Salt == null) { response.ReturnCode = -0010; response.ReasonCode = 0003; response.Message = "Salt is mandatory."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000005; response.Contents = 0; return response; } _EncryptedPassword = EncryptX(_Salt, Password); using (var connection = new MySqlConnection( ConnString.ConnectionStringFramework )) { var commandString = ( "INSERT INTO SecurityUser " + "(UserID, UserName, LogonAttempts, Password, Salt" + ")" + " VALUES " + "( " + " @UserID " + ", @UserName " + ", @LogonAttempts " + ", @Password " + ", @Salt " + " )" ); using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add("@UserID", MySqlDbType.VarChar ).Value = _UserID; command.Parameters.Add("@UserName", MySqlDbType.VarChar ).Value = _UserName; command.Parameters.Add("@LogonAttempts", MySqlDbType.Int32).Value = 0; command.Parameters.Add("@Password", MySqlDbType.VarChar).Value = _EncryptedPassword; command.Parameters.Add("@Salt", MySqlDbType.Int32).Value = Salt; connection.Open(); command.ExecuteNonQuery(); } } return response; } public ResponseStatus UpdateUser() { ResponseStatus response = new ResponseStatus(); response.Message = "User Updated Successfully."; response.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000005; int _uid = 0; DateTime _now = DateTime.Today; if (_UserID == null) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "User ID is mandatory."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000003; response.Contents = 0; return response; } using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "UPDATE SecurityUser " + "SET UserName = @UserName " + "WHERE UserID = @UserID" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UserID", MySqlDbType.VarChar).Value = _UserID; command.Parameters.Add("@UserName", MySqlDbType.VarChar).Value = _UserName; connection.Open(); command.ExecuteNonQuery(); } } return response; } public ResponseStatus UpdatePassword() { ResponseStatus response = new ResponseStatus(); response.Message = "Password changed successfully."; response.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000005; // Encrypt password _EncryptedPassword = EncryptX(_Salt, Password); int _uid = 0; DateTime _now = DateTime.Today; if (_UserID == null) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "User ID is mandatory."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000003; response.Contents = 0; return response; } using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "UPDATE SecurityUser " + " SET Password = <PASSWORD>, LogonAttempts = @LogonAttempts " + " WHERE UserID = @UserID" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UserID", MySqlDbType.VarChar).Value = _UserID; command.Parameters.Add("@Password", MySqlDbType.VarChar).Value = _EncryptedPassword; command.Parameters.Add("@LogonAttempts", MySqlDbType.VarChar).Value = 0; connection.Open(); command.ExecuteNonQuery(); } } return response; } public ResponseStatus UpdateLogonAttempts(string action) { if (action == "reset") this.LogonAttempts = 0; else this.LogonAttempts++; if (_UserID == null) return new ResponseStatus(MessageType.Error); using (var connection = new MySqlConnection( ConnString.ConnectionStringFramework )) { var commandString = ( "UPDATE SecurityUser SET LogonAttempts = @LogonAttempts " + "WHERE UserID = @UserID" ); using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add( "@UserID", MySqlDbType.VarChar ).Value = _UserID; command.Parameters.Add( "@LogonAttempts", MySqlDbType.Int32 ).Value = _LogonAttempts; connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus(); } // Encrypt a byte array into a byte array using a key and an IV public static byte[] Encrypt( byte[] clearData, byte[] Key, byte[] IV ) { // Create a MemoryStream to accept the encrypted bytes MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream( ms, alg.CreateEncryptor(), CryptoStreamMode.Write ); cs.Write( clearData, 0, clearData.Length ); cs.Close(); byte[] encryptedData = ms.ToArray(); return encryptedData; } // Encrypt a string into a string using a password // Uses Encrypt(byte[], byte[], byte[]) public static string Encrypt( string clearText, string Password ) { // First we need to turn the input string into a byte array. byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes( clearText ); PasswordDeriveBytes pdb = new PasswordDeriveBytes( Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76} ); byte[] encryptedData = Encrypt( clearBytes, pdb.GetBytes( 32 ), pdb.GetBytes( 16 ) ); return Convert.ToBase64String( encryptedData ); } // Encrypt bytes into bytes using a password // Uses Encrypt(byte[], byte[], byte[]) public static byte[] Encrypt( byte[] clearData, string Password ) { PasswordDeriveBytes pdb = new PasswordDeriveBytes( Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76} ); return Encrypt( clearData, pdb.GetBytes( 32 ), pdb.GetBytes( 16 ) ); } // Decrypt a byte array into a byte array using a key and an IV public static byte[] Decrypt( byte[] cipherData, byte[] Key, byte[] IV ) { MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = IV; CryptoStream cs = new CryptoStream( ms, alg.CreateDecryptor(), CryptoStreamMode.Write ); // Write the data and make it do the decryption cs.Write( cipherData, 0, cipherData.Length ); cs.Close(); byte[] decryptedData = ms.ToArray(); return decryptedData; } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> private static string SQLConcat() { string ret = " " + FieldName.UserID + "," + FieldName.UserName + ", " + FieldName.Password + ", " + FieldName.Salt + ", " + FieldName.LogonAttempts + " "; return ret; } /// <summary> /// Set user setting values /// </summary> /// <param name="reader"></param> /// <param name="prefix"></param> /// <returns></returns> private static UserAccess SetDocumentItem(MySqlDataReader reader) { var user = new UserAccess(); user.UserID = reader[FieldName.UserID].ToString(); user.UserName = reader[FieldName.UserName].ToString(); user.Salt = reader[FieldName.Salt].ToString(); user.LogonAttempts = Convert.ToInt32(reader[FieldName.LogonAttempts].ToString()); user.Password = reader[FieldName.Password].ToString(); return user; } } } <file_sep>using System.Collections.Generic; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract { public class ClientListResponse { public List<Client> clientList; public ResponseStatus response; } public class ClientUpdateRequest { public HeaderInfo headerInfo; public Client eventClient; } public class ClientUpdateResponse { public List<Client> clientList; public ResponseStatus response; } public class ClientAddRequest { public HeaderInfo headerInfo; public Client eventClient; public string linkInitialSet; } public class ClientAddResponse { public ResponseStatus responseStatus; public int clientUID; } public class ClientDeleteRequest { public HeaderInfo headerInfo; public int clientUID; } public class ClientDeleteResponse { public ResponseStatus responseStatus; public int clientUID; } public class ClientReadRequest { public HeaderInfo headerInfo; public int clientUID; } public class ClientReadResponse { public ResponseStatus responseStatus; public Client client; } public class ReadFieldResponse { public ResponseStatus responseStatus; public string fieldContents; } public class ReadFieldRequest { public HeaderInfo headerInfo; public string field; public int clientUID; } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using System.Windows.Forms; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentSetList { public List<DocumentSet> documentSetList; // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public void List() { this.documentSetList = new List<DocumentSet>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,TemplateType " + " ,TemplateFolder " + " ,IsVoid " + " FROM DocumentSet " + " WHERE IsVoid = 'N' " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { DocumentSet documentSet = new DocumentSet(); documentSet.UID = Convert.ToInt32(reader["UID"].ToString()); documentSet.TemplateType = reader["TemplateType"].ToString(); documentSet.TemplateFolder = reader["TemplateFolder"].ToString(); documentSet.IsVoid = Convert.ToChar(reader["IsVoid"].ToString()); documentSet.UIDNameDisplay = documentSet.UID.ToString() + "; " + documentSet.TemplateType; this.documentSetList.Add(documentSet); } } } } } public void ListInComboBox(ComboBox cbxList) { this.List(); foreach (DocumentSet docSet in documentSetList) { cbxList.Items.Add(docSet.UID + "; " + docSet.TemplateType); } } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Security; using MackkadoITFramework.Utils; using fcm.Windows.Cache; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; namespace fcm.Windows { public partial class UIUserAccess : Form { private TreeNode tndocSelected; private List<UserAccess> _ListOfUsers; ImageList imageList; ImageList imageList32; public string ScreenCode; float tvClientDocumentListFontSize; int tvClientDocumentListIconSize; /// <summary> /// Constructor /// </summary> public UIUserAccess() { InitializeComponent(); ScreenCode = FCMConstant.ScreenCode.UserAccess; } /// <summary> /// Load event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UIUserAccess_Load(object sender, EventArgs e) { // Image list // // 32 x 32 imageList32 = ControllerUtils.GetImageList(); imageList32.ImageSize = new Size(32, 32); // 16 x 16 imageList = ControllerUtils.GetImageList(); tvUserList.ImageList = imageList; tvAvailableRoles.ImageList = imageList; // Clear nodes tvUserList.Nodes.Clear(); tvAvailableRoles.Nodes.Clear(); RefreshList(); } /// <summary> /// Event Drag and Drop /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tvUserList_DragDrop(object sender, DragEventArgs e) { AddRoleToUser(sender, e); } /// <summary> /// Add role to user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddRoleToUser(object sender, DragEventArgs e) { // Get selected item in available tree // TreeNode tnRoleAvailableSelected = tvAvailableRoles.SelectedNode; if (tnRoleAvailableSelected == null) return; // Get destination node // if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvUserList.PointToClient(new Point(e.X, e.Y)); destinationNode = tvUserList.GetNodeAt(pt); if (destinationNode == null) return; var user = new UserAccess(); user = (UserAccess)destinationNode.Tag; if (tnRoleAvailableSelected != null) { tnRoleAvailableSelected.Remove(); destinationNode.Nodes.Add(tnRoleAvailableSelected); // Get role // SecurityRole roleNew = new SecurityRole(); roleNew = (SecurityRole)tnRoleAvailableSelected.Tag; // Update database // SecurityUserRole newUserRole = new SecurityUserRole(HeaderInfo.Instance); newUserRole.FK_Role = roleNew.Role; newUserRole.FK_UserID = user.UserID; newUserRole.IsActive = "Y"; newUserRole.IsVoid = "N"; newUserRole.StartDate = System.DateTime.Today; var response = newUserRole.Add(); // Show message ControllerUtils.ShowFCMMessage(response.UniqueCode, Utils.UserID); RefreshList(); } } } /// <summary> /// Add screen to role /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddScreenToRole(object sender, DragEventArgs e) { // Get selected item in available tree // TreeNode tnScreenAvailableSelected = tvScreenList.SelectedNode; if (tnScreenAvailableSelected == null) return; // Get destination node // if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvAvailableRoles.PointToClient(new Point(e.X, e.Y)); destinationNode = tvAvailableRoles.GetNodeAt(pt); if (destinationNode == null) return; var role = new SecurityRole(); role = (SecurityRole)destinationNode.Tag; if (tnScreenAvailableSelected != null) { tnScreenAvailableSelected.Remove(); destinationNode.Nodes.Add(tnScreenAvailableSelected); // Get scree // CodeValue roleNew = new CodeValue(); roleNew = (CodeValue)tnScreenAvailableSelected.Tag; // Update database // SecurityRoleScreen newRoleScreen = new SecurityRoleScreen(); newRoleScreen.FKRoleCode = role.Role; newRoleScreen.FKScreenCode = roleNew.ID; var response = BUSUserAccess.AddScreenToRole(newRoleScreen); // Show message ControllerUtils.ShowFCMMessage(response.UniqueCode, Utils.UserID); // RefreshList(); } } } private void tvUserList_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvUserList_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void tvAvailableRoles_DragDrop(object sender, DragEventArgs e) { // Get selected item in available tree // //TreeNode tnRoleAvailableSelected = tvAvailableRoles.SelectedNode; //if (tnRoleAvailableSelected == null) // return; AddScreenToRole(sender, e); } private void tvAvailableRoles_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvAvailableRoles_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void removeAccessToolStripMenuItem_Click(object sender, EventArgs e) { RemoveRoleFromUser(sender, e); } /// <summary> /// Remove role from user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveRoleFromUser(object sender, EventArgs e) { // Get selected item in available tree // TreeNode tnUserRoleSelected = tvUserList.SelectedNode; if (tnUserRoleSelected == null) return; if (tnUserRoleSelected.Tag.GetType().ToString() != "FCMMySQLBusinessLibrary.SecurityUserRole") return; // Get role // SecurityUserRole roleOld = new SecurityUserRole(HeaderInfo.Instance); roleOld = (SecurityUserRole )tnUserRoleSelected.Tag; // Update database // SecurityUserRole newUserRole = new SecurityUserRole(HeaderInfo.Instance); newUserRole.UniqueID = roleOld.UniqueID; newUserRole.FK_Role = roleOld.FK_Role; newUserRole.FK_UserID = roleOld.FK_UserID; var response = newUserRole.Delete(); Utils.RefreshCache(); // Show message ControllerUtils.ShowFCMMessage(response.UniqueCode, Utils.UserID); RefreshList(); } private void tsmExit_Click(object sender, EventArgs e) { this.Dispose(); } private void btnNew_Click(object sender, EventArgs e) { txtUserID.Text = ""; txtName.Text = ""; txtPassword.Text = ""; txtNewPassword.Text = ""; txtUserID.Focus(); } private void btnSave_Click(object sender, EventArgs e) { var uacnew = new UserAccess(); var readuser = uacnew.Read(txtUserID.Text); uacnew.UserID = txtUserID.Text; uacnew.UserName = txtName.Text; uacnew.Salt = System.DateTime.Now.Hour.ToString(); uacnew.Password = <PASSWORD>; var response = BUSUserAccess.Save(uacnew); ControllerUtils.ShowFCMMessage(response.UniqueCode, Utils.UserID); RefreshList(); } private void tvUserList_Click(object sender, EventArgs e) { } private void tvUserList_AfterSelect(object sender, TreeViewEventArgs e) { // Get selected item in available tree // TreeNode tnUserRoleSelected = tvUserList.SelectedNode; if (tnUserRoleSelected == null) return; // Get user // txtUserID.Text = ""; txtName.Text = ""; txtPassword.Text = ""; txtNewPassword.Text = ""; if (tnUserRoleSelected.Tag.GetType().ToString() == "FCMMySQLBusinessLibrary.UserAccess") { UserAccess user = new UserAccess(); user = (UserAccess)tnUserRoleSelected.Tag; txtUserID.Text = user.UserID; txtName.Text = user.UserName; } } private void btnResetPassword_Click(object sender, EventArgs e) { var uacnew = new UserAccess(); var readuser = uacnew.Read(txtUserID.Text); uacnew.UserID = txtUserID.Text; uacnew.Salt = System.DateTime.Now.Hour.ToString(); uacnew.Password = <PASSWORD>.Text; if (txtPassword.Text != txtNewPassword.Text) { MessageBox.Show("Passwords do not match."); return; } var response = BUSUserAccess.SavePassword(uacnew); ControllerUtils.ShowFCMMessage(response.UniqueCode, Utils.UserID); // Refresh list // ListRoles(); ListUserRoles(); } private void btnSaveRole_Click(object sender, EventArgs e) { SecurityRole role = new SecurityRole(); role.Role = txtRoleName.Text; role.Description = txtRoleDescription.Text; var response = BUSUserAccess.AddRole(role); ControllerUtils.ShowFCMMessage(response, HeaderInfo.Instance.UserID); RefreshList(); } private void btnNewRole_Click(object sender, EventArgs e) { txtRoleName.Focus(); } private void tsRefresh_Click(object sender, EventArgs e) { RefreshList(); } private void RefreshList() { // Refresh list // ListRoles(); ListUserRoles(); ListScreens(); tvScreenList.Nodes[0].Expand(); tvUserList.Nodes[0].Expand(); tvAvailableRoles.Nodes[0].Expand(); } /// <summary> /// List user roles /// </summary> private void ListUserRoles() { tvUserList.Nodes.Clear(); // List User/Roles _ListOfUsers = UserAccess.List(); // Create root // UserAccess root = new UserAccess(); root.UserID = "ROOT"; root.UserName = "ROOT FOLDER"; var rootNode = new TreeNode(root.UserID, FCMConstant.Image.Folder, FCMConstant.Image.Folder); rootNode.Tag = root; tvUserList.Nodes.Add(rootNode); foreach (var user in _ListOfUsers) { var usernode = new TreeNode( user.UserID, FCMConstant.Image.Client, FCMConstant.Image.Client); usernode.Tag = user; rootNode.Nodes.Add(usernode); // List Roles // SecurityUserRole userRole = new SecurityUserRole(HeaderInfo.Instance); var userRoleList = userRole.UserRoleList(user.UserID); foreach (var userrole in userRoleList) { var userrolenode = new TreeNode( userrole.FK_Role, FCMConstant.Image.Checked, FCMConstant.Image.Checked); userrolenode.Tag = userrole; usernode.Nodes.Add(userrolenode); } } } /// <summary> /// List roles /// </summary> private void ListRoles() { tvAvailableRoles.Nodes.Clear(); // List roles // SecurityRole rootRole = new SecurityRole(); rootRole.Role = "ROOT"; rootRole.Description = "ROOT FOLDER"; var rootRoleNode = new TreeNode( rootRole.Role, FCMConstant.Image.Folder, FCMConstant.Image.Folder); rootRoleNode.Tag = rootRole; tvAvailableRoles.Nodes.Add(rootRoleNode); var roleList = SecurityRole.List(); foreach (var role in roleList) { var roleNode = new TreeNode( role.Role, FCMConstant.Image.Checked, FCMConstant.Image.Checked); roleNode.Tag = role; rootRoleNode.Nodes.Add(roleNode); // Add screens connected to role // var respList = BUSUserAccess.ListByRole(role.Role); var listOfScreens = (List<SecurityRoleScreen>) respList.Contents; // Get Screen Description from cache. // foreach (var screen in listOfScreens) { var screenDescription = CachedInfo.GetDescription(FCMConstant.CodeTypeString.SCREENCODE, screen.FKScreenCode); var screenNode = new TreeNode( screenDescription, FCMConstant.Image.Folder, FCMConstant.Image.Folder); screenNode.Tag = screen; roleNode.Nodes.Add(screenNode); } } } /// <summary> /// List screens /// </summary> private void ListScreens() { tvScreenList.Nodes.Clear(); var codeValue = new CodeValue(); var listOfScreens = new List<CodeValue>(); codeValue.ListS(FCMConstant.CodeTypeString.SCREENCODE, listOfScreens); // List roles // CodeValue rootScreen = new CodeValue(); rootScreen.ID = "ROOT"; rootScreen.Description = "ROOT Screen"; var rootScreenNode = new TreeNode( rootScreen.ID, FCMConstant.Image.Folder, FCMConstant.Image.Folder); rootScreenNode.Tag = rootScreen; tvScreenList.Nodes.Add(rootScreenNode); foreach (var screen in listOfScreens) { var roleNode = new TreeNode( screen.Description, FCMConstant.Image.Checked, FCMConstant.Image.Checked); roleNode.Tag = screen; rootScreenNode.Nodes.Add(roleNode); } } private void tvScreenList_DragDrop(object sender, DragEventArgs e) { // Get selected item in available tree // TreeNode tnRoleAvailableSelected = tvScreenList.SelectedNode; if (tnRoleAvailableSelected == null) return; } private void tvScreenList_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void tvScreenList_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void groupBox1_Enter(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.Security; using FCMMySQLBusinessLibrary; namespace fcm.Windows { public partial class UIUserSettings : Form { private TreeNode tndocSelected; private List<UserSettings> _ListOfSettings; ImageList imageList; ImageList imageList32; public string ScreenCode; float tvClientDocumentListFontSize; int tvClientDocumentListIconSize; /// <summary> /// Constructor /// </summary> public UIUserSettings() { InitializeComponent(); } private void UIUserSettings_Load(object sender, EventArgs e) { // Image list // // 32 x 32 imageList32 = ControllerUtils.GetImageList(); imageList32.ImageSize = new Size(32, 32); // 16 x 16 imageList = ControllerUtils.GetImageList(); tvUserSettings.ImageList = imageList; // Clear nodes tvUserSettings.Nodes.Clear(); ListUserSettings(); } /// <summary> /// List user roles /// </summary> private void ListUserSettings() { tvUserSettings.Nodes.Clear(); // List User/Roles _ListOfSettings = UserSettings.List(Utils.UserID); // Create root // UserAccess root = new UserAccess(); root.UserID = Utils.UserID; root.UserName = Utils.UserID; var rootNode = new TreeNode(root.UserID, FCMConstant.Image.Folder, FCMConstant.Image.Folder); rootNode.Tag = root; tvUserSettings.Nodes.Add(rootNode); foreach (var userSetting in _ListOfSettings) { string show = userSetting.FKScreenCode + " " + userSetting.FKControlCode + " " + userSetting.FKPropertyCode + " " + userSetting.Value + " "; var usernode = new TreeNode( show, FCMConstant.Image.Client, FCMConstant.Image.Client); usernode.Tag = userSetting; rootNode.Nodes.Add(usernode); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIDocumentIssue : Form { public UIDocumentIssue() { InitializeComponent(); } private void UIDocumentIssue_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Repository.RepositoryClient { public class RepClientEmail : ClientEmail { // ----------------------------------------------------- // List clients // ----------------------------------------------------- public static List<ClientEmail> List(string groupType) { var clientEmailList = new List<ClientEmail>(); if (string.IsNullOrEmpty(groupType)) return new List<ClientEmail>(); using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = string.Format( " SELECT " + " UID " + ", FirstName " + ", LastName " + ", EmailAddress " + ", Type " + " FROM ClientEmail " + " WHERE (EmailSent is null or EmailSent = '') and Type = @groupType" + " ORDER BY UID ASC " ); using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add("@groupType", MySqlDbType.VarChar).Value = groupType; connection.Open(); try { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var clientEmail = new ClientEmail(); clientEmail.UID = Convert.ToInt32(reader["UID"]); clientEmail.FirstName = reader["FirstName"].ToString(); clientEmail.LastName = reader["LastName"].ToString(); clientEmail.EmailAddress = reader["EmailAddress"].ToString(); clientEmail.Type = reader["Type"].ToString(); clientEmailList.Add(clientEmail); } } } catch (Exception ex) { string error = ex.ToString(); LogFile.WriteToTodaysLogFile(ex.ToString(), "", "", "ClientEmail.cs"); } } } return clientEmailList; } // ----------------------------------------------------- // List clients // ----------------------------------------------------- public static List<ClientEmail> ListCertificates(string groupType) { var clientEmailList = new List<ClientEmail>(); string certType = "Cert"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + ", FirstName " + ", LastName " + ", EmailAddress " + ", Type " + ", Document" + ", CertificateType " + " FROM ClientEmail, temp_emailattach" + " WHERE " + " FKEmailClientID = SecID and " + " Type = @groupType and CertificateType = @certType " + " ORDER BY UID ASC " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@groupType", MySqlDbType.VarChar).Value = groupType; command.Parameters.Add("@certType", MySqlDbType.VarChar).Value = certType; connection.Open(); try { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var clientEmail = new ClientEmail(); clientEmail.UID = Convert.ToInt32(reader["UID"]); clientEmail.FirstName = reader["FirstName"].ToString(); clientEmail.LastName = reader["LastName"].ToString(); clientEmail.EmailAddress = reader["EmailAddress"].ToString(); clientEmail.Type = reader["Type"].ToString(); clientEmail.Attachment = reader["Document"].ToString(); clientEmail.CertificateType = reader["CertificateType"].ToString(); clientEmailList.Add(clientEmail); } } } catch (Exception ex) { string error = ex.ToString(); LogFile.WriteToTodaysLogFile(ex.ToString(), "", "", "ClientEmail.cs"); } } } return clientEmailList; } // // Set void flag // public static void UpdateToEmailSent(int clientEmailUID) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientEmail " + " SET " + " EmailSent = @EmailSent" + " WHERE " + " UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = clientEmailUID; command.Parameters.Add("@EmailSent", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } } } } <file_sep>using System.ServiceModel; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Interface { [ServiceContract] public interface IBUSClientList { [OperationContract] ClientListResponse ClientList(HeaderInfo headerInfo); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; namespace fcm.Windows { public partial class UIDocument : Form { private DocumentSet documentSet; private DocumentSetList dsl; public UIDocument() { InitializeComponent(); // Initialise DocumentSet documentSet = new DocumentSet(); } private void UIDocumentSet_Load(object sender, EventArgs e) { dsl = new DocumentSetList(); dsl.ListInComboBox(cbxDocumentSet); if (cbxDocumentSet.Items.Count > 0) { cbxDocumentSet.SelectedIndex = 0; SelectIndexChanged(); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } public void loadDocumentList() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvFileList.ImageList = imageList; // Clear nodes tvFileList.Nodes.Clear(); var docoList = new DocumentList(); docoList.List(); // Load document in the treeview // // docoList.ListInTree(tvFileList); Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvFileList, docoList, root); // tvFileList.ExpandAll(); tvFileList.Nodes[0].Expand(); } public void loadDocumentList(int documentSetUID = 0) { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvFileList.ImageList = imageList; // Clear nodes tvFileList.Nodes.Clear(); // List Document Set documentSet.UID = documentSetUID; documentSet.Read(IncludeDocuments: 'Y'); // Load document in the treeview // Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); // Using Business Layer root = BUSDocument.GetRootDocument(); // DocumentList.ListInTree(tvFileList, documentSet.documentList, root); tvFileList.Nodes[0].Expand(); } private void cbxDocumentSet_SelectedIndexChanged(object sender, EventArgs e) { SelectIndexChanged(); } // Handles the selection index change // private void SelectIndexChanged() { int documentSetUID = 0; if (string.IsNullOrEmpty(cbxDocumentSet.Text) || cbxDocumentSet.Visible == false) { documentSetUID = 0; } else { string[] ArrayDocSetText = cbxDocumentSet.Text.Split(';'); documentSetUID = Convert.ToInt32(ArrayDocSetText[0]); } if (documentSetUID == 0) loadDocumentList(); else loadDocumentList(documentSetUID); txtDocumentSetUID.Text = documentSet.UID.ToString(); txtDocumentSetName.Text = documentSet.TemplateType; } private void btnLoadAllDocuments_Click(object sender, EventArgs e) { // Using private variable to load documents documentSet.LoadAllDocuments(); SelectIndexChanged(); MessageBox.Show("Document Loaded Successfully."); } private void tsbRemove_Click(object sender, EventArgs e) { TreeNode tndocSelected = tvFileList.SelectedNode; if (tndocSelected == null) return; TreeNode parent = tndocSelected.Parent; if (tndocSelected == null) return; else { if (tndocSelected.Tag.GetType().Name == "Document") { DocumentSet.DeleteDocumentTreeNode(documentSetUID: documentSet.UID, documentSetNode: tndocSelected); } tndocSelected.Remove(); tvFileList.SelectedNode = parent; } } private void tsbNew_Click(object sender, EventArgs e) { txtDocumentSetName.Text = ""; txtDocumentSetUID.Text = ""; txtDocumentSetName.Focus(); } private void miLinkDocumentFolder_Click(object sender, EventArgs e) { LinkDocument(); } private void LinkDocument() { TreeNode tnSelected = new TreeNode(); tnSelected = tvFileList.SelectedNode; TreeNode parentNode = new TreeNode(); parentNode = tnSelected.Parent; if (tnSelected == null) return; var nodeSelected = (Document)tnSelected.Tag; DocumentList docList = new DocumentList(); UIDocumentList udl = new UIDocumentList(docList); udl.ShowDialog(); foreach (var documentSelected in docList.documentList) { DocumentSetDocument docfind = new DocumentSetDocument(); docfind.Find(documentSelected.UID, documentSet.UID, voidRead: 'N'); if (docfind.UID > 0) continue; DocumentSetDocument dsd = new DocumentSetDocument(); dsd.FKDocumentSetUID = documentSet.UID; dsd.FKDocumentUID = documentSelected.UID; dsd.EndDate = System.DateTime.MaxValue; dsd.StartDate = System.DateTime.Today; dsd.UID = 0; dsd.Location = documentSelected.Location; dsd.SequenceNumber = tnSelected.Index; dsd.IsVoid = 'N'; dsd.FKParentDocumentSetUID = documentSet.UID; dsd.FKParentDocumentUID = nodeSelected.UID; dsd.Add(); TreeNode tnNew = new TreeNode(); tnNew.Tag = documentSelected; tnSelected.Nodes.Add(tnNew); } // Reset sequence numbers ResetAllSequenceNumbers(tvFileList.Nodes[0]); SelectIndexChanged(); } private void ResetAllSequenceNumbers(TreeNode root) { foreach (TreeNode tn in root.Nodes) { var doc = (Document)tn.Tag; doc.SequenceNumber = tn.Index; DocumentSetDocument.UpdateSequenceNumber(DocumentSetUID: documentSet.UID, DocumentUID: doc.UID, SequenceNumber: tn.Index); foreach (TreeNode tn2 in tn.Nodes) { ResetAllSequenceNumbers(tn2); } } } private void label1_Click(object sender, EventArgs e) { } private void tsbDown_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; int i = tndocSelected.Index + 1; tndocSelected.Remove(); parent.Nodes.Insert(i, tndocSelected); tvFileList.SelectedNode = tndocSelected; // Update sequence number ResetAllSequenceNumbers(parent); } private void tsbUp_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; if (tndocSelected.Index > 0) { int i = tndocSelected.Index - 1; tndocSelected.Remove(); parent.Nodes.Insert(i, tndocSelected); tvFileList.SelectedNode = tndocSelected; // Update sequence number ResetAllSequenceNumbers(parent); } } private void btnSave_Click(object sender, EventArgs e) { DocumentSet ds = new DocumentSet(); if (string.IsNullOrEmpty(txtDocumentSetUID.Text)) { ds.IsVoid = 'N'; ds.Name = txtDocumentSetName.Text; ds.TemplateType = txtDocumentSetName.Text; ds.TemplateFolder = ""; ds.UID = 0; ds.Add(); } else { ds.IsVoid = 'N'; ds.TemplateType = txtDocumentSetName.Text; ds.UID = documentSet.UID; ds.Update(); } // Reload document set list // cbxDocumentSet.Items.Clear(); dsl.ListInComboBox(cbxDocumentSet); cbxDocumentSet.SelectedIndex = 0; SelectIndexChanged(); } private void tsbExit_Click(object sender, EventArgs e) { this.Close(); } private void tsmManageLinks_Click(object sender, EventArgs e) { UIDocumentSetDocumentLink uidosdl = new UIDocumentSetDocumentLink(documentSet.UID, cbxDocumentSet.Text); uidosdl.ShowDialog(); } private void tvFileList_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvFileList.SelectedNode = tvFileList.GetNodeAt( e.X, e.Y ); } } private void addToolStripMenuItem_Click(object sender, EventArgs e) { LinkDocument(); } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using System.Windows.Forms; using System.Linq; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentLinkList { public List<DocumentLink> documentLinkList; // ----------------------------------------------------- // List related documents // ----------------------------------------------------- public static DocumentLinkList ListRelatedDocuments(int docUID, string type) { DocumentLinkList ret = new DocumentLinkList(); ret.documentLinkList = new List<DocumentLink>(); string linktype=""; if (type == "ALL" || string.IsNullOrEmpty(type)) { // do nothing } else { linktype = " AND link.LinkType = '" + type + "'"; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " link.FKParentDocumentUID " + " ,doc.UID DOCUID " + " ,link.LinkType " + " ,doc.CUID "+ " ,doc.Name "+ " ,doc.SequenceNumber,doc.IssueNumber " + " ,doc.Location,doc.Comments,doc.SourceCode,doc.FileName " + " ,doc.FKClientUID,doc.ParentUID " + " ,doc.RecordType,doc.IsProjectPlan " + " ,docFrom.CUID docFromCUID "+ " ,docFrom.Name docFromName " + " ,docFrom.SequenceNumber " + " ,docFrom.IssueNumber " + " ,docFrom.UID docFromUID " + " ,docFrom.Location docFromLocation " + " ,docFrom.Comments " + " ,docFrom.SourceCode,docFrom.FileName " + " ,docFrom.FKClientUID,docFrom.ParentUID " + " ,docFrom.RecordType,docFrom.IsProjectPlan " + " ,link.UID,link.IsVoid " + " FROM Document doc, " + " DocumentLink link, " + " Document docFrom " + " WHERE " + " link.IsVoid = 'N' " + linktype + " AND link.FKParentDocumentUID = {0} " + " AND doc.UID = link.FKChildDocumentUID " + " AND docFrom.UID = link.FKParentDocumentUID ", docUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { DocumentLink _Document = new DocumentLink(); _Document.FKParentDocumentUID = docUID; _Document.documentFrom = new Model.ModelDocument.Document(); _Document.documentTo = new Model.ModelDocument.Document(); _Document.documentTo.UID = Convert.ToInt32(reader["DOCUID"].ToString()); _Document.FKChildDocumentUID = _Document.documentTo.UID; _Document.documentTo.CUID = reader["CUID"].ToString(); _Document.documentTo.Name = reader["Name"].ToString(); _Document.documentTo.SequenceNumber = Convert.ToInt32(reader["SequenceNumber"].ToString()); _Document.documentTo.IssueNumber = Convert.ToInt32(reader["IssueNumber"].ToString()); _Document.documentTo.Location = reader["Location"].ToString(); _Document.documentTo.Comments = reader["Comments"].ToString(); _Document.documentTo.SourceCode = reader["SourceCode"].ToString(); _Document.documentTo.FileName = reader["FileName"].ToString(); _Document.documentTo.FKClientUID = Convert.ToInt32(reader["FKClientUID"].ToString()); _Document.documentTo.ParentUID = Convert.ToInt32(reader["ParentUID"].ToString()); _Document.documentTo.RecordType = reader["RecordType"].ToString(); _Document.documentTo.IsProjectPlan = reader["IsProjectPlan"].ToString(); _Document.LinkType = reader["LinkType"].ToString(); _Document.documentFrom.UID = Convert.ToInt32(reader["docFromUID"].ToString()); _Document.documentFrom.Name = reader["docFromName"].ToString(); string isVoid = reader["IsVoid"].ToString(); ret.documentLinkList.Add(_Document); } } } } return ret; } // ----------------------------------------------------- // Load documents in a tree // ----------------------------------------------------- public static void ListInTree( TreeView fileList, DocumentLinkList documentList, Model.ModelDocument.Document root) { // Find root folder // Model.ModelDocument.Document rootDocument = new Model.ModelDocument.Document(); rootDocument.CUID = root.CUID; rootDocument.RecordType = root.RecordType; rootDocument.UID = root.UID; // rootDocument.Read(); rootDocument = RepDocument.Read(true, root.UID); // Create root // var rootNode = new TreeNode(rootDocument.Name, MakConstant.Image.Folder, MakConstant.Image.Folder); // Add root node to tree // fileList.Nodes.Add(rootNode); rootNode.Tag = rootDocument; rootNode.Name = rootDocument.Name; foreach (var document in documentList.documentLinkList) { // Ignore root folder if (document.documentTo.CUID == "ROOT") continue; // Check if folder has a parent string cdocumentUID = document.UID.ToString(); string cparentIUID = document.documentTo.ParentUID.ToString(); int image = 0; document.documentTo.RecordType = document.documentTo.RecordType.Trim(); image = Utils.ImageSelect(document.documentTo.RecordType); if (document.documentTo.ParentUID == 0) { var treeNode = new TreeNode(document.documentTo.Name, image, image); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find(cparentIUID, true); if (node.Count() > 0) { var treeNode = new TreeNode(document.documentTo.Name, image, image); treeNode.Tag = document; treeNode.Name = cdocumentUID; node[0].Nodes.Add(treeNode); } else { // Add Element to the root // var treeNode = new TreeNode(document.documentTo.Name, image, image); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add(treeNode); } } } } // ----------------------------------------------------- // List related documents // ----------------------------------------------------- public static DocumentLinkList ListRelatedDocuments(int docUID) { return ListRelatedDocuments(docUID, "ALL"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClient; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace fcm.Windows.Cache { public static class CachedInfo { public static List<RelatedCode> ListOfRelatedCodes; public static List<RelatedCodeValue> ListOfRelatedCodeValues; public static List<CodeType> ListOfCodeTypes; public static List<CodeValue> ListOfCodeValues; public static List<CodeValue> ErrorList; public static List<CodeValue> ListOfScreensAllowedToUser; /// <summary> /// Refresh cache /// </summary> /// <returns></returns> public static void LoadReferenceDataInCache(HeaderInfo headerInfo) { if (CachedInfo.ListOfCodeTypes == null) CachedInfo.ListOfCodeTypes = new List<CodeType>(); var codeType = new CodeType(); codeType.List(headerInfo); ListOfCodeTypes.Clear(); ListOfCodeTypes = codeType.codeTypeList; if (ListOfCodeValues != null) ListOfCodeValues.Clear(); var codeValue = new CodeValue(); ListOfCodeValues = codeValue.ListS(); if (ListOfScreensAllowedToUser != null) ListOfScreensAllowedToUser.Clear(); CachedInfo.ListOfScreensAllowedToUser = BUSReferenceData.GetListScreensForUser(Utils.UserID); return; } /// <summary> /// Retrieve description from cache. /// </summary> /// <param name="codeType"></param> /// <param name="codeValue"></param> /// <returns></returns> public static string GetDescription(string codeType, string codeValue) { string response = ""; foreach (var value in ListOfCodeValues) { if (value.FKCodeType == codeType && value.ID == codeValue) response = value.Description; } return response; } /// <summary> /// List value for a give code type /// </summary> /// <param name="codeType"></param> /// <returns></returns> public static List<CodeValue> GetListOfCodeValue(string codeType) { List<CodeValue> list = new List<CodeValue>(); foreach (var value in ListOfCodeValues) { if (value.FKCodeType == codeType) { list.Add(value); } } return list; } /// <summary> /// Refresh cache /// </summary> /// <returns></returns> public static void LoadRelatedCodeInCache() { if (CachedInfo.ListOfRelatedCodes == null) CachedInfo.ListOfRelatedCodes = new List<RelatedCode>(); if (CachedInfo.ListOfRelatedCodes != null) CachedInfo.ListOfRelatedCodes.Clear(); CachedInfo.ListOfRelatedCodes = BUSReferenceData.ListRelatedCode(); CachedInfo.ListOfRelatedCodeValues = BUSReferenceData.ListRelatedCodeValue(); return; } /// <summary> /// Retrieve related code from cache /// </summary> /// <param name="relatedCodeID"></param> /// <returns></returns> public static RelatedCode GetRelatedCode( string relatedCodeID ) { RelatedCode response = new RelatedCode(); foreach (var value in ListOfRelatedCodes) { if (value.RelatedCodeID == relatedCodeID) response = value; } return response; } /// <summary> /// List value for a give code type /// </summary> /// <param name="codeType"></param> /// <returns></returns> public static List<RelatedCodeValue> GetListOfRelatedCodeValue( string relatedCodeID, string codeTypeFrom, string codeValueFrom) { List<RelatedCodeValue> list = new List<RelatedCodeValue>(); foreach (var value in ListOfRelatedCodeValues) { if ( value.FKRelatedCodeID == relatedCodeID && value.FKCodeTypeFrom == codeTypeFrom && value.FKCodeValueFrom == codeValueFrom ) { list.Add(value); } } return list; } public static bool IsUserAllowedToScreen(string userID, string screen) { bool userIsAllowed = false; foreach (var sc in CachedInfo.ListOfScreensAllowedToUser) { if (sc.ID == screen) { userIsAllowed = true; break; } } return userIsAllowed; } } } <file_sep>using System; namespace MackkadoITFramework.Interfaces { public interface IOutputMessage { void AddOutputMessage( string outputMessage, string processName, string userID ); void AddErrorMessage( string errorMessage, string processName, string userID ); void UpdateProgressBar( double value, DateTime estimatedTime, int documentsToBeGenerated = 0 ); void Activate(); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data; using System.Globalization; using System.Transactions; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using MackkadoITFramework.ErrorHandling; using FCMUtils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace FCMMySQLBusinessLibrary.Repository.RepositoryClient { public class RepClient : Client { public RepClient(HeaderInfo headerInfo) { _headerInfo = headerInfo; } public RepClient() { } // ----------------------------------------------------- // Get Client details // ----------------------------------------------------- public ResponseStatus Read() { // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientFieldString() + " FROM Client" + " WHERE UID = @UID"; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadClientObject(reader, this); } catch (Exception) { UID = 0; } } } } return new ResponseStatus(); } // ----------------------------------------------------- // Get Client details // ----------------------------------------------------- public static ClientReadResponse Read(int iUID) { // // EA SQL database // ClientReadResponse crr = new ClientReadResponse(); crr.responseStatus = new ResponseStatus(); crr.client = new Client(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientFieldString() + " FROM Client" + " WHERE UID = @UID"; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = iUID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadClientObject(reader, crr.client); } catch (Exception) { crr.client.UID = 0; } } } } return crr; } /// <summary> /// Check if user is already connected to a client /// </summary> /// <returns></returns> internal ResponseStatus ReadLinkedUser() { var response = new ResponseStatus(); // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientFieldString() + " FROM Client" + " WHERE FKUserID = @FKUserID "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKUserID", MySqlDbType.String).Value = FKUserID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { int cliendUIDRead = Convert.ToInt32(reader[FCMDBFieldName.Client.UID]); // If client uid read is the same as user id passed in // no issues if (cliendUIDRead == this.UID) { // User ID is already connect to a client. // User is connected to client supplied // response.ReturnCode = 0001; response.ReasonCode = 0003; response.Message = "User is linked to client supplied."; } else { // User ID is already connect to a client. // User is NOT connected to client supplied // response.ReturnCode = 0001; response.ReasonCode = 0001; response.Message = "User is linked to a different client."; } LoadClientObject(reader, this); } catch (Exception) { UID = 0; response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "Error retrieving client."; } } else { UID = 0; response.ReturnCode = 0001; response.ReasonCode = 0010; response.Message = "User ID is not linked to a Client."; } } } return response; } /// <summary> /// Check if user is already connected to a client /// </summary> /// <returns></returns> public static ResponseStatus ReadLinkedUser(Client client) { var response = new ResponseStatus(); // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientFieldString() + " FROM Client" + " WHERE FKUserID = @FKUserID "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKUserID", MySqlDbType.String).Value = client.FKUserID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { int cliendUIDRead = Convert.ToInt32(reader[FCMDBFieldName.Client.UID]); // If client uid read is the same as user id passed in // no issues if (cliendUIDRead == client.UID) { // User ID is already connect to a client. // User is connected to client supplied // response.ReturnCode = 0001; response.ReasonCode = 0003; response.Message = "User is linked to client supplied."; } else { // User ID is already connect to a client. // User is NOT connected to client supplied // response.ReturnCode = 0001; response.ReasonCode = 0001; response.Message = "User is linked to a different client."; } LoadClientObject(reader, client); } catch (Exception) { client.UID = 0; response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "Error retrieving client."; } } else { client.UID = 0; response.ReturnCode = 0001; response.ReasonCode = 0010; response.Message = "User ID is not linked to a Client."; } } } return response; } /// <summary> /// Check if user is already connected to a client /// </summary> /// <returns></returns> public static int ReadLinkedClient( string userID ) { int clientUID = 0; // // EA SQL database // using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { var commandString = " SELECT " + ClientFieldString() + " FROM Client" + " WHERE FKUserID = @FKUserID "; using ( var command = new MySqlCommand( commandString, connection ) ) { command.Parameters.Add( "@FKUserID", MySqlDbType.String ).Value = userID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if ( reader.Read() ) { try { clientUID = Convert.ToInt32( reader [FCMDBFieldName.Client.UID] ); // If client uid read is the same as user id passed in // no issues } catch ( Exception ) { } } } } return clientUID; } /// <summary> /// Retrieve client's field information /// </summary> /// <param name="field">Field name - use Client.FieldName</param> /// <param name="clientUID"></param> /// <returns></returns> internal static ReadFieldResponse ReadFieldClient(ReadFieldRequest readFieldRequest) { var ret = ""; // // EA SQL database // ReadFieldResponse rfr = new ReadFieldResponse(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { const string commandString = " SELECT @field FROM Client " + " WHERE UID = @clientUID "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.AddWithValue("@field", readFieldRequest.field); command.Parameters.AddWithValue("@clientUID", readFieldRequest.clientUID); connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { ret = reader[readFieldRequest.field].ToString(); } catch (Exception) { rfr.responseStatus.Message = "Error retrieving data. (ReadFieldClient) " + commandString; } } } } return rfr; } /// <summary> /// Retrieve client's field information /// </summary> /// <param name="field">Field name - use Client.FieldName</param> /// <param name="clientUID"></param> /// <returns></returns> internal static string GetClientName( int clientUID ) { var ret = ""; // // EA SQL database // using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { const string commandString = " SELECT NAME FROM Client " + " WHERE UID = @clientUID "; using ( var command = new MySqlCommand( commandString, connection ) ) { command.Parameters.AddWithValue( "@clientUID", clientUID ); connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if ( reader.Read() ) { try { ret = reader ["NAME"].ToString(); } catch ( Exception ) { } } } } return ret; } //// ----------------------------------------------------- //// Get Client details //// ----------------------------------------------------- //public ResponseStatus Read(int iUID) //{ // var response = new ResponseStatus(); // var retClient = new Client( _headerInfo ); // // // // EA SQL database // // // using (var connection = new MySqlConnection(ConnString.ConnectionString)) // { // var commandString = // " SELECT " + // ClientFieldString() + // " FROM Client" + // " WHERE UID = @UID " ; // using (var command = new MySqlCommand( // commandString, connection)) // { // command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; // connection.Open(); // MySqlDataReader reader = command.ExecuteReader(); // if (reader.Read()) // { // try // { // LoadClientObject(reader, retClient); // } // catch (Exception) // { // UID = 0; // } // } // } // } // response.Contents = retClient; // return response; //} /// <summary> /// Add new Client /// </summary> /// <returns></returns> public static ResponseStatus Insert(HeaderInfo headerInfo, Client client, MySqlConnection connection = null ) { var response = new ResponseStatus(); response.ReturnCode = 1; response.ReasonCode = 1; response.Message = "Client Added Successfully"; int uid = 0; int nextUID = GetLastUID() + 1; // 2010100000 if (nextUID == 1) { nextUID = DateTime.Now.Year * 100000 + 1; } uid = DateTime.Now.Year * 100000 + ( Convert.ToInt32( nextUID.ToString(CultureInfo.InvariantCulture).Substring(4,5) ) ); client.UID = uid; client.RecordVersion = 1; if (String.IsNullOrEmpty(client.Name)) { response.ReturnCode = -10; response.ReasonCode = 1; response.Message = "Error: Client Name is Mandatory."; return response; } if (client.Address == null) client.Address = ""; if (client.MainContactPersonName == null) client.MainContactPersonName = ""; // using (var connection = new MySqlConnection(ConnString.ConnectionString)) if (connection == null) { connection = new MySqlConnection(ConnString.ConnectionString); connection.Open(); } var commandString = ( "INSERT INTO Client " + "(" + ClientFieldString() + ")" + " VALUES " + ClientFieldValue() ); using (var command = new MySqlCommand( commandString, connection)) { client.RecordVersion = 1; AddSqlParameters(command, MackkadoITFramework.Helper.Utils.SQLAction.CREATE, headerInfo, client); command.ExecuteNonQuery(); } response.Contents = uid; return response; } /// <summary> /// Update client details /// </summary> /// <returns></returns> public static ResponseStatus Update(HeaderInfo headerInfo, Client client, MySqlConnection conn = null) { var response = new ResponseStatus(); response.ReturnCode = 1; response.ReasonCode = 1; response.Message = "Client Updated Successfully."; if (client.Name == null) client.Name = ""; if (client.Address == null) client.Address = ""; if (client.MainContactPersonName == null) client.MainContactPersonName = ""; // Check record version. Do not allow update if version is different if (!IsTheSameRecordVersion(client.UID, client.RecordVersion)) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "Record updated previously by another user."; return response; } string commandString = ( "UPDATE Client " + " SET " + FCMDBFieldName.Client.ABN + " = @" + FCMDBFieldName.Client.ABN + ", " + FCMDBFieldName.Client.RecordVersion + " = @" + FCMDBFieldName.Client.RecordVersion + ", " + FCMDBFieldName.Client.Name + " = @" + FCMDBFieldName.Client.Name + ", " + FCMDBFieldName.Client.LegalName + " = @" + FCMDBFieldName.Client.LegalName + ", " + FCMDBFieldName.Client.Address + " = @" + FCMDBFieldName.Client.Address + ", " + FCMDBFieldName.Client.Phone + " = @" + FCMDBFieldName.Client.Phone + ", " + FCMDBFieldName.Client.Fax + " = @" + FCMDBFieldName.Client.Fax + ", " + FCMDBFieldName.Client.Mobile + " = @" + FCMDBFieldName.Client.Mobile + ", " + FCMDBFieldName.Client.Logo1Location + " = @" + FCMDBFieldName.Client.Logo1Location + ", " + FCMDBFieldName.Client.Logo2Location + " = @" + FCMDBFieldName.Client.Logo2Location + ", " + FCMDBFieldName.Client.Logo3Location + " = @" + FCMDBFieldName.Client.Logo3Location + ", " + FCMDBFieldName.Client.FKUserID + " = @" + FCMDBFieldName.Client.FKUserID + ", " + FCMDBFieldName.Client.FKDocumentSetUID + " = @" + FCMDBFieldName.Client.FKDocumentSetUID + ", " + FCMDBFieldName.Client.EmailAddress + " = @" + FCMDBFieldName.Client.EmailAddress + ", " + FCMDBFieldName.Client.MainContactPersonName + " = @" + FCMDBFieldName.Client.MainContactPersonName + ", " + FCMDBFieldName.Client.DisplayLogo + " = @" + FCMDBFieldName.Client.DisplayLogo + ", " + FCMDBFieldName.Client.UpdateDateTime + " = @" + FCMDBFieldName.Client.UpdateDateTime + ", " + FCMDBFieldName.Client.UserIdUpdatedBy + " = @" + FCMDBFieldName.Client.UserIdUpdatedBy + " WHERE UID = @UID " ); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { using (var command = new MySqlCommand(cmdText: commandString, connection: connection)) { client.RecordVersion++; AddSqlParameters(command, MackkadoITFramework.Helper.Utils.SQLAction.UPDATE, headerInfo, client); try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), headerInfo.UserID); response.ReturnCode = -0020; response.ReasonCode = 0001; response.Message = "Error saving client. " + ex.ToString(); return response; } } } return response; } /// <summary> /// Logical Delete client /// </summary> /// <param name="client"></param> /// <returns></returns> internal static ResponseStatus Delete(Client client) { var response = new ResponseStatus(); response.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000007; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE Client " + " SET " + " IsVoid = @IsVoid " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = client.UID; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = "Y"; connection.Open(); command.ExecuteNonQuery(); } } return response; } // ----------------------------------------------------- // Retrieve last Client UID // ----------------------------------------------------- private static int GetLastUID() { int lastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM Client"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { lastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { lastUID = 0; } } } } return lastUID; } /// <summary> /// Check if the record version is the same. If it is not, deny update /// </summary> /// <param name="clientUID"></param> /// <param name="recordVersion"></param> /// <returns></returns> private static bool IsTheSameRecordVersion(int clientUID, int recordVersion) { // // EA SQL database // int currentVersion = 0; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT recordversion FROM Client WHERE UID = " + clientUID.ToString(CultureInfo.InvariantCulture); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { currentVersion = Convert.ToInt32(reader["recordversion"]); } catch (Exception) { currentVersion = 0; } } } } bool ret = false; if (currentVersion == 0 || currentVersion != recordVersion) ret = false; else ret = true; return ret; } // ----------------------------------------------------- // List clients // ----------------------------------------------------- public static List<Client> List(HeaderInfo _headerInfo) { var clientList = new List<Client>(); using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = string.Format( " SELECT " + ClientFieldString() + " FROM Client " + " WHERE IsVoid = 'N' " + " ORDER BY UID ASC " ); using (var command = new MySqlCommand( commandString, connection )) { connection.Open(); try { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var client = new Client(_headerInfo); RepClient.LoadClientObject(reader, client); // Retrieve status of the logo. Enabled or disabled // // 26.01.2013 // The attribute is now stored on the Client Table // //var rmd = new ReportMetadata(); //rmd.Read(client.UID, ReportMetadata.MetadataFieldCode.COMPANYLOGO); //client.DisplayLogo = rmd.Enabled; clientList.Add(client); } } } catch (Exception ex) { string error = ex.ToString(); LogFile.WriteToTodaysLogFile(ex.ToString(), _headerInfo.UserID, "", "Client.cs"); } } } return clientList; } /// <summary> /// Get Logo location for a client. /// </summary> /// <param name="clientUID"></param> /// <param name="curEnvironment"> </param> /// <returns></returns> public static string GetClientLogoLocation(int clientUID, HeaderInfo headerInfo, string curEnvironment = MackkadoITFramework.Helper.Utils.EnvironmentList.LOCAL ) { string logoPath = ""; string logoName = ""; string logoPathName = ""; Utils.FCMenvironment = curEnvironment; // Get Company Logo // //ReportMetadata rmd = new ReportMetadata(); //rmd.ClientUID = clientUID; //rmd.RecordType = Utils.MetadataRecordType.CLIENT; //rmd.FieldCode = "COMPANYLOGO"; //rmd.Read(clientUID: clientUID, fieldCode: "COMPANYLOGO"); //Client client = new Client(headerInfo); //client.UID = clientUID; //client.Read(); var resp = RepClient.Read(clientUID); Client client = new Client(); client = resp.client; // Set no icon image if necessary // logoPath = FCMConstant.SYSFOLDER.LOGOFOLDER; logoName = "imgNoImage.jpg"; if (client.Logo1Location != null) { logoName = client.Logo1Location.Replace(FCMConstant.SYSFOLDER.LOGOFOLDER, string.Empty); } logoPathName = Utils.getFilePathName(logoPath, logoName); return logoPathName; } /// <summary> /// Load client object /// </summary> /// <param name="reader"></param> /// <param name="client"> </param> private static void LoadClientObject(MySqlDataReader reader, Client client) { client.UID = Convert.ToInt32(reader[FCMDBFieldName.Client.UID]); client.RecordVersion = Convert.ToInt32(reader[FCMDBFieldName.Client.RecordVersion]); client.ABN = reader[FCMDBFieldName.Client.ABN].ToString(); client.Name = reader[FCMDBFieldName.Client.Name].ToString(); client.LegalName = reader[FCMDBFieldName.Client.LegalName].ToString(); client.Address = reader[FCMDBFieldName.Client.Address].ToString(); client.EmailAddress = reader[FCMDBFieldName.Client.EmailAddress].ToString(); client.Phone = reader[FCMDBFieldName.Client.Phone].ToString(); try { client.FKUserID = reader[FCMDBFieldName.Client.FKUserID].ToString(); } catch { client.FKUserID = ""; } try { client.FKDocumentSetUID = Convert.ToInt32(reader[FCMDBFieldName.Client.FKDocumentSetUID]); } catch { client.FKDocumentSetUID = 0; } try { client.Fax = reader[FCMDBFieldName.Client.Fax].ToString(); } catch { client.Fax = ""; } try { client.Mobile = reader[FCMDBFieldName.Client.Mobile].ToString(); } catch { client.Mobile = ""; } try { client.Logo1Location = reader[FCMDBFieldName.Client.Logo1Location].ToString(); } catch { client.Logo1Location = ""; } try { client.Logo2Location = reader[FCMDBFieldName.Client.Logo2Location].ToString(); } catch { client.Logo2Location = ""; } try { client.Logo3Location = reader[FCMDBFieldName.Client.Logo3Location].ToString(); } catch { client.Logo3Location = ""; } try { client.MainContactPersonName = reader[FCMDBFieldName.Client.MainContactPersonName].ToString(); } catch { client.MainContactPersonName = ""; } try { client.DisplayLogo = Convert.ToChar(reader[FCMDBFieldName.Client.DisplayLogo]); } catch { client.DisplayLogo = ' '; } try { client.UpdateDateTime = Convert.ToDateTime(reader[FCMDBFieldName.Client.UpdateDateTime].ToString()); } catch { client.UpdateDateTime = DateTime.Now; } try { client.CreationDateTime = Convert.ToDateTime(reader[FCMDBFieldName.Client.CreationDateTime].ToString()); } catch { client.CreationDateTime = DateTime.Now; } try { client.IsVoid = reader[FCMDBFieldName.Client.IsVoid].ToString(); } catch { client.IsVoid = "N"; } try { client.UserIdCreatedBy = reader[FCMDBFieldName.Client.UserIdCreatedBy].ToString(); } catch { client.UserIdCreatedBy = "N"; } try { client.UserIdUpdatedBy = reader[FCMDBFieldName.Client.UserIdCreatedBy].ToString(); } catch { client.UserIdCreatedBy = "N"; } client.DocSetUIDDisplay = "0; 0"; if (client.FKDocumentSetUID > 0) { DocumentSet ds = new DocumentSet(); ds.UID = client.FKDocumentSetUID; ds.Read('N'); client.DocSetUIDDisplay = ds.UID + "; " + ds.TemplateType; } } /// <summary> /// Add SQL Parameters /// </summary> /// <param name="_uid"></param> /// <param name="command"></param> /// <param name="action"></param> /// <param name="headerInfo"> </param> private static void AddSqlParameters(MySqlCommand command, string action, HeaderInfo headerInfo, Client client) { if (string.IsNullOrEmpty(headerInfo.UserID)) headerInfo.UserID = "UNDEF"; command.Parameters.Add("@UID", MySqlDbType.Int32).Value = client.UID; command.Parameters.Add("@ABN", MySqlDbType.VarChar).Value = client.ABN; command.Parameters.Add("@Name", MySqlDbType.VarChar).Value = client.Name; command.Parameters.Add("@LegalName", MySqlDbType.VarChar).Value = client.LegalName; command.Parameters.Add("@Address", MySqlDbType.VarChar).Value = client.Address; command.Parameters.Add("@Phone", MySqlDbType.VarChar).Value = client.Phone; command.Parameters.Add("@EmailAddress", MySqlDbType.VarChar).Value = client.EmailAddress; command.Parameters.Add("@Fax", MySqlDbType.VarChar).Value = client.Fax; command.Parameters.Add("@Mobile", MySqlDbType.VarChar).Value = client.Mobile; command.Parameters.Add("@Logo1Location", MySqlDbType.VarChar).Value = client.Logo1Location; command.Parameters.Add("@Logo2Location", MySqlDbType.VarChar).Value = client.Logo2Location; command.Parameters.Add("@Logo3Location", MySqlDbType.VarChar).Value = client.Logo3Location; command.Parameters.Add("@MainContactPersonName", MySqlDbType.VarChar).Value = client.MainContactPersonName; command.Parameters.Add("@DisplayLogo", MySqlDbType.VarChar).Value = client.DisplayLogo; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = "N"; command.Parameters.Add("@FKUserID", MySqlDbType.VarChar).Value = client.FKUserID; command.Parameters.Add("@FKDocumentSetUID", MySqlDbType.Int32).Value = client.FKDocumentSetUID; command.Parameters.Add("@UpdateDateTime", MySqlDbType.DateTime, 8).Value = System.DateTime.Today; command.Parameters.Add("@UserIdUpdatedBy", MySqlDbType.VarChar).Value = headerInfo.UserID; if (action == MackkadoITFramework.Helper.Utils.SQLAction.CREATE) { command.Parameters.Add("@CreationDateTime", MySqlDbType.DateTime, 8).Value = System.DateTime.Today; command.Parameters.Add("@UserIdCreatedBy", MySqlDbType.VarChar).Value = headerInfo.UserID; } command.Parameters.Add("@recordVersion", MySqlDbType.Int32).Value = client.RecordVersion; } /// <summary> /// Client string of fields. /// </summary> /// <returns></returns> private static string ClientFieldString() { string ret = FCMDBFieldName.Client.UID + "," + FCMDBFieldName.Client.ABN + "," + FCMDBFieldName.Client.Name + "," + FCMDBFieldName.Client.LegalName + "," + FCMDBFieldName.Client.Address + "," + FCMDBFieldName.Client.Phone + "," + FCMDBFieldName.Client.EmailAddress + "," + FCMDBFieldName.Client.Fax + "," + FCMDBFieldName.Client.Mobile + "," + FCMDBFieldName.Client.Logo1Location + "," + FCMDBFieldName.Client.Logo2Location + "," + FCMDBFieldName.Client.Logo3Location + "," + FCMDBFieldName.Client.MainContactPersonName + "," + FCMDBFieldName.Client.DisplayLogo + "," + FCMDBFieldName.Client.IsVoid + "," + FCMDBFieldName.Client.FKUserID + "," + FCMDBFieldName.Client.FKDocumentSetUID + "," + FCMDBFieldName.Client.UpdateDateTime + "," + FCMDBFieldName.Client.UserIdUpdatedBy + "," + FCMDBFieldName.Client.CreationDateTime + "," + FCMDBFieldName.Client.UserIdCreatedBy + "," + FCMDBFieldName.Client.RecordVersion; return ret; } /// <summary> /// Client string of fields. /// </summary> /// <returns></returns> private static string ClientFieldValue() { string ret = "( @UID " + ", @ABN " + ", @Name " + ", @LegalName " + ", @Address " + ", @Phone " + ", @EmailAddress " + ", @Fax " + ", @Mobile " + ", @Logo1Location " + ", @Logo2Location " + ", @Logo3Location " + ", @MainContactPersonName " + ", @DisplayLogo " + ", @IsVoid " + ", @FKUserID " + ", @FKDocumentSetUID " + ", @UpdateDateTime " + ", @UserIdUpdatedBy " + ", @CreationDateTime " + ", @UserIdCreatedBy " + ", @recordVersion ) "; return ret; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIClientDetails : Form { // private string _connectionString; private string _userID; public DataTable elementSourceDataTable; public DataTable employeeSourceDataTable; public UIClientDetails(string userID) { InitializeComponent(); // _connectionString = connectionString; _userID = userID; // // Create datatable (Client) // var UID = new DataColumn("UID", typeof(String)); var ABN = new DataColumn("ABN", typeof(String)); var Name = new DataColumn("Name", typeof(String)); var Phone = new DataColumn("Phone", typeof(String)); var Fax = new DataColumn("Fax", typeof(String)); var EmailAddress = new DataColumn("EmailAddress", typeof(String)); var MainContactPersonName = new DataColumn("MainContactPersonName", typeof(String)); var Address = new DataColumn("Address", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(UID); elementSourceDataTable.Columns.Add(ABN); elementSourceDataTable.Columns.Add(Name); elementSourceDataTable.Columns.Add(Phone); elementSourceDataTable.Columns.Add(Fax); elementSourceDataTable.Columns.Add(EmailAddress); elementSourceDataTable.Columns.Add(MainContactPersonName); elementSourceDataTable.Columns.Add(Address); dgvClientList.DataSource = elementSourceDataTable; // // Create datatable (Employee) // var EmployeeUID = new DataColumn("EmployeeUID", typeof(String)); var EmployeeRoleType = new DataColumn("EmployeeRoleType", typeof(String)); var EmployeeRoleDescription = new DataColumn("EmployeeRoleDescription", typeof(String)); var EmployeeName = new DataColumn("EmployeeName", typeof(String)); var FK_CompanyUID = new DataColumn("FK_CompanyUID", typeof(String)); employeeSourceDataTable = new DataTable("EmployeeSourceDataTable"); employeeSourceDataTable.Columns.Add(EmployeeUID); employeeSourceDataTable.Columns.Add(EmployeeRoleDescription); employeeSourceDataTable.Columns.Add(EmployeeName); employeeSourceDataTable.Columns.Add(FK_CompanyUID); employeeSourceDataTable.Columns.Add(EmployeeRoleType); dgvEmployeeList.DataSource = employeeSourceDataTable; } // -------------------------------------------------- // Save click // -------------------------------------------------- private void btnSave_Click(object sender, EventArgs e) { Client Client = new Client("Daniel"); Client.Name = txtName.Text; Client.ABN = txtABN.Text; Client.Address = txtAddress.Text; Client.Phone = txtPhone.Text; Client.Fax = txtFax.Text; Client.EmailAddress = txtEmailAddress.Text; Client.Fax = txtFax.Text; Client.MainContactPersonName = txtContactPerson.Text; Client.insert(); MessageBox.Show("Client Added Successfully."); loadClientList(); } private void ClientDetails_Load(object sender, EventArgs e) { loadClientList(); } // // List companies // private void loadClientList() { elementSourceDataTable.Clear(); var compList = new ClientList(_userID); compList.List(); foreach (Client Client in compList.clientList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["UID"] = Client.UID; elementRow["ABN"] = Client.ABN; elementRow["Name"] = Client.Name; elementRow["Phone"] = Client.Phone; elementRow["Fax"] = Client.Fax; elementRow["EmailAddress"] = Client.EmailAddress; elementRow["MainContactPersonName"] = Client.MainContactPersonName; elementRow["Address"] = Client.Address; elementSourceDataTable.Rows.Add(elementRow); } } private void btnAddNewClient_Click(object sender, EventArgs e) { txtABN.Text = ""; txtAddress.Text = ""; txtContactPerson.Text = ""; txtEmailAddress.Text = ""; txtFax.Text = ""; txtName.Text = ""; txtPhone.Text = ""; txtUID.Text = ""; } private void btnUpdateClientDetails_Click(object sender, EventArgs e) { } private void dgvClientList_SelectionChanged(object sender, EventArgs e) { LoadClientDetails(); } private void LoadClientDetails() { if (dgvClientList.SelectedRows.Count <= 0) return; var selectedRow = dgvClientList.SelectedRows; txtUID.Text = selectedRow[0].Cells["UID"].Value.ToString(); txtABN.Text = selectedRow[0].Cells["ABN"].Value.ToString(); txtName.Text = selectedRow[0].Cells["Name"].Value.ToString(); txtPhone.Text = selectedRow[0].Cells["Phone"].Value.ToString(); txtFax.Text = selectedRow[0].Cells["Fax"].Value.ToString(); txtAddress.Text = selectedRow[0].Cells["Address"].Value.ToString(); txtContactPerson.Text = selectedRow[0].Cells["MainContactPersonName"].Value.ToString(); txtEmailAddress.Text = selectedRow[0].Cells["EmailAddress"].Value.ToString(); loadEmployeeList(Convert.ToInt32(txtUID.Text)); Utils.ClientID = Convert.ToInt32(txtUID.Text); Utils.ClientIndex = Utils.ClientID-1; } // // List Employees // private void loadEmployeeList(int clientID) { employeeSourceDataTable.Clear(); var employeeList = new EmployeeList(); employeeList.List(clientID); foreach (Employee employee in employeeList.employeeList) { DataRow elementRow = employeeSourceDataTable.NewRow(); elementRow["FK_CompanyUID"] = employee.FKCompanyUID; elementRow["EmployeeUID"] = employee.UID; elementRow["EmployeeName"] = employee.Name; elementRow["EmployeeRoleType"] = employee.RoleType; elementRow["EmployeeRoleDescription"] = employee.RoleDescription; employeeSourceDataTable.Rows.Add(elementRow); } } private void btnSaveEmployee_Click(object sender, EventArgs e) { } private void btnDocuments_Click(object sender, EventArgs e) { UIClientDocumentSet ucds = new UIClientDocumentSet(); ucds.Show(); } private void dgvClientList_CellContentClick(object sender, DataGridViewCellEventArgs e) { } } } <file_sep>using System; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentSetDocumentLink { public int UID; public int FKDocumentSetUID; public int FKParentDocumentUID; public int FKChildDocumentUID; public string LinkType; public char IsVoid; public Model.ModelDocument.Document documentParent; public Model.ModelDocument.Document documentChild; public DocumentSetDocument documentSetDocumentParent; public DocumentSetDocument documentSetDocumentChild; // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM DocumentSetDocumentLink"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Add new Link // ----------------------------------------------------- public void Add() { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO DocumentSetDocumentLink " + " ( " + " UID " + ",FKDocumentSetUID " + ",FKParentDocumentUID " + ",FKChildDocumentUID]" + ",LinkType]" + ",IsVoid]" + ")" + " VALUES " + " ( " + " @UID " + ", @FKDocumentSetUID " + ", @FKParentDocumentUID " + ", @FKChildDocumentUID " + ", @LinkType " + ", @IsVoid" + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add("@FKDocumentSetUID", MySqlDbType.Int32).Value = FKDocumentSetUID; command.Parameters.Add("@FKParentDocumentUID", MySqlDbType.Int32).Value = FKParentDocumentUID; command.Parameters.Add("@FKChildDocumentUID", MySqlDbType.Int32).Value = FKChildDocumentUID; command.Parameters.Add("@LinkType", MySqlDbType.VarChar).Value = LinkType; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'N'; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Delete Link // ----------------------------------------------------- public static void DeleteAllRelated(int DocumentSetDocumentUID) { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "DELETE FROM DocumentSetDocumentLink " + " WHERE FKParentDocumentUID = @DocumentSetDocumentUID " + " OR FKChildDocumentUID = @DocumentSetDocumentUID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@DocumentSetDocumentUID", MySqlDbType.Int32).Value = DocumentSetDocumentUID; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Save Links // ----------------------------------------------------- public static void LinkDocuments(int DocumentSetUID, int ParentID, int ChildID, string LinkType) { DocumentSetDocumentLink findOne = new DocumentSetDocumentLink(); if (findOne.Read(DocumentSetUID, ParentID, ChildID, LinkType)) { // Already exists } else { findOne.LinkType = LinkType; findOne.FKDocumentSetUID = DocumentSetUID; findOne.FKParentDocumentUID = ParentID; findOne.FKChildDocumentUID = ChildID; findOne.Add(); } } // ----------------------------------------------------- // Get Link details // ----------------------------------------------------- public bool Read() { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKParentDocumentUID " + " ,FKChildDocumentUID " + " ,LinkType " + " FROM DocumentSetDocumentLink" + " WHERE IsVoid = 'N' " + " AND CUID = '{0}'", this.UID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.FKParentDocumentUID = Convert.ToInt32(reader["FKParentDocumentUID "].ToString()); this.FKChildDocumentUID = Convert.ToInt32(reader["FKChildDocumentUID"].ToString()); this.LinkType = reader["LinkType"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Get Link details // ----------------------------------------------------- public bool Read(int DocumentSetUID, int ParentID, int ChildID, string LinkType) { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKDocumentSetUID " + " ,FKParentDocumentUID " + " ,FKChildDocumentUID " + " ,LinkType " + " FROM DocumentSetDocumentLink" + " WHERE IsVoid = 'N' " + " AND FKDocumentSetUID = '{0}'" + " AND FKParentDocumentUID = '{1}'" + " AND FKChildDocumentUID = '{2}'" + " AND LinkType = '{3}' ", DocumentSetUID, ParentID, ChildID, LinkType); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.FKDocumentSetUID = Convert.ToInt32(reader["FKDocumentSetUID"].ToString()); this.FKParentDocumentUID = Convert.ToInt32(reader["FKParentDocumentUID"].ToString()); this.FKChildDocumentUID = Convert.ToInt32(reader["FKChildDocumentUID"].ToString()); this.LinkType = reader["LinkType"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Logical Delete // ----------------------------------------------------- public void Delete(int UID) { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE DocumentSetDocumentLink " + " SET " + " IsVoid = @IsVoid" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIMaintainProjectDocuments : Form { public UIMaintainProjectDocuments() { InitializeComponent(); } private void UIMaintainProjectDocuments_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using FCMMySQLBusinessLibrary.Service.SVCClient; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; namespace fcm.Windows { public partial class UIReportMetadata : Form { private string _userID; public DataTable elementSourceDataTable; private string listType; private int _clientUID; private Form _comingFromForm; public UIReportMetadata(Form comingFromForm) : this() { _comingFromForm = comingFromForm; listType = "DEFAULT"; } // This constructor lists variables for a specific Client // public UIReportMetadata(Form comingFromForm, int clientUID): this() { btnList.Enabled = false; btnSelect.Visible = true; listType = "CLIENT"; _clientUID = clientUID; cbxType.Enabled = false; cbxType.Text = listType; cbxClient.Enabled = false; } public UIReportMetadata(Form comingFromForm, bool DefaultOnly) : this() { btnList.Enabled = false; btnSelect.Visible = true; this.listType = "DEFAULT"; } private UIReportMetadata() { InitializeComponent(); btnSelect.Visible = false; // // Create datatable // var UID = new DataColumn("UID", typeof(String)); var RecordType = new DataColumn("RecordType", typeof(String)); var FieldCode = new DataColumn("FieldCode", typeof(String)); var Description = new DataColumn("Description", typeof(String)); var ClientType = new DataColumn("ClientType", typeof(String)); var ClientUID = new DataColumn("ClientUID", typeof(String)); var InformationType = new DataColumn("InformationType", typeof(String)); var Condition = new DataColumn("Condition", typeof(String)); var CompareWith = new DataColumn("CompareWith", typeof(String)); var Enabled = new DataColumn("Enabled", typeof(String)); var UseAsLabel = new DataColumn("UseAsLabel", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(UID); elementSourceDataTable.Columns.Add(RecordType); elementSourceDataTable.Columns.Add(FieldCode); elementSourceDataTable.Columns.Add(Description); elementSourceDataTable.Columns.Add(ClientType); elementSourceDataTable.Columns.Add(ClientUID); elementSourceDataTable.Columns.Add(InformationType); elementSourceDataTable.Columns.Add(Condition); elementSourceDataTable.Columns.Add(CompareWith); elementSourceDataTable.Columns.Add(Enabled); elementSourceDataTable.Columns.Add(UseAsLabel); dgvClientMetadata.DataSource = elementSourceDataTable; ucReportMetadata1.Visible = false; cbxType.Text = "DEFAULT"; loadMetadataList(0); } private void btnList_Click(object sender, EventArgs e) { loadMetadataList(0); } private void UIGeneralMetadata_Load(object sender, EventArgs e) { ucReportMetadata1.Visible = false; // Pass this instance to the component to enable the manipulation/refresh // of the list // ucReportMetadata1.SetUIReportInst(this); // Define defaults cbxType.Text = "DEFAULT"; loadMetadataList(0); // Get client list from background and load into the list // foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // Get selected client from the background // cbxClient.SelectedIndex = Utils.ClientIndex; } // Toggle edit screen private void EditMetadata(object sender, DataGridViewCellEventArgs e) { EditMetadata(false); } // // List companies // public void loadMetadataList(int iUID) { elementSourceDataTable.Clear(); int rts = -1; int cnt = 0; var metaList = new ReportMetadataList(); if (string.IsNullOrEmpty(listType)) { listType = "DEFAULT"; } // List metadata for a client if (listType == "CLIENT") { metaList.ListMetadataForClient(Utils.ClientID); } else { metaList.ListDefault(); } foreach (ReportMetadata metadata in metaList.reportMetadataList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["UID"] = metadata.UID; elementRow["RecordType"] = metadata.RecordType; elementRow["FieldCode"] = metadata.FieldCode; elementRow["Description"] = metadata.Description; elementRow["ClientType"] = metadata.ClientType; elementRow["ClientUID"] = metadata.ClientUID; elementRow["InformationType"] = metadata.InformationType; elementRow["Condition"] = metadata.Condition; elementRow["CompareWith"] = metadata.CompareWith; elementRow["Enabled"] = metadata.Enabled; elementRow["UseAsLabel"] = metadata.UseAsLabel; elementSourceDataTable.Rows.Add(elementRow); if (metadata.UID == iUID) rts = cnt; cnt++; } if (rts >= 0) { dgvClientMetadata.Rows[rts].Selected = true; } } // // // public void EditMetadata(object sender, EventArgs e) { EditMetadata(false); } public void EditMetadataRefresh(object sender, EventArgs e) { // It only does the refresh EditMetadata(true); } // // this method shows the component to edit/ add // a new metadata record. // private void EditMetadata(bool RefreshOnly) { if (!RefreshOnly) { // Toggle edit component // if (ucReportMetadata1.Visible == true) { ucReportMetadata1.Visible = false; refreshList(); return; } ucReportMetadata1.Visible = true; } // if there are no records selected // if (dgvClientMetadata.SelectedRows.Count <= 0) { ucReportMetadata1.NewEntry(Utils.ClientID); return; } var selectedRow = dgvClientMetadata.SelectedRows; ReportMetadata rm = new ReportMetadata(); rm.UID = Convert.ToInt32(selectedRow[0].Cells["UID"].Value); rm.RecordType = selectedRow[0].Cells["RecordType"].Value.ToString(); rm.FieldCode = selectedRow[0].Cells["FieldCode"].Value.ToString(); rm.ClientType = selectedRow[0].Cells["ClientType"].Value.ToString(); rm.Description = selectedRow[0].Cells["Description"].Value.ToString(); rm.ClientUID = Convert.ToInt32( selectedRow[0].Cells["ClientUID"].Value); rm.InformationType = selectedRow[0].Cells["InformationType"].Value.ToString(); rm.Condition = selectedRow[0].Cells["Condition"].Value.ToString(); rm.CompareWith = selectedRow[0].Cells["CompareWith"].Value.ToString(); rm.Enabled = Convert.ToChar(selectedRow[0].Cells["Enabled"].Value); rm.UseAsLabel = Convert.ToChar(selectedRow[0].Cells["UseAsLabel"].Value); ucReportMetadata1.SetValues(rm); } private void miEdit_Click(object sender, EventArgs e) { EditMetadata(false); } private void miDelete_Click(object sender, EventArgs e) { } private void UIReportMetadata_FormClosed(object sender, FormClosedEventArgs e) { if (_comingFromForm == null) { // Do nothing } else { _comingFromForm.Activate(); } } private void btnShow_Click(object sender, EventArgs e) { refreshList(); } public void refreshList() { if (string.IsNullOrEmpty(cbxType.Text)) { if (string.IsNullOrEmpty(listType)) listType = "DEFAULT"; } else listType = cbxType.Text; if (listType == "CLIENT") { _clientUID = Utils.ClientID; } loadMetadataList(0); } // When client is changed or the client document set is changed // private void indexChanged(object sender, EventArgs e) { listType = cbxType.Text; if (cbxType.Text == "DEFAULT") { cbxClient.Enabled = false; } else { cbxClient.Enabled = true; } if (cbxClient.SelectedIndex >= 0) { // Get selected client // // Find selected item // Utils.ClientIndex = cbxClient.SelectedIndex; // Extract client id Utils.ClientID = Utils.ClientList[Utils.ClientIndex].UID; } refreshList(); } private void UIReportMetadata_Load(object sender, EventArgs e) { // Get client list from background and load into the list // foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // Get selected client from the background // cbxClient.SelectedIndex = Utils.ClientIndex; cbxClient.Enabled = false; cbxType.Text = listType; // cbxType.SelectedIndex = 0; ucReportMetadata1.Visible = false; } private void btnNew_Click(object sender, EventArgs e) { ucReportMetadata1.NewEntry(0); ucReportMetadata1.Visible = true; } private void menuToolStripMenuItem_Click(object sender, EventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Components { public partial class UCCodeType : UserControl { public UCCodeType() { InitializeComponent(); } private void UCCodeType_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { CodeType ct = new CodeType(); ct.Code = txtCodeType.Text; ct.Description = txtCodeDescription.Text; ct.ShortCodeType = txtShortCode.Text; ct.Add(); MessageBox.Show("Code Type Save Successfully."); txtShortCode.Text = ""; txtCodeType.Text = ""; txtCodeDescription.Text = ""; txtCodeType.Focus(); } private void txtCodeType_TextChanged(object sender, EventArgs e) { } private void UCCodeType_Enter(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelClientDocument { public class ClientDocumentLink { public int UID; public int FKClientUID; public int FKParentDocumentUID; public int FKChildDocumentUID; public int FKClientDocumentSetUID; public string LinkType; public char isVoid; public ClientDocument parentClientDocument; public ClientDocument childClientDocument; public ClientDocumentSet clientDocumentSet; public Model.ModelDocument.Document parentDocument; public Model.ModelDocument.Document childDocument; public List<scClientDocSetDocLink> clientDocSetDocLink; // ----------------------------------------------------- // Add new Link // ----------------------------------------------------- public void Add() { int _uid = 0; _uid = GetLastUID() + 1; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO ClientDocumentLink " + " ( " + " UID " + ",FKParentDocumentUID " + ",FKChildDocumentUID" + ",FKClientDocumentSetUID" + ",FKClientUID" + ",LinkType" + ",IsVoid" + ")" + " VALUES " + " ( " + " @UID " + ", @FKParentDocumentUID " + ", @FKChildDocumentUID " + ", @FKClientDocumentSetUID " + ", @FKClientUID " + ", @LinkType " + ", @IsVoid" + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add("@FKParentDocumentUID", MySqlDbType.Int32).Value = FKParentDocumentUID; command.Parameters.Add("@FKChildDocumentUID", MySqlDbType.Int32).Value = FKChildDocumentUID; command.Parameters.Add("@FKClientDocumentSetUID ", MySqlDbType.Int32).Value = FKClientDocumentSetUID; command.Parameters.Add("@FKClientUID", MySqlDbType.Int32).Value = FKClientUID; command.Parameters.Add("@LinkType", MySqlDbType.VarChar).Value = LinkType; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'N'; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientDocumentLink"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // // List documents for a client // public void List(int clientID, int clientDocumentSetUID) { clientDocSetDocLink = new List<scClientDocSetDocLink>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,FKClientUID " + " ,FKClientDocumentSetUID " + " ,FKDocumentUID " + " ,SequenceNumber " + " ,StartDate " + " ,EndDate " + " ,IsVoid " + " ,SourceLocation " + " ,SourceFileName " + " ,Location " + " ,FileName " + " ,SourceIssueNumber " + " ,Generated " + " ,RecordType " + " ,ParentUID " + " FROM ClientDocument " + " WHERE FKClientUID = {0} " + " AND FKClientDocumentSetUID = {1} " + " ORDER BY ParentUID ASC, SequenceNumber ASC ", clientID, clientDocumentSetUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if (Convert.ToChar(reader["IsVoid"]) == 'Y') continue; var docItem = new scClientDocSetDocLink(); // Get document // docItem.document = new Model.ModelDocument.Document(); docItem.document.UID = Convert.ToInt32(reader["FKDocumentUID"]); // docItem.document.Read(); docItem.document = RepDocument.Read(false, docItem.document.UID); // Get Client Document Set // docItem.clientDocumentSet = new ClientDocumentSet(); docItem.clientDocumentSet.UID = Convert.ToInt32(reader["FKClientDocumentSetUID"].ToString()); docItem.clientDocumentSet.FKClientUID = Convert.ToInt32(reader["FKClientUID"].ToString()); // Set Client Document // docItem.clientDocument = new ClientDocument(); docItem.clientDocument.UID = Convert.ToInt32(reader["UID"].ToString()); docItem.clientDocument.FKDocumentUID = Convert.ToInt32(reader["FKDocumentUID"].ToString()); docItem.clientDocument.SequenceNumber = Convert.ToInt32(reader["SequenceNumber"].ToString()); docItem.clientDocument.FKClientDocumentSetUID = Convert.ToInt32(reader["FKClientDocumentSetUID"].ToString()); docItem.clientDocument.IsVoid = Convert.ToChar(reader["IsVoid"].ToString()); docItem.clientDocument.StartDate = Convert.ToDateTime(reader["StartDate"].ToString()); docItem.clientDocument.SourceLocation = reader["SourceLocation"].ToString(); docItem.clientDocument.SourceFileName = reader["SourceFileName"].ToString(); docItem.clientDocument.Location = reader["Location"].ToString(); docItem.clientDocument.FileName = reader["FileName"].ToString(); docItem.clientDocument.SourceIssueNumber = Convert.ToInt32(reader["SourceIssueNumber"].ToString()); docItem.clientDocument.Generated = Convert.ToChar(reader["Generated"]); docItem.clientDocument.RecordType = reader["RecordType"].ToString(); docItem.clientDocument.ParentUID = Convert.ToInt32(reader["ParentUID"].ToString()); try { docItem.clientDocument.EndDate = Convert.ToDateTime(reader["EndDate"].ToString()); } catch { docItem.clientDocument.EndDate = System.DateTime.MaxValue; } this.clientDocSetDocLink.Add(docItem); } } } } } // --------------------------------------------------------- // Copy document links to client document links // --------------------------------------------------------- public void ReplicateDocLinkToClientDeprecated(int ClientUID, int ClientSetUID) { // 1... GetClientDocument // List documents for a Client Set Document // var clientDocumentList = new ClientDocument(); // clientDocumentList.List(ClientUID, ClientSetUID); RepClientDocument.List( clientDocumentList, ClientUID, ClientSetUID ); // 2... foreach( clientDocument ) // For each client document, retrieve the linked documents // foreach (var clientDocument in clientDocumentList.clientDocSetDocLink) { // 3...... GetDocumentChildren( currentClientDocument) // This part retrieves Document Links and not ClientDocument Links // that's why we need to get the equivalent ClientDocumentUID... var children = DocumentLinkList.ListRelatedDocuments(clientDocument.document.UID); // 4...... foreach (GetDocumentChildren) foreach (var child in children.documentLinkList) { // 5..... CreateClientDocumentLink(Client,ClientSet,DocumentParent,DocumentChild, Type) ClientDocumentLink newLink = new ClientDocumentLink(); // This is the client document UID newLink.FKParentDocumentUID = clientDocument.clientDocument.UID; // Get clientUID for child document ClientDocument childDocument = new ClientDocument(); //childDocument.FKDocumentUID = child.UID; childDocument.FKDocumentUID = child.documentTo.UID; // childDocument.Find(child.documentTo.UID, clientDocument.clientDocumentSet.UID, 'N', ClientUID); childDocument = RepClientDocument.Find( child.documentTo.UID, clientDocument.clientDocumentSet.UID, 'N', ClientUID ); if (childDocument.UID > 0) { newLink.FKChildDocumentUID = childDocument.UID; newLink.LinkType = child.LinkType; // Replace by link type newLink.Add(); } } } //using (var connection = new MySqlConnection(ConnString.ConnectionString)) //{ // var commandString = string.Format( // " SELECT " + // " UID " + // " FROM ClientDocument " + // " WHERE " + // " FKClientUID = {0} " + // " AND FKClientDocumentSetUID = {1} ", // ClientUID, // ClientSetUID // ); // using (var command = new MySqlCommand( // commandString, connection)) // { // connection.Open(); // using (MySqlDataReader reader = command.ExecuteReader()) // { // while (reader.Read()) // { // int ClientDocumentUID; // ClientDocumentUID = Convert.ToInt32(reader["UID"].ToString()); // } // } // } //} } // --------------------------------------------------------- // Copy document links to client document links // --------------------------------------------------------- public void ReplicateDocLinkToClientX(int ClientUID, int ClientSetUID) { // 1... GetClientDocument // List documents for a Client Set Document // var clientDocumentList = new ClientDocument(); //clientDocumentList.List(ClientUID, ClientSetUID); RepClientDocument.List(clientDocumentList, ClientUID, ClientSetUID ); // 2... foreach( clientDocument ) // For each client document, retrieve the linked documents // foreach (var clientDocument in clientDocumentList.clientDocSetDocLink) { // 3...... GetDocumentChildren( currentClientDocument) // This part retrieves Document Links and not ClientDocument Links var children = DocumentLinkList.ListRelatedDocuments(clientDocument.document.UID); // 4...... foreach (GetDocumentChildren) foreach (var child in children.documentLinkList) { // 5..... CreateClientDocumentLink(Client,ClientSet,DocumentParent,DocumentChild, Type) ClientDocumentLink newLink = new ClientDocumentLink(); newLink.FKClientDocumentSetUID = ClientSetUID; newLink.FKClientUID = ClientUID; newLink.FKParentDocumentUID = clientDocument.document.UID; newLink.FKChildDocumentUID = child.FKChildDocumentUID; newLink.LinkType = child.LinkType; newLink.Add(); } } } // ------------------------------------------------------------ // Cop\y document links from Document Set Document Link // ------------------------------------------------------------ public void ReplicateDocSetDocLinkToClient(int ClientUID, int ClientSetUID, int DocumentSetUID) { // 1... GetClientDocument // List documents for a Client Set Document // var clientDocumentList = new ClientDocument(); //clientDocumentList.List( ClientUID, ClientSetUID ); RepClientDocument.List( clientDocumentList, ClientUID, ClientSetUID ); // 2... foreach( clientDocument ) // For each client document, retrieve the linked documents // foreach (var clientDocument in clientDocumentList.clientDocSetDocLink) { // 3...... GetDocumentChildren( currentClientDocument) // This part retrieves Document Links and not ClientDocument Links var children = DocumentSetDocumentLinkList.ListRelatedDocuments(DocumentSetUID, clientDocument.document.UID, type: "ALL"); // 4...... foreach (GetDocumentChildren) foreach (var child in children.documentSetDocumentLinkList) { // 5..... CreateClientDocumentLink(Client,ClientSet,DocumentParent,DocumentChild, Type) ClientDocumentLink newLink = new ClientDocumentLink(); newLink.FKClientDocumentSetUID = ClientSetUID; newLink.FKClientUID = ClientUID; newLink.FKParentDocumentUID = clientDocument.document.UID; newLink.FKChildDocumentUID = child.FKChildDocumentUID; newLink.LinkType = child.LinkType; newLink.Add(); } } } // ----------------------------------------------------- // Get Link details // ----------------------------------------------------- public bool Read(int ParentID, int ChildID, string LinkType, int clientUID, int clientDocumentSetUID) { // // EA SQL database // bool ret = false; if (ParentID == 0 || ChildID == 0 || string.IsNullOrEmpty(LinkType) || clientUID == 0 || clientDocumentSetUID == 0) { return false; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKParentDocumentUID " + " ,FKChildDocumentUID " + " ,FKClientDocumentSetUID " + " ,FKClientUID " + " ,LinkType " + " FROM ClientDocumentLink" + " WHERE IsVoid = 'N' " + " AND FKParentDocumentUID = {0}" + " AND FKChildDocumentUID = {1}" + " AND LinkType = '{2}' " + " AND FKClientUID = {3} " + " AND FKClientDocumentSetUID = {4} ", ParentID, ChildID, LinkType, clientUID, clientDocumentSetUID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.FKParentDocumentUID = Convert.ToInt32(reader["FKParentDocumentUID"].ToString()); this.FKChildDocumentUID = Convert.ToInt32(reader["FKChildDocumentUID"].ToString()); this.FKClientDocumentSetUID = Convert.ToInt32(reader["FKClientDocumentSetUID"].ToString()); this.FKClientUID = Convert.ToInt32(reader["FKClientUID"].ToString()); this.LinkType = reader["LinkType"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Save Links // ----------------------------------------------------- public static void LinkDocuments( int clientUID, int clientDocumentSetUID, int parentDocumentUID, int childDocumentUID, string LinkType) { ClientDocumentLink findOne = new ClientDocumentLink(); if (findOne.Read( ParentID: parentDocumentUID, ChildID: childDocumentUID, LinkType: LinkType, clientUID: clientUID, clientDocumentSetUID:clientDocumentSetUID )) { // Already exists } else { findOne.FKClientUID = clientUID; findOne.FKClientDocumentSetUID = clientDocumentSetUID; findOne.LinkType = LinkType; findOne.FKParentDocumentUID = parentDocumentUID; findOne.FKChildDocumentUID = childDocumentUID; findOne.Add(); } } // ----------------------------------------------------- // Logical Delete // ----------------------------------------------------- public void Delete(int UID) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocumentLink " + " SET " + " IsVoid = @IsVoid" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.ReferenceData { public class CodeValue { [Display(Name = "Code Type")] [Required(AllowEmptyStrings = false, ErrorMessage = "Code Type must be supplied.")] [StringLength(20, MinimumLength = 4, ErrorMessage = "Code Type must be between 4 and 20 characters")] public string FKCodeType { get; set; } [Display(Name = "Code Value ID")] [Required(AllowEmptyStrings = false, ErrorMessage = "Code Value must be supplied.")] [StringLength(20, MinimumLength = 2, ErrorMessage = "Code Value ID must be between 4 and 10 characters")] public string ID { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "Description must be supplied.")] [Display(Name = "Description")] [StringLength(200, MinimumLength = 2)] public string Description { get; set; } [Display(Name = "Abbreviation")] [StringLength(10, MinimumLength = 3)] public string Abbreviation { get; set; } [Display(Name = "Value Extended")] [StringLength(200, MinimumLength = 0)] public string ValueExtended { get; set; } public bool FoundinDB { get; set; } public List<CodeValue> codeValueList; public List<string> codeValueIDList; public string ListForCodeType; // Public Methods // /// <summary> /// Add or Update a record /// </summary> public ResponseStatus Save() { // Check if code value exists. // If it exists, update // Else Add a new one Read(true); bool results = FoundinDB; if (results) Update(); else Add(); return new ResponseStatus(); } // Delete record // public void Delete() { } /// <summary> /// Return value extended /// </summary> /// <param name="iCodeType"></param> /// <param name="iCodeValueID"></param> /// <param name="headerInfo"> </param> /// <returns></returns> public static string GetCodeValueExtended(string iCodeType, string iCodeValueID, string constring = "") { if (string.IsNullOrEmpty(constring)) constring = ConnString.ConnectionStringFramework; if (string.IsNullOrEmpty(constring)) { LogFile.WriteToTodaysLogFile( "GetCodeValueExtended Error. Connection string is empty.", programName: "ProcessRequestCodeValues.cs" ); return ""; } string ret = ""; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = " SELECT " + " ValueExtended " + " FROM rdCodeValue" + " WHERE FKCodeType = @FKCodeType " + " AND ID = @UID "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.AddWithValue("@UID", iCodeValueID); command.Parameters.AddWithValue("@FKCodeType", iCodeType); try { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { ret = reader["ValueExtended"] as string; } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "GetCodeValueExtended error retrieving extended. " + ex, programName: "ProcessRequestCodeValues.cs" ); throw new Exception(ex.ToString()); } } } return ret; } /// <summary> /// Return value extended /// </summary> /// <param name="iCodeType"></param> /// <param name="iCodeValueID"></param> /// <param name="headerInfo"> </param> /// <returns></returns> public static string GetCodeValueExtraString( string iCodeType, string iCodeValueID, string constring = "" ) { if ( string.IsNullOrEmpty( constring ) ) constring = ConnString.ConnectionStringFramework; if ( string.IsNullOrEmpty( constring ) ) { LogFile.WriteToTodaysLogFile( "GetCodeValueExtraString Error. Connection string is empty.", programName: "ProcessRequestCodeValues.cs" ); return ""; } string ret = ""; using ( var connection = new MySqlConnection( ConnString.ConnectionStringFramework ) ) { var commandString = " SELECT " + " ExtraString " + " FROM rdCodeValue" + " WHERE FKCodeType = @FKCodeType " + " AND ID = @UID "; using ( var command = new MySqlCommand( commandString, connection ) ) { command.Parameters.AddWithValue( "@UID", iCodeValueID ); command.Parameters.AddWithValue( "@FKCodeType", iCodeType ); try { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if ( reader.Read() ) { ret = reader ["ExtraString"] as string; } } catch ( Exception ex ) { LogFile.WriteToTodaysLogFile( "GetCodeValueExtraString error retrieving extended. " + ex, programName: "ProcessRequestCodeValues.cs" ); throw new Exception( ex.ToString() ); } } } return ret; } public static string GetCodeValueDescription(string iCodeType, string iCodeValueID, string constring = "") { string ret = ""; if (string.IsNullOrEmpty(constring)) constring = ConnString.ConnectionStringFramework; if ( string.IsNullOrEmpty(constring) ) { LogFile.WriteToTodaysLogFile( "GetCodeValueDescription Error. Connection string is empty.", programName: "ProcessRequestCodeValues.cs" ); return ""; } using (var connection = new MySqlConnection(constring)) { var commandString = " SELECT " + " Description " + " FROM rdCodeValue" + " WHERE FKCodeType = @FKCodeType " + " AND ID = @UID "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = iCodeValueID; command.Parameters.Add("@FKCodeType", MySqlDbType.VarChar).Value = iCodeType; try { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { ret = reader["Description"] as string; } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "GetCodeValueExtended error retrieving extended. " + ex, programName: "ProcessRequestCodeValues.cs" ); throw new Exception(ex.ToString()); } } } return ret; } public CodeValue Read(bool checkOnly) { CodeValue ret = null; // // EA SQL database // da using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue" + " WHERE FKCodeType = '{0}' " + " AND ID = '{1}' ", FKCodeType, this.ID); using (var command = new MySqlCommand( commandString, connection)) { try { connection.Open(); if (connection.State != System.Data.ConnectionState.Open) { LogFile.WriteToTodaysLogFile(connection.ServerThread.ToString()); return null; } MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { if (!checkOnly) { FKCodeType = reader["FKCodeType"] as string; ID = reader["ID"] as string; Description = reader["Description"] as string; Abbreviation = reader["Abbreviation"] as string; ValueExtended = reader["ValueExtended"] as string; } FoundinDB = true; } else { FoundinDB = false; } } catch (Exception ex) { Description = ex.ToString(); LogFile.WriteToTodaysLogFile(this.Description, Helper.Utils.UserID, null,"ProcessRequestCodeValues.cs"); throw new Exception(ex.ToString()); } } } return ret; } // // // public ResponseStatus Add() { string ret = "Item updated successfully"; int _uid = 0; DateTime _now = DateTime.Today; if (FKCodeType == null) return new ResponseStatus(MessageType.Error); if (ID == null) return new ResponseStatus(MessageType.Error); if (Description == null) return new ResponseStatus(MessageType.Error); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO rdCodeValue ( " + "FKCodeType, "+ "ID, " + "Description, " + "Abbreviation, " + "ValueExtended" + ")" + " VALUES " + "( " + " @FKCodeType " + ", @ID " + ", @Description " + ", @Abbreviation " + ", @ValueExtended " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKCodeType", MySqlDbType.VarChar).Value = FKCodeType; command.Parameters.Add("@ID", MySqlDbType.VarChar).Value = ID; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@Abbreviation", MySqlDbType.VarChar).Value = Abbreviation; command.Parameters.Add("@ValueExtended", MySqlDbType.VarChar).Value = ValueExtended; connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus(); } public ResponseStatus Update() { if (string.IsNullOrEmpty(FKCodeType)) return new ResponseStatus { ReturnCode = -0010, ReasonCode = 0001, Message = "Code Type is mandatory." }; if (string.IsNullOrEmpty( ID )) return new ResponseStatus { ReturnCode = -0010, ReasonCode = 0002, Message = "ID not supplied." }; if (string.IsNullOrEmpty( Description )) return new ResponseStatus { ReturnCode = -0010, ReasonCode = 0003, Message = "Description not supplied." }; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format ( "UPDATE rdCodeValue " + "SET " + " Description = '{0}', " + " Abbreviation = '{1}', " + " ValueExtended= '{2}' " + "WHERE " + " FKCodeType = '{3}' " + " AND ID = '{4}' ", Description, Abbreviation , ValueExtended, FKCodeType, ID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus(); } // ----------------------------------------------------- // Listing code values // ----------------------------------------------------- public void ListInCombo(string codeType, System.Windows.Forms.ComboBox input) { this.List(codeType); foreach (CodeValue cv in this.codeValueList) { input.Items.Add(cv.ID); } return; } public void ListInCombo(bool IDDesc, string codeType, System.Windows.Forms.ComboBox input) { this.List(codeType); foreach (CodeValue cv in this.codeValueList) { input.Items.Add(cv.ID + ";" + cv.Description); } return; } // // Public Methods // public ResponseStatus List(string codeType) { ListForCodeType = codeType; this.codeValueList = new List<CodeValue>(); this.codeValueIDList= new List<string>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue " + " WHERE FKCodeType = '{0}'" , codeType ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { CodeValue _codeValue = new CodeValue(); _codeValue.FKCodeType = reader["FKCodeType"] as string; _codeValue.ID = reader["ID"] as string; _codeValue.Description = reader["Description"] as string; _codeValue.Abbreviation = reader["Abbreviation"] as string; _codeValue.ValueExtended = reader["ValueExtended"] as string; this.codeValueList.Add(_codeValue); this.codeValueIDList.Add(_codeValue.ID); } } } } return new ResponseStatus(); } // // Public Methods // public static IEnumerable<CodeValue> ListCodeValues(string codeType) { List<CodeValue> listOfCodeValues = new List<CodeValue>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = " SELECT " + " FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue " + " WHERE FKCodeType = @FKCodeType "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.AddWithValue("@FKCodeType", codeType); connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { CodeValue _codeValue = new CodeValue(); _codeValue.FKCodeType = reader["FKCodeType"] as string; _codeValue.ID = reader["ID"] as string; _codeValue.Description = reader["Description"] as string; _codeValue.Abbreviation = reader["Abbreviation"] as string; _codeValue.ValueExtended = reader["ValueExtended"] as string; listOfCodeValues.Add(_codeValue); } } } } return listOfCodeValues; } public static bool IsValueInCodeType(string value, string codeType) { var listOfCodeValues = CodeValue.ListCodeValuesString(codeType); if (listOfCodeValues.Contains(value)) return true; return false; } public static List<string> ListCodeValuesString(string codeType) { List<string> listOfCodeValues = new List<string>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = " SELECT " + " FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue " + " WHERE FKCodeType = @FKCodeType "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.AddWithValue("@FKCodeType", codeType); connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { CodeValue _codeValue = new CodeValue(); _codeValue.FKCodeType = reader["FKCodeType"] as string; _codeValue.ID = reader["ID"] as string; _codeValue.Description = reader["Description"] as string; _codeValue.Abbreviation = reader["Abbreviation"] as string; _codeValue.ValueExtended = reader["ValueExtended"] as string; listOfCodeValues.Add(_codeValue.ID); } } } } return listOfCodeValues; } // // Public Methods // /// <summary> /// Return a list of codes for a given code type. /// </summary> /// <param name="codeType"></param> /// <returns></returns> public ResponseStatus ListS(string codeType, List<CodeValue> list) { using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue " + " WHERE FKCodeType = '{0}'", codeType); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _codeValue = new CodeValue(); _codeValue.FKCodeType = reader["FKCodeType"].ToString(); _codeValue.ID = reader["ID"].ToString(); _codeValue.Description = reader["Description"].ToString(); _codeValue.Abbreviation = reader["Abbreviation"].ToString(); _codeValue.ValueExtended = reader["ValueExtended"].ToString(); list.Add(_codeValue); } } } } return new ResponseStatus(); } /// <summary> /// Return a list of codes for a given code type. /// </summary> /// <param name="codeType"></param> /// <returns></returns> public List<CodeValue> ListS() { List<CodeValue> list = new List<CodeValue>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " FKCodeType " + " ,ID " + " ,Description " + " ,Abbreviation " + " ,ValueExtended " + " FROM rdCodeValue " + " ORDER BY FKCodeType " ) ; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { CodeValue _codeValue = new CodeValue(); _codeValue.FKCodeType = reader["FKCodeType"].ToString(); _codeValue.ID = reader["ID"].ToString(); _codeValue.Description = reader["Description"].ToString(); _codeValue.Abbreviation = reader["Abbreviation"].ToString(); _codeValue.ValueExtended = reader["ValueExtended"].ToString(); list.Add(_codeValue); } } } } return list; } } public class ListCodeValuesRequest { public HeaderInfo XHeaderInfo; public CodeType XCodeType; } public class ListCodeValuesResponse { public ResponseStatus XResponseStatus; public List<CodeValue> ListOfCodeValues; } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelClientDocument { public class ClientDocumentLinkList { public List<ClientDocumentLink> clientDocumentLinkList; // ----------------------------------- // List children documents // ----------------------------------- public void ListChildrenDocuments( int clientUID, int clientDocumentSetUID, int documentUID, string type ) { string linktype = ""; if (type == "ALL" || string.IsNullOrEmpty( type )) { // do nothing } else { linktype = " AND CDL.LinkType = '" + type + "'"; } // The client document UID is unique // The link table does not have document set uid // clientDocumentLinkList = new List<ClientDocumentLink>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " CDL.UID " + " ,CDL.FKChildDocumentUID " + " ,CDL.FKParentDocumentUID " + " ,CDL.LinkType " + " ,CDL.IsVoid " + " ,CD.UID childUID" + " ,CD.FKClientUID childFKClientUID" + " ,CD.FKClientDocumentSetUID childFKClientDocumentSetUID" + " ,CD.FKDocumentUID childFKDocumentUID" + " ,CD.SequenceNumber childSequenceNumber" + " ,CD.StartDate childStartDate" + " ,CD.EndDate childEndDate" + " ,CD.SourceLocation childSourceLocation" + " ,CD.SourceFileName childSourceFileName" + " ,CD.Location childLocation" + " ,CD.FileName childFileName" + " ,CD.SourceIssueNumber childIssueNumber" + " ,CD.Generated childGenerated" + " ,CD.RecordType childRecordType" + " ,CD.ParentUID childParentUID" + " ,CD.IsVoid childIsVoid" + " ,PARENT.UID parentUID" + " ,PARENT.FKClientUID parentFKClientUID" + " ,PARENT.FKClientDocumentSetUID parentFKClientDocumentSetUID" + " ,PARENT.FKDocumentUID parentFKDocumentUID" + " ,PARENT.SequenceNumber parentSequenceNumber" + " ,PARENT.StartDate parentStartDate" + " ,PARENT.EndDate parentEndDate" + " ,PARENT.SourceLocation parentSourceLocation" + " ,PARENT.SourceFileName parentSourceFileName" + " ,PARENT.Location parentLocation" + " ,PARENT.FileName parentFileName" + " ,PARENT.SourceIssueNumber parentIssueNumber" + " ,PARENT.Generated parentGenerated" + " ,PARENT.RecordType parentRecordType" + " ,PARENT.ParentUID parentParentUID" + " ,PARENT.IsVoid parentIsVoid" + " FROM ClientDocument CD, " + " ClientDocumentLink CDL," + " ClientDocument PARENT" + " WHERE " + " CDL.IsVoid = 'N' " + " AND PARENT.IsVoid = 'N' " + " AND CD.IsVoid = 'N' " + " AND CDL.FKParentDocumentUID = {0} " + " AND CDL.FKClientDocumentSetUID = {1} " + " AND CDL.FKClientUID = {2} " + " AND CDL.FKChildDocumentUID = CD.FKDocumentUID " + " AND CDL.FKParentDocumentUID = PARENT.FKDocumentUID " + linktype + " ORDER BY CD.ParentUID ASC, CD.SequenceNumber ASC " , documentUID , clientDocumentSetUID , clientUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if (Convert.ToChar(reader["IsVoid"]) == 'Y') continue; var docItem = new ClientDocumentLink(); // Set Client Document Link Details // docItem.UID = Convert.ToInt32(reader["UID"].ToString()); docItem.FKParentDocumentUID = Convert.ToInt32(reader["FKParentDocumentUID"].ToString()); docItem.FKChildDocumentUID = Convert.ToInt32(reader["FKChildDocumentUID"].ToString()); docItem.isVoid = Convert.ToChar(reader["IsVoid"].ToString()); docItem.LinkType = reader["LinkType"].ToString(); // Set Client Document Child // docItem.childClientDocument = new ClientDocument(); docItem.childClientDocument.UID = Convert.ToInt32(reader["childUID"].ToString()); docItem.childClientDocument.FKDocumentUID = Convert.ToInt32(reader["childFKDocumentUID"].ToString()); docItem.childClientDocument.SequenceNumber = Convert.ToInt32(reader["childSequenceNumber"].ToString()); docItem.childClientDocument.FKClientDocumentSetUID = Convert.ToInt32(reader["childFKClientDocumentSetUID"].ToString()); docItem.childClientDocument.IsVoid = Convert.ToChar(reader["childIsVoid"].ToString()); docItem.childClientDocument.StartDate = Convert.ToDateTime(reader["childStartDate"].ToString()); docItem.childClientDocument.SourceLocation = reader["childSourceLocation"].ToString(); docItem.childClientDocument.SourceFileName = reader["childSourceFileName"].ToString(); docItem.childClientDocument.Location = reader["childLocation"].ToString(); docItem.childClientDocument.FileName = reader["childFileName"].ToString(); docItem.childClientDocument.SourceIssueNumber = Convert.ToInt32(reader["childIssueNumber"].ToString()); docItem.childClientDocument.Generated = Convert.ToChar(reader["childGenerated"]); docItem.childClientDocument.RecordType = reader["childRecordType"].ToString(); docItem.childClientDocument.ParentUID = Convert.ToInt32(reader["childParentUID"].ToString()); //docItem.childClientDocument.EndDate = Convert.ToDateTime(reader["childEndDate"].ToString()); docItem.childClientDocument.EndDate = System.DateTime.MaxValue; // Set Client Document Parent // docItem.parentClientDocument = new ClientDocument(); docItem.parentClientDocument.UID = Convert.ToInt32(reader["parentUID"].ToString()); docItem.parentClientDocument.FKDocumentUID = Convert.ToInt32(reader["parentFKDocumentUID"].ToString()); docItem.parentClientDocument.SequenceNumber = Convert.ToInt32(reader["parentSequenceNumber"].ToString()); docItem.parentClientDocument.FKClientDocumentSetUID = Convert.ToInt32(reader["parentFKClientDocumentSetUID"].ToString()); docItem.parentClientDocument.IsVoid = Convert.ToChar(reader["parentIsVoid"].ToString()); docItem.parentClientDocument.StartDate = Convert.ToDateTime(reader["parentStartDate"].ToString()); docItem.parentClientDocument.SourceLocation = reader["parentSourceLocation"].ToString(); docItem.parentClientDocument.SourceFileName = reader["parentSourceFileName"].ToString(); docItem.parentClientDocument.Location = reader["parentLocation"].ToString(); docItem.parentClientDocument.FileName = reader["parentFileName"].ToString(); docItem.parentClientDocument.SourceIssueNumber = Convert.ToInt32(reader["parentIssueNumber"].ToString()); docItem.parentClientDocument.Generated = Convert.ToChar(reader["parentGenerated"]); docItem.parentClientDocument.RecordType = reader["parentRecordType"].ToString(); docItem.parentClientDocument.ParentUID = Convert.ToInt32(reader["parentParentUID"].ToString()); //docItem.parentClientDocument .EndDate = Convert.ToDateTime(reader["parentEndDate"].ToString()); docItem.parentClientDocument.EndDate = System.DateTime.MaxValue; this.clientDocumentLinkList.Add(docItem); } } } } } public static ClientDocumentLinkList ListRelatedDocuments( int clientUID, int clientDocumentSetUID, int documentUID, string type) { ClientDocumentLinkList ret = new ClientDocumentLinkList(); ret.clientDocumentLinkList = new List<ClientDocumentLink>(); string linktype = ""; if (type == "ALL" || string.IsNullOrEmpty(type)) { // do nothing } else { linktype = " AND CDL.LinkType = '" + type + "'"; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format ( "SELECT " + " CDL.UID CDLUID " + " ,CDL.FKParentDocumentUID CDLFKParentDocumentUID " + " ,CDL.FKChildDocumentUID CDLFKChildDocumentUID " + " ,CDL.LinkType CDLLinkType " + " ,CDL.IsVoid CDLIsVoid " + " ,CDL.FKClientDocumentSetUID CDLFKClientDocumentSetUID " + " ,CDL.FKClientUID CDLFKClientUID " + " " + " FROM ClientDocumentLink CDL " + " WHERE " + " CDL.IsVoid = 'N' " + " AND CDL.FKParentDocumentUID = {0} " + " AND CDL.FKClientDocumentSetUID = {1} " + " AND CDL.FKClientUID = {2} " + linktype , documentUID , clientDocumentSetUID , clientUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ClientDocumentLink clientDocumentLink = new ClientDocumentLink(); clientDocumentLink.UID = Convert.ToInt32(reader["CDLUID"].ToString()); clientDocumentLink.FKParentDocumentUID = Convert.ToInt32(reader["CDLFKParentDocumentUID"].ToString()); clientDocumentLink.FKChildDocumentUID = Convert.ToInt32(reader["CDLFKChildDocumentUID"].ToString()); clientDocumentLink.LinkType = reader["CDLLinkType"].ToString(); clientDocumentLink.FKClientDocumentSetUID = Convert.ToChar(reader["CDLFKClientDocumentSetUID"].ToString()); clientDocumentLink.FKClientUID = Convert.ToInt32(reader["CDLFKClientUID"].ToString()); // Get the client document child clientDocumentLink.childClientDocument = new ClientDocument(); clientDocumentLink.childClientDocument.UID = clientDocumentLink.FKChildDocumentUID; // 04.02.2013 // clientDocumentLink.childClientDocument.Read(); clientDocumentLink.childClientDocument = RepClientDocument.Read( clientDocumentLink.FKChildDocumentUID ); // Get the document child clientDocumentLink.childDocument = new Model.ModelDocument.Document(); clientDocumentLink.childDocument.UID = clientDocumentLink.FKChildDocumentUID; // clientDocumentLink.childDocument.Read(); clientDocumentLink.childDocument = RepDocument.Read(false, clientDocumentLink.FKChildDocumentUID); // Get the client document parent clientDocumentLink.parentClientDocument = new ClientDocument(); clientDocumentLink.parentClientDocument.UID = clientDocumentLink.FKParentDocumentUID; //clientDocumentLink.parentClientDocument.Read(); clientDocumentLink.parentClientDocument = RepClientDocument.Read( clientDocumentLink.FKParentDocumentUID ); // Get the document parent clientDocumentLink.parentDocument = new Model.ModelDocument.Document(); clientDocumentLink.parentDocument.UID = clientDocumentLink.FKParentDocumentUID; // clientDocumentLink.parentDocument.Read(); clientDocumentLink.parentDocument = RepDocument.Read(false, clientDocumentLink.FKParentDocumentUID); // Get the client document set clientDocumentLink.clientDocumentSet = new ClientDocumentSet(); clientDocumentLink.clientDocumentSet.UID = clientDocumentLink.FKClientDocumentSetUID; clientDocumentLink.clientDocumentSet.Read(); ret.clientDocumentLinkList.Add(clientDocumentLink); } } } } return ret; } // // Delete links to specific document // public static void VoidLinks( int clientUID, int clientDocumentSetUID, int documentUID ) { // 11/09/2010 19:03 // Continuar daqui. Preciso criar um metodo para apagar todos os links relacionados a um documento // Quando um documento e'deletado do cliente/ client document set preciso apagar o seguinte: // 1) ClientDocument // 2) ClientDocumentLink // 3) // Ja existe metodo para listar os documentos linkados... ClientDocumentLinkList... both directions... string ret = "Item updated successfully"; using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = ( "UPDATE ClientDocumentLink " + " SET " + " IsVoid = @IsVoid" + " WHERE " + " FKClientDocumentSetUID = @FKClientDocumentSetUID " + " AND FKClientUID = @FKClientUID " + " AND FKParentDocumentUID = @FKDocumentUID " + " OR FKChildDocumentUID = @FKDocumentUID " ); using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add( "@FKClientDocumentSetUID", MySqlDbType.Int32 ).Value = clientDocumentSetUID; command.Parameters.Add( "@FKClientUID", MySqlDbType.Int32 ).Value = clientUID; command.Parameters.Add( "@FKDocumentUID", MySqlDbType.Int32 ).Value = documentUID; command.Parameters.Add( "@IsVoid", MySqlDbType.VarChar ).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } // // Physically Delete links to specific document // public static void DeleteLinks( int clientUID, int clientDocumentSetUID, int documentUID ) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = ( "DELETE ClientDocumentLink " + "FROM ClientDocumentLink " + " WHERE " + " FKClientDocumentSetUID = @FKClientDocumentSetUID " + " AND FKClientUID = @FKClientUID " + " AND ( FKParentDocumentUID = @FKDocumentUID " + " OR FKChildDocumentUID = @FKDocumentUID )"); using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add( "@FKClientDocumentSetUID", MySqlDbType.Int32 ).Value = clientDocumentSetUID; command.Parameters.Add( "@FKClientUID", MySqlDbType.Int32 ).Value = clientUID; command.Parameters.Add( "@FKDocumentUID", MySqlDbType.Int32 ).Value = documentUID; command.Parameters.Add( "@IsVoid", MySqlDbType.VarChar ).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } } } } <file_sep>using System; using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; using System.IO; namespace FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument { public class RepClientDocument: ClientDocument { private RepClientDocument() { clientDocumentSet = new ClientDocumentSet(); } /// <summary> /// Retrieve client document /// </summary> /// <param name="clientDocumentUid"></param> /// <returns></returns> internal static ClientDocument Read(int clientDocumentUid) { var clientDocument = new ClientDocument(); bool ret = false; using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { var commandString = string.Format( " SELECT " + SQLConcat( "CD" ) + " FROM ClientDocument CD" + " WHERE CD.UID = {0} " , clientDocumentUid ); using ( var command = new MySqlCommand( commandString, connection ) ) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if ( reader.Read() ) { clientDocument.UID = Convert.ToInt32( reader ["CDUID"].ToString() ); clientDocument.FKClientUID = Convert.ToInt32( reader ["CDFKClientUID"].ToString() ); clientDocument.DocumentCUID = reader ["CDDocumentCUID"].ToString(); clientDocument.ParentUID = Convert.ToInt32( reader ["CDParentUID"].ToString() ); clientDocument.FKDocumentUID = Convert.ToInt32( reader ["CDFKDocumentUID"].ToString() ); clientDocument.SourceIssueNumber = Convert.ToInt32( reader ["CDSourceIssueNumber"].ToString() ); clientDocument.ClientIssueNumber = Convert.ToInt32( reader ["CDClientIssueNumber"].ToString() ); clientDocument.FKClientDocumentSetUID = Convert.ToInt32( reader ["CDFKClientDocumentSetUID"].ToString() ); clientDocument.SequenceNumber = Convert.ToInt32( reader ["CDSequenceNumber"].ToString() ); clientDocument.SourceLocation = reader ["CDSourceLocation"].ToString(); clientDocument.SourceFileName = reader ["CDSourceFileName"].ToString(); clientDocument.Location = reader ["CDLocation"].ToString(); clientDocument.FileName = reader ["CDFileName"].ToString(); clientDocument.StartDate = Convert.ToDateTime( reader ["CDStartDate"].ToString() ); try { clientDocument.EndDate = Convert.ToDateTime( reader ["CDEndDate"].ToString() ); } catch ( Exception ) { clientDocument.EndDate = DateTime.MaxValue; } clientDocument.IsVoid = Convert.ToChar( reader ["CDIsVoid"] ); clientDocument.IsLocked = Convert.ToChar( reader ["CDIsLocked"] ); clientDocument.IsProjectPlan = reader ["CDIsProjectPlan"].ToString(); clientDocument.DocumentType = reader ["CDDocumentType"].ToString(); clientDocument.RecordType = reader ["CDRecordType"].ToString(); } } } // ----------------------------------------- // Populate client document set // ----------------------------------------- clientDocument.clientDocumentSet.UID = clientDocument.FKClientDocumentSetUID; clientDocument.FKClientUID = clientDocument.FKClientUID; clientDocument.clientDocumentSet.Read(); return clientDocument; } /// <summary> /// Retrieve client document /// </summary> /// <param name="clientDocumentUid"></param> /// <returns></returns> internal static ClientDocument GetRoot( int clientUID, int documentSetUID ) { var clientDocument = new ClientDocument(); bool ret = false; using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { var commandString = " SELECT " + SQLConcat( "CD" ) + " FROM ClientDocument CD" + " WHERE CD.DocumentCUID = @DocumentCUID "+ " AND CD.FKClientUID = @FKClientUID " + " AND CD.FKClientDocumentSetUID = @FKClientDocumentSetUID "; using ( var command = new MySqlCommand( commandString, connection ) ) { command.Parameters.Add( "@DocumentCUID", MySqlDbType.VarChar ).Value = "ROOT"; command.Parameters.Add( "@FKClientUID", MySqlDbType.Int32 ).Value = clientUID; command.Parameters.Add( "@FKClientDocumentSetUID", MySqlDbType.Int32 ).Value = documentSetUID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if ( reader.Read() ) { clientDocument.UID = Convert.ToInt32( reader ["CDUID"].ToString() ); clientDocument.FKClientUID = Convert.ToInt32( reader ["CDFKClientUID"].ToString() ); clientDocument.DocumentCUID = reader ["CDDocumentCUID"].ToString(); clientDocument.ParentUID = Convert.ToInt32( reader ["CDParentUID"].ToString() ); clientDocument.FKDocumentUID = Convert.ToInt32( reader ["CDFKDocumentUID"].ToString() ); clientDocument.SourceIssueNumber = Convert.ToInt32( reader ["CDSourceIssueNumber"].ToString() ); clientDocument.ClientIssueNumber = Convert.ToInt32( reader ["CDClientIssueNumber"].ToString() ); clientDocument.FKClientDocumentSetUID = Convert.ToInt32( reader ["CDFKClientDocumentSetUID"].ToString() ); clientDocument.SequenceNumber = Convert.ToInt32( reader ["CDSequenceNumber"].ToString() ); clientDocument.SourceLocation = reader ["CDSourceLocation"].ToString(); clientDocument.SourceFileName = reader ["CDSourceFileName"].ToString(); clientDocument.Location = reader ["CDLocation"].ToString(); clientDocument.FileName = reader ["CDFileName"].ToString(); clientDocument.StartDate = Convert.ToDateTime( reader ["CDStartDate"].ToString() ); try { clientDocument.EndDate = Convert.ToDateTime( reader ["CDEndDate"].ToString() ); } catch ( Exception ) { clientDocument.EndDate = DateTime.MaxValue; } clientDocument.IsVoid = Convert.ToChar( reader ["CDIsVoid"] ); clientDocument.IsLocked = Convert.ToChar( reader ["CDIsLocked"] ); clientDocument.IsProjectPlan = reader ["CDIsProjectPlan"].ToString(); clientDocument.DocumentType = reader ["CDDocumentType"].ToString(); clientDocument.RecordType = reader ["CDRecordType"].ToString(); } } } // ----------------------------------------- // Populate client document set // ----------------------------------------- clientDocument.clientDocumentSet.UID = clientDocument.FKClientDocumentSetUID; clientDocument.FKClientUID = clientDocument.FKClientUID; clientDocument.clientDocumentSet.Read(); return clientDocument; } /// <summary> /// Get Document for a client. This method locates a ClientDocument using DocumentUID /// </summary> /// <param name="documentUID"></param> /// <param name="clientDocSetUID"></param> /// <param name="voidRead"></param> /// <param name="clientUID"> </param> /// <returns></returns> internal static ClientDocument Find( int documentUID, int clientDocSetUID, char voidRead, int clientUID) { // // EA SQL database // bool ret = false; ClientDocument clientDocument = new ClientDocument(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT "+ SQLConcat("CD") + " FROM ClientDocument CD" + " WHERE CD.FKDocumentUID = {0} " + " AND CD.FKClientDocumentSetUID = {1} " + " AND CD.IsVoid = '{2}' " + " AND CD.FKClientUID = {3} " , documentUID , clientDocSetUID , voidRead , clientUID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { clientDocument.UID = Convert.ToInt32( reader ["CDUID"].ToString() ); clientDocument.FKDocumentUID = Convert.ToInt32( reader ["CDFKDocumentUID"].ToString() ); clientDocument.SequenceNumber = Convert.ToInt32( reader ["CDSequenceNumber"].ToString() ); clientDocument.FKClientDocumentSetUID = Convert.ToInt32( reader ["CDFKClientDocumentSetUID"].ToString() ); clientDocument.StartDate = Convert.ToDateTime( reader ["CDStartDate"].ToString() ); // Tentar.... //this.EndDate = (reader.IsDBNull(10) ? DateTime.MaxValue : Convert.ToDateTime(reader["CDEndDate"].ToString())); // instead if this... try { clientDocument.EndDate = Convert.ToDateTime( reader ["CDEndDate"].ToString() ); } catch (Exception) { clientDocument.EndDate = DateTime.MaxValue; } clientDocument.IsVoid = Convert.ToChar( reader ["CDIsVoid"] ); ret = true; } } } return clientDocument; } // ----------------------------------------------------- // Associate documents with document set // ----------------------------------------------------- internal void LinkDocumentListToSet( ListOfscClientDocSetDocLink docListToLink ) { // for each document in the list // check if it is already linked with document set // if it is not linked, add a new link record // otherwise, ignore link. foreach (var doco in docListToLink.list) { LinkDocumentToClientSet(doco); } } // ----------------------------------------------------- // Associate documents with document set // ----------------------------------------------------- internal static int LinkDocumentToClientSet( scClientDocSetDocLink doco ) { int clientDocumentUID = 0; var dslLocate = new ClientDocument(); dslLocate.StartDate = DateTime.Today; dslLocate.IsVoid = 'N'; dslLocate.IsLocked = 'N'; dslLocate.IsProjectPlan = doco.clientDocument.IsProjectPlan; dslLocate.DocumentType = doco.clientDocument.DocumentType; dslLocate.FKDocumentUID = doco.document.UID; dslLocate.FKClientDocumentSetUID = doco.clientDocumentSet.UID; dslLocate.FKClientUID = doco.clientDocumentSet.FKClientUID; dslLocate.DocumentCUID = doco.clientDocument.DocumentCUID; dslLocate.SourceLocation = doco.clientDocument.SourceLocation; dslLocate.SourceFileName = doco.clientDocument.SourceFileName; dslLocate.Location = doco.clientDocument.Location; dslLocate.FileName = doco.clientDocument.FileName; dslLocate.SequenceNumber = doco.clientDocument.SequenceNumber; dslLocate.SourceIssueNumber = doco.clientDocument.SourceIssueNumber; dslLocate.Generated = 'N'; dslLocate.ParentUID = doco.clientDocument.ParentUID; dslLocate.RecordType = doco.clientDocument.RecordType; dslLocate.IsRoot = doco.clientDocument.IsRoot; dslLocate.IsFolder = doco.clientDocument.IsFolder; // Prepare data to add or update var dslAddUpdate = new ClientDocument(); dslAddUpdate.StartDate = DateTime.Today; dslAddUpdate.IsVoid = 'N'; dslAddUpdate.IsLocked = 'N'; dslAddUpdate.IsProjectPlan = doco.clientDocument.IsProjectPlan; dslAddUpdate.DocumentType = doco.clientDocument.DocumentType; dslAddUpdate.FKDocumentUID = doco.document.UID; dslAddUpdate.FKClientDocumentSetUID = doco.clientDocumentSet.UID; dslAddUpdate.FKClientUID = doco.clientDocumentSet.FKClientUID; dslAddUpdate.DocumentCUID = doco.clientDocument.DocumentCUID; dslAddUpdate.SourceLocation = doco.clientDocument.SourceLocation; dslAddUpdate.SourceFileName = doco.clientDocument.SourceFileName; dslAddUpdate.Location = doco.clientDocument.Location; if (dslAddUpdate.DocumentType == "FOLDER") { if ( dslAddUpdate.IsRoot == 'Y') dslAddUpdate.FileName = doco.clientDocument.FileName; else dslAddUpdate.FileName = doco.document.FileName; } else dslAddUpdate.FileName = doco.clientDocument.FileName; dslAddUpdate.SequenceNumber = doco.clientDocument.SequenceNumber; dslAddUpdate.SourceIssueNumber = doco.clientDocument.SourceIssueNumber; dslAddUpdate.ClientIssueNumber = 0; dslAddUpdate.ComboIssueNumber = doco.clientDocument.ComboIssueNumber; dslAddUpdate.Generated = 'N'; dslAddUpdate.ParentUID = doco.clientDocument.ParentUID; dslAddUpdate.RecordType = doco.clientDocument.RecordType; dslAddUpdate.IsRoot = doco.clientDocument.IsRoot; dslAddUpdate.IsFolder = doco.clientDocument.IsFolder; dslLocate = Find(doco.document.UID, doco.clientDocumentSet.UID, 'N', doco.clientDocumentSet.FKClientUID); if ( dslLocate.UID > 0 ) { // Fact: There is an existing non-voided row // Intention (1): Make it void // Intention (2): Do nothing // // Check for Intention (1) // if (doco.clientDocument.IsVoid == 'Y') { // Update row to make it voided... // SetToVoid( Utils.ClientID, doco.clientDocumentSet.UID, doco.clientDocument.UID ); } else { // Update details // dslAddUpdate.UID = doco.clientDocument.UID; Update(dslAddUpdate); // dslAddUpdate.Update(); clientDocumentUID = doco.clientDocument.UID; } } else { // if the pair does not exist, check if it is void. // If void = Y, just ignore. if (doco.clientDocument.IsVoid == 'Y') { // just ignore. The pair was not saved initially. } else { // add document to set //clientDocumentUID = dslAddUpdate.Add(); clientDocumentUID = Add( dslAddUpdate ); } } return clientDocumentUID; } /// <summary> /// Calculate the number of documents in the set /// </summary> /// <param name="clientUID"> </param> /// <param name="clientDocumentSetUID"> </param> /// <returns></returns> internal static int GetNumberOfDocuments( int clientUID, int clientDocumentSetUID ) { int DocoCount = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT COUNT(*) SETCOUNT FROM ClientDocument" + " WHERE FKClientUID = " + clientUID + " AND FKClientDocumentSetUID = " + clientDocumentSetUID ; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { DocoCount = Convert.ToInt32(reader["SETCOUNT"]); } catch (Exception) { DocoCount = 0; } } } } return DocoCount; } /// <summary> /// This method returns the complete logical path of a given Client Document. /// It walk through the structure, up, and then comes down /// It requires the root to be correctly set. /// </summary> /// <param name="clientDocument"></param> /// <returns></returns> internal static ResponseStatus GetDocumentPath( ClientDocument clientDocument ) { var rs = new ResponseStatus(); var clientDocList = new List<ClientDocument>(); string documentPath = ""; // If root is supplied, return location // if (clientDocument.IsRoot == 'Y') { // documentPath = clientDocument.Location; documentPath = "%CLIENTFOLDER%"; rs.Contents = documentPath; return rs; } int currentClientID = clientDocument.UID; int count = currentClientID; // walk up until it finds the root // while (currentClientID > 0) { var client = Read( currentClientID ); if (client == null) break; if (client.RecordType == null) break; clientDocList.Add(client); currentClientID = client.ParentUID; } // walk down building the path // for (int x = clientDocList.Count - 1;x > 0;x--) { var doco = clientDocList[x]; if (doco.IsRoot == 'Y') { documentPath = doco.Location + @"\" + doco.FileName; } else { if (doco.IsFolder == 'Y') documentPath = documentPath + @"\" + doco.FileName; } } rs.Contents = documentPath; return rs; } // ----------------------------------------------------- // Retrieve last Client UID // ----------------------------------------------------- private static int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientDocument"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Retrieve last document id for a client // ----------------------------------------------------- internal static int GetLastClientCUID( int clientUID ) { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT count(*) CNTCLIENT FROM Document WHERE FKClientUID = " + clientUID.ToString(); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["CNTCLIENT"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Retrieve Unlink Document // ----------------------------------------------------- internal void UnlinkDocument( ClientDocument clientDocument ) { // This method deletes a document set link // // 1) Look for connection that is not voided // 2) Update the IsVoid flag to "Y"; EndDate to Today string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + " EndDate = @EndDate" + ",IsVoid = @IsVoid " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = UID; command.Parameters.Add("@EndDate", MySqlDbType.DateTime).Value = DateTime.Today; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Add root folder for client // ----------------------------------------------------- internal static void AddRootFolder( ClientDocument clientDocument, int clientUID, int DocSetUID, string DestinationFolder ) { clientDocument.RecordType = "FOLDER"; clientDocument.ParentUID = 0; clientDocument.DocumentCUID = "ROOT"; clientDocument.FKClientDocumentSetUID = DocSetUID; clientDocument.FKClientUID = clientUID; clientDocument.FKDocumentUID = 1; clientDocument.FileName = DestinationFolder; clientDocument.Location = FCMConstant.SYSFOLDER.CLIENTFOLDER; clientDocument.Generated = 'N'; clientDocument.SourceIssueNumber = 1; clientDocument.SourceFileName = "Folder Source File Name"; clientDocument.SourceLocation = "Folder Source File Location"; clientDocument.StartDate = System.DateTime.Today; clientDocument.EndDate = System.DateTime.MaxValue; clientDocument.IsVoid = 'N'; clientDocument.IsLocked = 'N'; clientDocument.IsProjectPlan = "N"; clientDocument.DocumentType = MackkadoITFramework.Helper.Utils.DocumentType.FOLDER; clientDocument.ComboIssueNumber = "Root"; Add( clientDocument ); } // ----------------------------------------------------- // Fix root folder for client // ----------------------------------------------------- internal static void FixRootFolder( int clientUID, int DocSetUID) { ClientDocument clientDocument = GetRoot( clientUID, DocSetUID ); if ( clientDocument.UID < 0 ) { LogFile.WriteToTodaysLogFile("RepClientDocument.FixRootFolder: Root is empty."); return; } clientDocument.RecordType = "FOLDER"; clientDocument.ParentUID = 0; clientDocument.DocumentCUID = "ROOT"; clientDocument.FKClientDocumentSetUID = DocSetUID; clientDocument.FKClientUID = clientUID; clientDocument.FKDocumentUID = 1; clientDocument.FileName = "CLIENT"+clientUID.ToString("000000000")+"SET"+DocSetUID.ToString("0000"); clientDocument.Location = FCMConstant.SYSFOLDER.CLIENTFOLDER; clientDocument.Generated = 'N'; clientDocument.SourceIssueNumber = 1; clientDocument.SourceFileName = "Folder Source File Name"; clientDocument.SourceLocation = "Folder Source File Location"; clientDocument.StartDate = System.DateTime.Today; clientDocument.EndDate = System.DateTime.MaxValue; clientDocument.IsVoid = 'N'; clientDocument.IsLocked = 'N'; clientDocument.IsProjectPlan = "N"; clientDocument.DocumentType = MackkadoITFramework.Helper.Utils.DocumentType.FOLDER; clientDocument.ComboIssueNumber = "Root"; Update( clientDocument ); } // ----------------------------------------------------- // Prepare root folder for client // ----------------------------------------------------- internal void PrepareRootFolder( int clientUID, int DocSetUID, string DestinationFolder ) { this.RecordType = "FOLDER"; this.ParentUID = 0; this.DocumentCUID = "ROOT"; this.FKClientDocumentSetUID = DocSetUID; this.FKClientUID = clientUID; this.FKDocumentUID = 1; this.FileName = DestinationFolder; this.Location = FCMConstant.SYSFOLDER.CLIENTFOLDER; this.Generated = 'N'; this.SourceIssueNumber = 1; this.SourceFileName = "Folder Source File Name"; this.SourceLocation = "Folder Source File Location"; this.StartDate = System.DateTime.Today; this.EndDate = System.DateTime.MaxValue; this.IsVoid = 'N'; this.IsLocked = 'N'; this.IsProjectPlan = "N"; this.DocumentType = MackkadoITFramework.Helper.Utils.DocumentType.FOLDER; this.ComboIssueNumber = "Root"; } // ----------------------------------------------------- // Add new Client Document // ----------------------------------------------------- internal static int Add( ClientDocument clientDocument ) { string ret = "Client Document Added Successfully"; int _uid = 0; _uid = GetLastUID() + 1; // Default values DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO ClientDocument " + "( UID, " + " FKClientUID, " + " FKClientDocumentSetUID, " + " FKDocumentUID, " + " DocumentCUID, " + " SequenceNumber, " + " SourceLocation, " + " SourceFileName, " + " Location, " + " FileName, " + " StartDate, " + " EndDate, " + " IsVoid, " + " IsLocked, " + " IsProjectPlan, " + " DocumentType, " + " xGenerated, " + " SourceIssueNumber, " + " ClientIssueNumber, " + " ComboIssueNumber, " + " ParentUID, " + " RecordType, " + " IsRoot, " + " IsFolder " + ")" + " VALUES " + "( @UID " + ", @FKClientUID " + ", @FKClientDocumentSetUID " + ", @FKDocumentUID " + ", @DocumentCUID " + ", @SequenceNumber " + ", @SourceLocation " + ", @SourceFileName " + ", @Location " + ", @FileName " + ", @StartDate " + ", @EndDate " + ", @IsVoid " + ", @IsLocked " + ", @IsProjectPlan " + ", @DocumentType " + ", @Generated " + ", @SourceIssueNumber " + ", @ClientIssueNumber " + ", @ComboIssueNumber " + ", @ParentUID " + ", @RecordType " + ", @IsRoot " + ", @IsFolder " + ")" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add( "@FKClientUID", MySqlDbType.Int32 ).Value = clientDocument.FKClientUID; command.Parameters.Add( "@FKClientDocumentSetUID", MySqlDbType.Int32 ).Value = clientDocument.FKClientDocumentSetUID; command.Parameters.Add( "@FKDocumentUID", MySqlDbType.Int32 ).Value = clientDocument.FKDocumentUID; command.Parameters.Add( "@SequenceNumber", MySqlDbType.Int32 ).Value = clientDocument.SequenceNumber; command.Parameters.Add( "@SourceLocation", MySqlDbType.VarChar ).Value = ( string.IsNullOrEmpty( clientDocument.SourceLocation ) ) ? " " : clientDocument.SourceLocation; command.Parameters.Add( "@DocumentCUID", MySqlDbType.VarChar ).Value = ( string.IsNullOrEmpty( clientDocument.DocumentCUID ) ) ? " " : clientDocument.DocumentCUID; command.Parameters.Add( "@SourceFileName", MySqlDbType.VarChar ).Value = ( string.IsNullOrEmpty( clientDocument.SourceFileName ) ) ? " " : clientDocument.SourceFileName; command.Parameters.Add( "@Location", MySqlDbType.VarChar ).Value = ( string.IsNullOrEmpty( clientDocument.Location ) ) ? " " : clientDocument.Location; command.Parameters.Add( "@FileName", MySqlDbType.VarChar ).Value = ( string.IsNullOrEmpty( clientDocument.FileName ) ) ? " " : clientDocument.FileName; command.Parameters.Add("@StartDate", MySqlDbType.DateTime).Value = _now; command.Parameters.AddWithValue("@EndDate", "9999-12-31"); command.Parameters.Add( "@IsVoid", MySqlDbType.VarChar ).Value = clientDocument.IsVoid; command.Parameters.Add( "@IsLocked", MySqlDbType.VarChar ).Value = clientDocument.IsLocked; command.Parameters.Add( "@IsProjectPlan", MySqlDbType.VarChar ).Value = clientDocument.IsProjectPlan; command.Parameters.Add( "@DocumentType", MySqlDbType.VarChar ).Value = clientDocument.DocumentType; command.Parameters.Add( "@Generated", MySqlDbType.VarChar ).Value = clientDocument.Generated; command.Parameters.Add( "@SourceIssueNumber", MySqlDbType.Int32 ).Value = clientDocument.SourceIssueNumber; command.Parameters.Add( "@ClientIssueNumber", MySqlDbType.Int32 ).Value = clientDocument.ClientIssueNumber; command.Parameters.Add( "@ComboIssueNumber", MySqlDbType.Text ).Value = clientDocument.ComboIssueNumber; command.Parameters.Add( "@ParentUID", MySqlDbType.Decimal ).Value = clientDocument.ParentUID; command.Parameters.Add( "@RecordType", MySqlDbType.VarChar ).Value = clientDocument.RecordType; command.Parameters.Add( "@IsRoot", MySqlDbType.VarChar ).Value = clientDocument.IsRoot; command.Parameters.Add( "@IsFolder", MySqlDbType.VarChar ).Value = clientDocument.IsFolder; connection.Open(); command.ExecuteNonQuery(); } } return _uid; } // ----------------------------------------------------- // Update Client Document // ----------------------------------------------------- internal static ResponseStatus Update( ClientDocument clientDocument ) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + " SequenceNumber = @SequenceNumber" + ",SourceLocation = @SourceLocation " + ",SourceFileName = @SourceFileName " + ",Location = @Location" + ",FileName = @FileName " + ",ParentUID = @ParentUID " + ",RecordType = @RecordType " + ",IsLocked = @IsLocked" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = clientDocument.UID; command.Parameters.Add( "@SequenceNumber", MySqlDbType.Int32 ).Value = clientDocument.SequenceNumber; command.Parameters.Add( "@SourceLocation", MySqlDbType.VarChar ).Value = clientDocument.SourceLocation; command.Parameters.Add( "@SourceFileName", MySqlDbType.VarChar ).Value = clientDocument.SourceFileName; command.Parameters.Add( "@Location", MySqlDbType.VarChar ).Value = clientDocument.Location; command.Parameters.Add( "@FileName", MySqlDbType.VarChar ).Value = clientDocument.FileName; command.Parameters.Add( "@ParentUID", MySqlDbType.Int32 ).Value = clientDocument.ParentUID; command.Parameters.Add( "@RecordType", MySqlDbType.VarChar ).Value = clientDocument.RecordType; command.Parameters.Add( "@IsLocked", MySqlDbType.VarChar ).Value = clientDocument.IsLocked; try { connection.Open(); command.ExecuteNonQuery(); } catch( Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), "", "", "RepClientDocument.cs"); return new ResponseStatus( MessageType.Error ) { Message = ex.ToString(), ReturnCode = -0010, ReasonCode = 0001 }; } } } return new ResponseStatus(MessageType.Informational); } // ----------------------------------------------------- // Update Client Document // ----------------------------------------------------- internal static void UpdateFieldString( int UID, string fieldName, string contents ) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + fieldName + "= @contents "+ " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@contents", MySqlDbType.VarChar).Value = contents; connection.Open(); command.ExecuteNonQuery(); } } return; } // Physically Delete a file from windows internal static void DeleteFile( int clientDocumentUID ) { var clientDocument = Read(clientDocumentUID); var fileNamePath = Utils.getFilePathName( clientDocument.clientDocumentSet.Folder + clientDocument.Location, clientDocument.FileName ); if (File.Exists( fileNamePath )) File.Delete( fileNamePath ); } // // Set void flag // internal static void SetToVoid( int clientUID, int clientDocumentSetUID, int documentUID ) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + " IsVoid = @IsVoid" + " WHERE " + " FKClientDocumentSetUID = @FKClientDocumentSetUID " + " AND FKClientUID = @FKClientUID " + " AND FKDocumentUID = @FKDocumentUID " + " " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add( "@FKClientDocumentSetUID", MySqlDbType.Int32 ).Value = clientDocumentSetUID; command.Parameters.Add( "@FKClientUID", MySqlDbType.Int32 ).Value = clientUID; command.Parameters.Add( "@FKDocumentUID", MySqlDbType.Int32 ).Value = documentUID; command.Parameters.Add( "@IsVoid", MySqlDbType.VarChar ).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } } // // Set void flag // internal static ResponseStatus Delete( int clientUID, int clientDocumentSetUID, int clientDocumentUID ) { var ret = new ResponseStatus(); ret.Message = "Item updated successfully"; ret.ReturnCode = 0001; ret.ReasonCode = 0001; using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = ( "DELETE FROM ClientDocument " + " WHERE " + " FKClientDocumentSetUID = @FKClientDocumentSetUID " + " AND FKClientUID = @FKClientUID " + " AND UID = @UID" + " " ); try { using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add( "@FKClientDocumentSetUID", MySqlDbType.Int32 ).Value = clientDocumentSetUID; command.Parameters.Add( "@FKClientUID", MySqlDbType.Int32 ).Value = clientUID; command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = clientDocumentUID; command.Parameters.Add( "@IsVoid", MySqlDbType.VarChar ).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } catch (Exception ex) { ret.Message = "Error deleting client document."; ret.ReturnCode = -0010; ret.ReasonCode = 0001; } } return ret; } /// <summary> /// Retrieve combo issue number /// </summary> /// <param name="documentCUID"></param> /// <param name="documentVersionNumber"></param> /// <param name="clientUID"></param> /// <returns></returns> internal static string GetComboIssueNumber( string documentCUID, int documentVersionNumber, int clientUID ) { string comboIssueNumber = ""; comboIssueNumber = documentCUID + '-' + documentVersionNumber.ToString("00") + "-" + clientUID.ToString("0000") + '-' + "00"; // client issue number; return comboIssueNumber; } /// <summary> /// It sets all the destination names for a client document from source name. /// </summary> /// <param name="documentCUID"></param> /// <param name="documentVersionNumber"></param> /// <param name="clientUID"></param> /// <param name="sourceVersionNumber"> </param> /// <param name="simpleFileName"> </param> /// <returns></returns> internal static ClientDocument SetClientDestinationFile( ClientDocument clientDocument, int clientUID, string documentCUID, int sourceVersionNumber, string simpleFileName) { clientDocument.ComboIssueNumber = documentCUID + '-' + sourceVersionNumber.ToString("00") + "-" + clientUID.ToString("0000") + '-' + "00"; // client issue number; clientDocument.FileName = clientDocument.ComboIssueNumber + " " + simpleFileName; return clientDocument; } // // Update document to Generated // internal static ResponseStatus SetFlagToGenerationRequested( int clientDocumentUID, int processRequestUID ) { using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { var commandString = "UPDATE ClientDocument " + " SET " + " xGenerated = @Generated" + " ,GenerationMessage = @GenerationMessage" + " ,FKProcessRequestUID = @FKProcessRequestUID" + " WHERE UID = @UID " ; using ( var command = new MySqlCommand( commandString, connection ) ) { command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = clientDocumentUID; command.Parameters.Add( "@Generated", MySqlDbType.VarChar ).Value = "R"; command.Parameters.Add( "@GenerationMessage", MySqlDbType.VarChar ).Value = ""; command.Parameters.Add( "@FKProcessRequestUID", MySqlDbType.Int32 ).Value = processRequestUID; connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus( MessageType.Informational ); } // // Update document to Generated // internal static ResponseStatus SetGeneratedFlagVersion( ClientDocument clientDocument, char generated, decimal issueNumber, string message ) { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "UPDATE ClientDocument " + " SET " + " xGenerated = @Generated" + " ,SourceIssueNumber = @SourceIssueNumber" + " ,GenerationMessage = @GenerationMessage" + " WHERE UID = @UID " ; using (var command = new MySqlCommand(commandString, connection)) { command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = clientDocument.UID; command.Parameters.Add("@Generated", MySqlDbType.VarChar).Value = generated; command.Parameters.Add( "@SourceIssueNumber", MySqlDbType.Decimal ).Value = issueNumber; command.Parameters.Add( "@GenerationMessage", MySqlDbType.VarChar ).Value = message; connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus(MessageType.Informational); } // // Update file name // internal void UpdateFileName() { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + " FileName = @FileName" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@FileName", MySqlDbType.VarChar).Value = FileName; connection.Open(); command.ExecuteNonQuery(); } } return; } // // Update document to Generate // internal static ResponseStatus UpdateSourceFileName( ClientDocument clientDocument ) { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + " SourceFileName = @SourceFileName" + " ,ComboIssueNumber = @ComboIssueNumber" + " ,FileName = @FileName" + " ,SourceIssueNumber = @SourceIssueNumber" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = clientDocument.UID; command.Parameters.Add( "@SourceFileName", MySqlDbType.VarChar ).Value = clientDocument.SourceFileName; command.Parameters.Add( "@ComboIssueNumber", MySqlDbType.VarChar ).Value = clientDocument.ComboIssueNumber; command.Parameters.Add( "@FileName", MySqlDbType.VarChar ).Value = clientDocument.FileName; command.Parameters.Add( "@SourceIssueNumber", MySqlDbType.Int32 ).Value = clientDocument.SourceIssueNumber; connection.Open(); command.ExecuteNonQuery(); } } return new ResponseStatus(MessageType.Informational); } // ----------------------------------------------------- // Create new client document version // ----------------------------------------------------- internal static string NewVersion( ClientDocument clientDocument ) { // 24.02.2013 - The paths must be physical when dealing with web // // string ClientDocSourceFolder // 1) Create a copy of current version in the version folder // 2) Create a Client Document Issue record to point to the versioned document in version folder // 3) Update the current client document with new details (file name, issue number etc) // Copy existing version to old folder version // // Old folder comes from %VERSIONFOLDER% // var versionFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.VERSIONFOLDER); // Create a record to point to the old version // ClientDocumentVersion documentIssue = new ClientDocumentVersion(); documentIssue.FKClientDocumentUID = clientDocument.UID; documentIssue.ClientIssueNumber = clientDocument.ClientIssueNumber; // Client Version documentIssue.SourceIssueNumber = clientDocument.SourceIssueNumber; // FCM Version documentIssue.IssueNumberText = documentIssue.ClientIssueNumber.ToString("0000"); documentIssue.ComboIssueNumber = clientDocument.FileName.Substring( 0, 22 ); documentIssue.FKClientUID = clientDocument.FKClientUID; documentIssue.Location = Utils.GetVersionPath( "%VERSIONFOLDER%" + "\\Client" + clientDocument.FKClientUID.ToString( "000000000" ) + clientDocument.Location ); documentIssue.FileName = clientDocument.FileName; documentIssue.Add(); // Copy the current document into the version folder // // string sourceLocationFileName = Utils.getFilePathName(ClientDocSourceFolder + this.Location, this.FileName); string sourceLocationFileName = Utils.getFilePathName( clientDocument.Location, clientDocument.FileName ); string destinationLocationFileName = Utils.getFilePathName( documentIssue.Location, documentIssue.FileName); string destinationLocation = Utils.GetPathName( documentIssue.Location); if (string.IsNullOrEmpty(sourceLocationFileName)) { return "Location of file is empty. Please contact support."; } if (!System.IO.Directory.Exists(destinationLocation)) System.IO.Directory.CreateDirectory(destinationLocation); File.Copy(sourceLocationFileName, destinationLocationFileName, true); // Generate the new version id // Increments issue number clientDocument.ClientIssueNumber++; // Create a new file name with version on it // POL-05-01-201000006-00 FILE NAME.doc // POL-05-01-XXXXHHHHH-YY FILE NAME.doc // | | | | // | | | +---- Client Version // | | +--------- Client UID // | +------------ FCM Version // +------------------- Document Identifier = CUID // string textversion = clientDocument.DocumentCUID + '-' + clientDocument.SourceIssueNumber.ToString( "00" ) + "-" + clientDocument.FKClientUID.ToString( "000000000" ) + '-' + clientDocument.ClientIssueNumber.ToString( "00" ); // FileName includes extension (.doc, .docx, etc.) // string newFileName = textversion + ' ' + clientDocument.FileName.Substring( 23 ).Trim(); // Copy file to new name // string newFilePathName = Utils.getFilePathName( clientDocument.Location, newFileName ); File.Copy(sourceLocationFileName, newFilePathName, true); // Delete old version from main folder // File.Delete(sourceLocationFileName); // Update document details - version, name, etc // this.ClientIssueNumber = version; clientDocument.ComboIssueNumber = textversion; clientDocument.FileName = newFileName; // clientDocument.UpdateVersion(); UpdateVersion( clientDocument ); return textversion; } // ----------------------------------------------------- // Create new client document version // ----------------------------------------------------- internal static string NewVersionWeb( ClientDocument clientDocument ) { // string ClientDocSourceFolder // 1) Create a copy of current version in the version folder // 2) Create a Client Document Issue record to point to the versioned document in version folder // 3) Update the current client document with new details (file name, issue number etc) // Copy existing version to old folder version // // Old folder comes from %VERSIONFOLDER% // // var versionFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.VERSIONFOLDER ); // Create a record to point to the old version // ClientDocumentVersion documentIssue = new ClientDocumentVersion(); documentIssue.FKClientDocumentUID = clientDocument.UID; documentIssue.ClientIssueNumber = clientDocument.ClientIssueNumber; // Client Version documentIssue.SourceIssueNumber = clientDocument.SourceIssueNumber; // FCM Version documentIssue.IssueNumberText = documentIssue.ClientIssueNumber.ToString( "0000" ); documentIssue.ComboIssueNumber = clientDocument.FileName.Substring( 0, 22 ); documentIssue.FKClientUID = clientDocument.FKClientUID; documentIssue.Location = Utils.GetVersionPath( "%VERSIONFOLDER%" + "\\Client" + clientDocument.FKClientUID.ToString( "000000000" ) + clientDocument.Location ); documentIssue.FileName = clientDocument.FileName; documentIssue.Add(); // Copy the current document into the version folder // string sourceLocationFileName = Utils.getFilePathName( clientDocument.Location, clientDocument.FileName ); // Increments issue number // clientDocument.ClientIssueNumber++; // Create a new file name with version on it // POL-05-01-201000006-00 FILE NAME.doc // POL-05-01-XXXXHHHHH-YY FILE NAME.doc // | | | | // | | | +---- Client Version // | | +--------- Client UID // | +------------ FCM Version // +------------------- Document Identifier = CUID // string textversion = clientDocument.DocumentCUID + '-' + clientDocument.SourceIssueNumber.ToString( "00" ) + "-" + clientDocument.FKClientUID.ToString( "000000000" ) + '-' + clientDocument.ClientIssueNumber.ToString( "00" ); // FileName includes extension (.doc, .docx, etc.) // string newFileName = textversion + ' ' + clientDocument.FileName.Substring( 23 ).Trim(); // Update document details - version, name, etc clientDocument.ComboIssueNumber = textversion; clientDocument.FileName = newFileName; UpdateVersion( clientDocument ); return textversion; } // ----------------------------------------------------- // Update Document Version // ----------------------------------------------------- private static void UpdateVersion( ClientDocument clientDocument) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocument " + " SET " + " ClientIssueNumber = @ClientIssueNumber" + ",Location = @Location" + ",FileName = @FileName" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add( "@ClientIssueNumber", MySqlDbType.Decimal ).Value = clientDocument.ClientIssueNumber; command.Parameters.Add( "@Location", MySqlDbType.VarChar ).Value = clientDocument.Location; command.Parameters.Add( "@FileName", MySqlDbType.VarChar ).Value = clientDocument.FileName; command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = clientDocument.UID; connection.Open(); command.ExecuteNonQuery(); } } return; } // // Listing... // /// <summary> /// List documents for a client /// </summary> /// <param name="clientDocument"></param> /// <param name="clientID"></param> /// <param name="clientDocumentSetUID"></param> /// <param name="condition"></param> internal static void List( ClientDocument clientDocument, int clientID, int clientDocumentSetUID, string condition = "" ) { clientDocument.clientDocSetDocLink = new List<scClientDocSetDocLink>(); clientDocument.clientDocumentList = new List<ClientDocument>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var prefix = "CD"; var commandString = string.Format( " SELECT " + SQLConcat(prefix) + " FROM ClientDocument "+ prefix + " WHERE " + " IsVoid = 'N' " + " AND FKClientUID = {0} " + " AND FKClientDocumentSetUID = {1} " + " " + condition + " " + " ORDER BY ParentUID ASC, SequenceNumber ASC ", clientID, clientDocumentSetUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if (Convert.ToChar(reader[prefix+FCMDBFieldName.ClientDocument.IsVoid]) == 'Y') continue; var docItem = SetDocumentItem(reader, prefix); // Check if document exists // clientDocument.clientDocSetDocLink.Add( docItem ); clientDocument.clientDocumentList.Add(docItem.clientDocument); clientDocument.UID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.UID].ToString() ); clientDocument.FKClientUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKClientUID].ToString() ); clientDocument.FKClientDocumentSetUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKClientDocumentSetUID].ToString() ); } } } } } // // (STATIC) List documents for a client // internal static List<scClientDocSetDocLink> ListS( int clientID, int clientDocumentSetUID ) { var clientDocSetDocLink = new List<scClientDocSetDocLink>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { string prefix = "CD"; var commandString = string.Format( " SELECT " + SQLConcat(prefix) + " FROM ClientDocument " + prefix + " WHERE " + " IsVoid = 'N' " + " AND FKClientUID = {0} " + " AND FKClientDocumentSetUID = {1} " + " ORDER BY ParentUID ASC, SequenceNumber ASC ", clientID, clientDocumentSetUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if ( Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsVoid] ) == 'Y' ) continue; var docItem = SetDocumentItem(reader, prefix); clientDocSetDocLink.Add(docItem); } } } } return clientDocSetDocLink; } // // (STATIC) List documents for a client // internal static List<ClientDocument> ListCD( int clientID, int clientDocumentSetUID ) { var clientDocumentList = new List<ClientDocument>(); using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { string prefix = "CD"; var commandString = string.Format( " SELECT " + SQLConcat( prefix ) + " FROM ClientDocument " + prefix + " WHERE " + " IsVoid = 'N' " + " AND FKClientUID = {0} " + " AND FKClientDocumentSetUID = {1} " + " ORDER BY ParentUID ASC, SequenceNumber ASC ", clientID, clientDocumentSetUID ); using ( var command = new MySqlCommand( commandString, connection ) ) { connection.Open(); using ( MySqlDataReader reader = command.ExecuteReader() ) { while ( reader.Read() ) { // Ignore voids if ( Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsVoid] ) == 'Y' ) continue; var docItem = SetDocumentItem( reader, prefix ); clientDocumentList.Add( docItem.clientDocument ); } } } } return clientDocumentList; } internal static void ListFolders( ClientDocument clientDocument, int clientID, int clientDocumentSetUID, string condition = "" ) { string cond = " AND IsFolder = 'Y' "; List( clientDocument, clientID, clientDocumentSetUID, cond ); } // // List documents for a client // internal static void ListImpacted( ClientDocument clientDocument, Model.ModelDocument.Document document ) { clientDocument.clientDocSetDocLink = new List<scClientDocSetDocLink>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { string prefix = "CD"; var commandString = string.Format( " SELECT " + SQLConcat(prefix) + " FROM ClientDocument " + prefix + " WHERE FKDocumentUID = {0} ", document.UID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if ( Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsVoid] ) == 'Y' ) continue; var docItem = SetDocumentItem(reader, prefix); clientDocument.clientDocSetDocLink.Add( docItem ); } } } } } // ----------------------------------------------------- // Load documents in a tree // The list in tree expects that the list has been // called before to populate the instance // ----------------------------------------------------- internal static void ListInTree( ClientDocument clientDocument, TreeView fileList, string listType ) { // listType = CLIENT // listType = FCM = default; string ListType = listType; if (ListType == null) ListType = "FCM"; foreach ( var docLinkSet in clientDocument.clientDocSetDocLink ) { // Check if folder has a parent string cdocumentUID = docLinkSet.clientDocument.UID.ToString(); string cparentIUID = docLinkSet.clientDocument.ParentUID.ToString(); TreeNode treeNode = new TreeNode(); int image = 0; int imageSelected = 0; docLinkSet.clientDocument.RecordType = docLinkSet.clientDocument.RecordType.Trim(); image = Utils.GetFileImage(docLinkSet.clientDocument.SourceFilePresent, docLinkSet.clientDocument.DestinationFilePresent, docLinkSet.clientDocument.DocumentType); imageSelected = image; //if (ListType == "CLIENT") // treeNode = new TreeNode(docLinkSet.clientDocument.FileName, image, imageSelected); //else // treeNode = new TreeNode(docLinkSet.document.Name, image, imageSelected); string treenodename = docLinkSet.document.DisplayName; if (string.IsNullOrEmpty(treenodename)) treenodename = docLinkSet.clientDocument.FileName; if (string.IsNullOrEmpty(treenodename)) treenodename = "Error: Name not found"; treeNode = new TreeNode(treenodename, image, imageSelected); if (docLinkSet.clientDocument.ParentUID == 0) { treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find(cparentIUID, true); if (node.Count() > 0) { treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; node[0].Nodes.Add(treeNode); } else { // Add Element to the root // treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add(treeNode); } } } } // ----------------------------------- // List project plans // ----------------------------------- internal static void ListProjectPlans( ClientDocument clientDocument, int clientID, int clientDocumentSetUID ) { clientDocument.clientDocSetDocLink = new List<scClientDocSetDocLink>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { string prefix = "CD"; var commandString = string.Format( " SELECT " + SQLConcat(prefix) + " FROM ClientDocument " +prefix + " WHERE FKClientUID = {0} " + " AND FKClientDocumentSetUID = {1} " + " AND IsProjectPlan = 'Y' " + " AND IsVoid = 'N' " + " ORDER BY ParentUID ASC, SequenceNumber ASC ", clientID, clientDocumentSetUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if (Convert.ToChar(reader[prefix + FCMDBFieldName.ClientDocument.IsVoid]) == 'Y') continue; var docItem = SetDocumentItem(reader, prefix); clientDocument.clientDocSetDocLink.Add(docItem); } } } } } // ----------------------------------------------------- // Load project plan in a tree // // ----------------------------------------------------- internal static void ListProjectPlanInTree( ClientDocument clientDocument, int clientID, int clientDocumentSetUID, TreeView fileList ) { int image = FCMConstant.Image.Document; int imageSelected = FCMConstant.Image.Document; ListProjectPlans( clientDocument, clientID, clientDocumentSetUID ); foreach ( var projectPlan in clientDocument.clientDocSetDocLink ) { // // load plan in tree // var treeNode = new TreeNode(projectPlan.document.Name, image, imageSelected); treeNode.Tag = projectPlan; treeNode.Name = projectPlan.clientDocument.UID.ToString(); fileList.Nodes.Add(treeNode); // List contents of the project plan // var cdl = new ClientDocumentLinkList(); // cdl.ListChildrenDocuments( projectPlan.clientDocument.UID ); if (clientID <= 0 || projectPlan.clientDocumentSet.UID <= 0 || projectPlan.document.UID <= 0) { MessageBox.Show("Error listing children document. Please contact support"); return; } cdl.ListChildrenDocuments(clientUID: clientID, clientDocumentSetUID: projectPlan.clientDocumentSet.UID, documentUID: projectPlan.document.UID, type: FCMConstant.DocumentLinkType.PROJECTPLAN); foreach (var planItem in cdl.clientDocumentLinkList) { // // load contents of the project plan in tree // var planItemNode = new TreeNode(planItem.childClientDocument.FileName, image, imageSelected); planItemNode.Tag = planItem; planItemNode.Name = planItem.childClientDocument.UID.ToString(); treeNode.Nodes.Add(planItemNode); } } } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> private static string SQLConcat( string tablePrefix ) { string ret = " " + tablePrefix + "."+ FCMDBFieldName.ClientDocument.UID + " " + tablePrefix + FCMDBFieldName.ClientDocument.UID + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.DocumentCUID + " " + tablePrefix + FCMDBFieldName.ClientDocument.DocumentCUID + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.FKClientUID + " " + tablePrefix + FCMDBFieldName.ClientDocument.FKClientUID + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.FKClientDocumentSetUID + " " + tablePrefix + FCMDBFieldName.ClientDocument.FKClientDocumentSetUID + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.FKDocumentUID + " " + tablePrefix + FCMDBFieldName.ClientDocument.FKDocumentUID + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.SourceLocation + " " + tablePrefix + FCMDBFieldName.ClientDocument.SourceLocation + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.SourceFileName + " " + tablePrefix + FCMDBFieldName.ClientDocument.SourceFileName + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.Location + " " + tablePrefix + FCMDBFieldName.ClientDocument.Location + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.FileName + " " + tablePrefix + FCMDBFieldName.ClientDocument.FileName + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.SourceIssueNumber + " " + tablePrefix + FCMDBFieldName.ClientDocument.SourceIssueNumber + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.ClientIssueNumber + " " + tablePrefix + FCMDBFieldName.ClientDocument.ClientIssueNumber + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.SequenceNumber + " " + tablePrefix + FCMDBFieldName.ClientDocument.SequenceNumber + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.Generated + " " + tablePrefix + FCMDBFieldName.ClientDocument.Generated + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.StartDate + " " + tablePrefix + FCMDBFieldName.ClientDocument.StartDate + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.EndDate + " " + tablePrefix + FCMDBFieldName.ClientDocument.EndDate + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.RecordType + " " + tablePrefix + FCMDBFieldName.ClientDocument.RecordType + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.ParentUID + " " + tablePrefix + FCMDBFieldName.ClientDocument.ParentUID + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.IsProjectPlan + " " + tablePrefix + FCMDBFieldName.ClientDocument.IsProjectPlan + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.DocumentType + " " + tablePrefix + FCMDBFieldName.ClientDocument.DocumentType + "," + tablePrefix + "."+ FCMDBFieldName.ClientDocument.ComboIssueNumber + " " + tablePrefix + FCMDBFieldName.ClientDocument.ComboIssueNumber + "," + tablePrefix + "." + FCMDBFieldName.ClientDocument.IsVoid + " " + tablePrefix + FCMDBFieldName.ClientDocument.IsVoid + "," + tablePrefix + "." + FCMDBFieldName.ClientDocument.IsLocked + " " + tablePrefix + FCMDBFieldName.ClientDocument.IsLocked + "," + tablePrefix + "." + FCMDBFieldName.ClientDocument.IsRoot + " " + tablePrefix + FCMDBFieldName.ClientDocument.IsRoot + "," + tablePrefix + "." + FCMDBFieldName.ClientDocument.IsFolder + " " + tablePrefix + FCMDBFieldName.ClientDocument.IsFolder + "," + tablePrefix + "." + FCMDBFieldName.ClientDocument.GenerationMessage + " " + tablePrefix + FCMDBFieldName.ClientDocument.GenerationMessage; return ret; } /// <summary> /// partial code /// </summary> /// <param name="reader"></param> /// <param name="prefix"></param> /// <param name="checkForSourceFile"></param> /// <param name="checkForDestinationFile"></param> /// <returns></returns> private static scClientDocSetDocLink SetDocumentItem( MySqlDataReader reader, string prefix, bool checkForSourceFile = false, bool checkForDestinationFile = false ) { var docItem = new scClientDocSetDocLink(); // Get document // docItem.document = new Model.ModelDocument.Document(); docItem.document.UID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKDocumentUID] ); // docItem.document.Read(includeVoid: true); docItem.document = RepDocument.Read( false, docItem.document.UID ); // Get Client Document Set // docItem.clientDocumentSet = new ClientDocumentSet(); docItem.clientDocumentSet.UID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKClientDocumentSetUID].ToString() ); docItem.clientDocumentSet.FKClientUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKClientUID].ToString() ); docItem.clientDocumentSet.Read(); // Set Client Document // docItem.clientDocument = new ClientDocument(); docItem.clientDocument.UID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.UID].ToString() ); docItem.clientDocument.DocumentCUID = reader [prefix + FCMDBFieldName.ClientDocument.DocumentCUID].ToString(); docItem.clientDocument.FKClientUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKClientUID].ToString() ); docItem.clientDocument.FKClientDocumentSetUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKClientDocumentSetUID].ToString() ); docItem.clientDocument.FKDocumentUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.FKDocumentUID].ToString() ); docItem.clientDocument.SourceLocation = reader [prefix + FCMDBFieldName.ClientDocument.SourceLocation].ToString(); docItem.clientDocument.SourceFileName = reader [prefix + FCMDBFieldName.ClientDocument.SourceFileName].ToString(); docItem.clientDocument.Location = reader [prefix + FCMDBFieldName.ClientDocument.Location].ToString(); docItem.clientDocument.FileName = reader [prefix + FCMDBFieldName.ClientDocument.FileName].ToString(); docItem.clientDocument.SourceIssueNumber = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.SourceIssueNumber].ToString() ); docItem.clientDocument.ClientIssueNumber = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.ClientIssueNumber].ToString() ); docItem.clientDocument.SequenceNumber = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.SequenceNumber].ToString() ); docItem.clientDocument.Generated = Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.Generated] ); docItem.clientDocument.StartDate = Convert.ToDateTime( reader [prefix + FCMDBFieldName.ClientDocument.StartDate].ToString() ); docItem.clientDocument.RecordType = reader [prefix + FCMDBFieldName.ClientDocument.RecordType].ToString(); //docItem.clientDocument.RecordType = docItem.clientDocument.RecordType.Trim(); docItem.clientDocument.ParentUID = Convert.ToInt32( reader [prefix + FCMDBFieldName.ClientDocument.ParentUID].ToString() ); docItem.clientDocument.IsProjectPlan = reader [prefix + FCMDBFieldName.ClientDocument.IsProjectPlan].ToString(); docItem.clientDocument.DocumentType = reader [prefix + FCMDBFieldName.ClientDocument.DocumentType].ToString(); docItem.clientDocument.ComboIssueNumber = reader [prefix + FCMDBFieldName.ClientDocument.ComboIssueNumber].ToString(); docItem.clientDocument.IsVoid = Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsVoid].ToString() ); docItem.clientDocument.IsRoot = Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsRoot].ToString() ); docItem.clientDocument.IsFolder = Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsFolder].ToString() ); docItem.clientDocument.IsLocked = Convert.ToChar( reader [prefix + FCMDBFieldName.ClientDocument.IsLocked].ToString() ); docItem.clientDocument.GenerationMessage = reader [prefix + FCMDBFieldName.ClientDocument.GenerationMessage].ToString(); if ( checkForSourceFile ) { // SOURCE FILE is present? // docItem.clientDocument.SourceFilePresent = 'N'; if ( string.IsNullOrEmpty( docItem.clientDocument.SourceLocation ) ) { docItem.clientDocument.SourceFilePresent = 'N'; } else { string filePathName = Utils.getFilePathName( docItem.clientDocument.SourceLocation, docItem.clientDocument.SourceFileName ); // This is the source client file name // string clientSourceFileLocationName = Utils.getFilePathName( docItem.clientDocument.SourceLocation.Trim(), docItem.clientDocument.SourceFileName.Trim() ); if ( File.Exists( clientSourceFileLocationName ) ) { docItem.clientDocument.SourceFilePresent = 'Y'; } } } if ( checkForDestinationFile ) { // DESTINATION FILE is present? // docItem.clientDocument.DestinationFilePresent = 'N'; if ( string.IsNullOrEmpty( docItem.clientDocument.Location ) ) { docItem.clientDocument.DestinationFilePresent = 'N'; } else { string filePathName = Utils.getFilePathName( docItem.clientDocument.Location, docItem.clientDocument.FileName ); // This is the destination client file name // string clientDestinationFileLocationName = Utils.getFilePathName( docItem.clientDocument.Location.Trim(), docItem.clientDocument.FileName.Trim() ); if ( File.Exists( clientDestinationFileLocationName ) ) { docItem.clientDocument.DestinationFilePresent = 'Y'; } } } try { docItem.clientDocument.EndDate = Convert.ToDateTime( reader [prefix + FCMDBFieldName.ClientDocument.EndDate].ToString() ); } catch { docItem.clientDocument.EndDate = System.DateTime.MaxValue; } return docItem; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Interfaces; using MackkadoITFramework.APIDocument; using MackkadoITFramework.Utils; using Word; using Excel = Microsoft.Office.Interop.Excel; using WordNet = Microsoft.Office.Interop.Word; using Application = Microsoft.Office.Interop.Word.Application; using System.IO; namespace FCMMySQLBusinessLibrary { public class WordReport { object oEndOfDoc = "\\endofdoc"; private int clientID; private int clientDocSetID; private object vkFalse; private IOutputMessage uioutput; private Word.Application vkWordApp; private WordNet._Application oApplication; private Excel.Application vkExcelApp; private ReportMetadataList clientMetadata; private List<WordDocumentTasks.TagStructure> ts; private ClientDocumentSet cds; private double valueForProgressBar; private string startTime; public Client client; public string FileName; public string FullFileNamePath; int row; public WordReport(int ClientID, int ClientDocSetID, IOutputMessage UIoutput = null, string OverrideDocuments = null) { row = 1; // Set private attributes clientID = ClientID; clientDocSetID = ClientDocSetID; uioutput = UIoutput; // Instantiate Word // vkFalse = false; vkWordApp = new Word.Application(); // Make it not visible vkWordApp.Visible = false; vkExcelApp = new Excel.Application(); // Make it not visible vkExcelApp.Visible = false; // Make it not visible oApplication = new Application(); oApplication.Visible = false; // Get Metadata for client clientMetadata = new ReportMetadataList(); clientMetadata.ListMetadataForClient(clientID); ts = new List<WordDocumentTasks.TagStructure>(); // Load variables/ metadata into memory // #region ClientMetadata foreach (ReportMetadata metadata in clientMetadata.reportMetadataList) { // Retrieve value for the field selected // string value = metadata.GetValue(); // If the field is not enabled, the program has to replace the value with spaces. // var valueOfTag = metadata.Enabled == 'Y' ? value : string.Empty; // When the field is an image and it is not enable, do not include the "No image" icon in the list // if (metadata.InformationType == MackkadoITFramework.Helper.Utils.InformationType.IMAGE && metadata.Enabled == 'N') continue; ts.Add(new WordDocumentTasks.TagStructure() { TagType = metadata.InformationType, Tag = metadata.FieldCode, TagValue = valueOfTag }); } #endregion ClientMetadata // Get Client Document Set Details // To get the source and destination folders cds = new ClientDocumentSet(); cds.Get(clientID, clientDocSetID); valueForProgressBar = 0; startTime = System.DateTime.Now.ToString(); client = new Client(); ClientReadRequest crr = new ClientReadRequest(); crr.clientUID = clientID; var response = BUSClient.ClientRead(crr); client = response.client; } ~WordReport() { oApplication.Quit(); vkWordApp.Quit( SaveChanges: ref vkFalse, OriginalFormat: ref vkFalse, RouteDocument: ref vkFalse ); vkExcelApp.Quit(); } /// <summary> /// Generate register of systems document using existing file. /// </summary> /// <param name="tv"></param> /// <param name="clientFolder"></param> /// <param name="fileName"></param> /// <returns></returns> public ResponseStatus RegisterOfSytemDocuments2( TreeView tv, string clientFolder, string fileName, string processName, string userID ) { uioutput.AddOutputMessage( "Starting Register of Systems Documents generation...", processName, userID ); uioutput.AddOutputMessage( clientFolder, processName, userID ); uioutput.AddOutputMessage( fileName, processName, userID ); ResponseStatus ret = new ResponseStatus(); object oMissing = System.Reflection.Missing.Value; object vkMissing = System.Reflection.Missing.Value; object vkReadOnly = false; object vkVisiblefalse = false; object vkFalse = false; var pastPlannedActivities = string.Empty; //Start Word and open the document. //WordNet._Application oApplication = new Application { Visible = false }; // string clientDestinationFileLocation = document.clientDocument.Location.Trim(); string clientDestinationFileLocation = clientFolder; //string clientDestinationFileLocationName = Utils.getFilePathName( // clientDestinationFileLocation, document.clientDocument.FileName.Trim() ); string clientDestinationFileLocationName = Utils.getFilePathName( clientDestinationFileLocation, fileName.Trim() ); object destinationFileName = clientDestinationFileLocationName; if ( !File.Exists( clientDestinationFileLocationName ) ) { uioutput.AddOutputMessage( "File doesn't exist " + destinationFileName, processName: processName, userID: userID ); uioutput.AddErrorMessage( "File doesn't exist " + destinationFileName, processName:processName, userID:userID ); var responseerror = new ResponseStatus(MessageType.Error); responseerror.Message = "File doesn't exist " + destinationFileName; return responseerror; } WordNet._Document oDoc; try { uioutput.AddOutputMessage( "Opening document in Word... " + destinationFileName, processName:processName, userID:userID ); oDoc = oApplication.Documents.Open( ref destinationFileName, ref vkMissing, ref vkFalse, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisiblefalse ); } catch ( Exception ex ) { var responseerror = new ResponseStatus( MessageType.Error ); responseerror.ReturnCode = -1; responseerror.ReasonCode = 1000; responseerror.Message = "Error copying file."; responseerror.Contents = ex; return responseerror; } if ( oDoc.ReadOnly ) { if ( uioutput != null ) uioutput.AddOutputMessage( "(Word) File is Read-only contact support: " + destinationFileName, processName, userID ); oDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject( oDoc ); var responseerror = new ResponseStatus( MessageType.Error ); responseerror.Message = "(Word) File is Read-only contact support: " + destinationFileName; return responseerror; } try { if ( uioutput != null ) uioutput.AddOutputMessage( "Saving document in Word... " + destinationFileName, processName, userID ); oDoc.Save(); } catch (Exception ex) { if ( uioutput != null ) uioutput.AddOutputMessage( "Error saving file " + clientDestinationFileLocationName, processName, userID ); var responseerror = new ResponseStatus( MessageType.Error ); responseerror.Message = "Error saving file " + clientDestinationFileLocationName; return responseerror; } string msg = ">>> Opening file... " + destinationFileName; if ( uioutput != null ) uioutput.AddOutputMessage( msg, processName, userID ); PrintToWord( oDoc, " ", 8, 1 ); WordNet.Range wrdRng; WordNet.Table oTable; wrdRng = oDoc.Bookmarks.get_Item( oEndOfDoc ).Range; int rowCount = 30; // Get number of rows for a client document, client document set // // var cds = new BUSClientDocumentSet( Utils.ClientID, Utils.ClientSetID XXXXXXXXXXXXXXX ); var cds = new BUSClientDocumentSet( clientID, clientDocSetID ); rowCount = cds.DocumentCount; if ( rowCount < 1 ) return new ResponseStatus( MessageType.Error ); oTable = oDoc.Tables.Add( wrdRng, rowCount, 8, ref vkFalse, ref vkFalse ); oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlack; oTable.Borders.InsideLineStyle = WordNet.WdLineStyle.wdLineStyleDouble; oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlueGray; oTable.Borders.OutsideLineStyle = WordNet.WdLineStyle.wdLineStyleEmboss3D; oTable.Rows [1].HeadingFormat = -1; WordNet.Row headingRow = oTable.Rows [1]; ApplyHeadingStyle( headingRow.Cells [1], 200 ); headingRow.Cells [1].Range.Text = "Directory"; ApplyHeadingStyle( headingRow.Cells [2], 60 ); headingRow.Cells [2].Range.Text = "Sub Directory"; ApplyHeadingStyle( headingRow.Cells [3], 80 ); headingRow.Cells [3].Range.Text = "Document Number"; ApplyHeadingStyle( headingRow.Cells [4], 30 ); headingRow.Cells [4].Range.Text = "Sml"; ApplyHeadingStyle( headingRow.Cells [5], 40 ); headingRow.Cells [5].Range.Text = "Med"; ApplyHeadingStyle( headingRow.Cells [6], 30 ); headingRow.Cells [6].Range.Text = "Lrg"; ApplyHeadingStyle( headingRow.Cells [7], 50 ); headingRow.Cells [7].Range.Text = "Version"; ApplyHeadingStyle( headingRow.Cells [8], 200 ); headingRow.Cells [8].Range.Text = "Document Name"; int line = 0; foreach ( var treeNode in tv.Nodes ) { line++; WriteLineToRoSD( tv.Nodes [0], oDoc, oTable, prefix: "", parent: "", seqnum: line ); } msg = ">>> End "; if ( uioutput != null ) uioutput.AddOutputMessage( msg, processName, userID ); PrintToWord( oDoc, " ", 12, 1 ); try { oDoc.Save(); } catch ( Exception ex ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Error saving file again... " + clientDestinationFileLocationName, processName, userID ); var responseerror = new ResponseStatus( MessageType.Error ); responseerror.Message = "Error saving file again... " + clientDestinationFileLocationName; return responseerror; } oDoc.Close(); ResponseStatus goodresponse = new ResponseStatus(MessageType.Informational); goodresponse.Message = "Document SRG-01 generated successfully."; return goodresponse; } private void WriteLineToRoSD(TreeNode tn, WordNet._Document oDoc, WordNet.Table oTable, string prefix="", string parent="", int seqnum=0) { if (tn.Tag == null || tn.Tag.GetType().Name != "scClientDocSetDocLink") { // still need to check subnodes } else { int x = 0; foreach (TreeNode node in tn.Nodes) { x++; row++; scClientDocSetDocLink documentClient = (scClientDocSetDocLink)node.Tag; string currentParent = ""; if ( string.IsNullOrEmpty( parent ) ) { currentParent = x.ToString(); } else { currentParent = parent + "." + x.ToString(); } // First column oTable.Cell( row, 1 ).Width = 200; if (documentClient.document.RecordType == "FOLDER") oTable.Cell( row, 1 ).Range.Text = documentClient.document.Name; else oTable.Cell( row, 1 ).Range.Text = ""; oTable.Cell( row, 2 ).Width = 60; oTable.Cell( row, 2 ).Range.Text = ""; // Sub Directory oTable.Cell( row, 3 ).Width = 80; if ( documentClient.document.RecordType == "DOCUMENT" ) oTable.Cell( row, 3 ).Range.Text = prefix + documentClient.document.CUID; else oTable.Cell( row, 3 ).Range.Text = ""; oTable.Cell( row, 4 ).Width = 30; oTable.Cell( row, 4 ).Range.Text = ""; // Sml oTable.Cell( row, 5 ).Width = 40; oTable.Cell( row, 5 ).Range.Text = ""; // Med oTable.Cell( row, 6 ).Width = 30; oTable.Cell( row, 6 ).Range.Text = ""; // Lrg oTable.Cell(row, 7).Width = 50; if ( documentClient.document.RecordType == "DOCUMENT" ) oTable.Cell( row, 7 ).Range.Text = prefix + documentClient.document.IssueNumber.ToString( "000" ); else oTable.Cell( row, 7 ).Range.Text = ""; oTable.Cell( row, 8 ).Width = 200; if ( documentClient.document.RecordType == "DOCUMENT" ) oTable.Cell(row, 8).Range.Text = prefix + documentClient.document.SimpleFileName; else oTable.Cell( row, 8 ).Range.Text = ""; if ( uioutput != null ) uioutput.AddOutputMessage( documentClient.document.Name, "", ""); if ( node.Nodes.Count > 0 ) WriteLineToRoSD( node, oDoc, oTable, prefix: "", parent: currentParent, seqnum: x ); } } } private void WriteLineToRoSDOld( TreeNode tn, WordNet._Document oDoc, WordNet.Table oTable, string prefix = "", string parent = "", int seqnum = 0 ) { if ( tn.Tag == null || tn.Tag.GetType().Name != "scClientDocSetDocLink" ) { // still need to check subnodes } else { int x = 0; foreach ( TreeNode node in tn.Nodes ) { x++; row++; scClientDocSetDocLink documentClient = (scClientDocSetDocLink) node.Tag; // First column string currentParent = ""; if ( string.IsNullOrEmpty( parent ) ) { currentParent = x.ToString(); } else { currentParent = parent + "." + x.ToString(); } oTable.Cell( row, 1 ).Width = 30; oTable.Cell( row, 1 ).Range.Text = currentParent; oTable.Cell( row, 2 ).Width = 30; System.Drawing.Bitmap bitmap1 = Properties.Resources.FolderIcon; if ( documentClient.document.RecordType.Trim() == FCMConstant.RecordType.FOLDER ) { bitmap1 = Properties.Resources.FolderIcon; } else { bitmap1 = Properties.Resources.WordIcon; if ( documentClient.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL ) bitmap1 = Properties.Resources.ExcelIcon; if ( documentClient.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.PDF ) bitmap1 = Properties.Resources.PDFIcon; } Clipboard.SetImage( bitmap1 ); oTable.Cell( row, 2 ).Range.Paste(); oTable.Cell( row, 3 ).Width = 60; oTable.Cell( row, 3 ).Range.Text = prefix + documentClient.document.CUID; oTable.Cell( row, 4 ).Width = 50; oTable.Cell( row, 4 ).Range.Text = prefix + documentClient.document.IssueNumber.ToString( "000" ); oTable.Cell( row, 5 ).Width = 300; oTable.Cell( row, 5 ).Range.Text = prefix + documentClient.document.Name; oTable.Cell( row, 6 ).Width = 100; oTable.Cell( row, 6 ).Range.Text = "???"; if ( uioutput != null ) uioutput.AddOutputMessage( documentClient.document.Name, "", ""); if ( node.Nodes.Count > 0 ) WriteLineToRoSD( node, oDoc, oTable, prefix: "", parent: currentParent, seqnum: x ); } } } private static void ApplyHeadingStyle(WordNet.Cell cell, int width = 300) { cell.Width = width; cell.Range.Font.Name = "Arial"; cell.Range.Font.Size = 10; cell.Range.Font.Bold = 1; } private static void ApplyContentsStyle(WordNet.Cell cell, WordNet.WdCellVerticalAlignment verticalAlignment = WordNet.WdCellVerticalAlignment.wdCellAlignVerticalCenter) { cell.VerticalAlignment = verticalAlignment; cell.Range.Font.Name = "Arial"; cell.Range.Font.Size = 8; cell.Range.Font.Bold = 0; } private void PrintToWord(WordNet._Document oDoc, string toPrint, int fontSize, int bold, string align = FCMWordAlign.LEFT) { WordNet.WdParagraphAlignment walign = WordNet.WdParagraphAlignment.wdAlignParagraphLeft; if (align == FCMWordAlign.CENTER) walign = WordNet.WdParagraphAlignment.wdAlignParagraphCenter; if (align == FCMWordAlign.RIGHT) walign = WordNet.WdParagraphAlignment.wdAlignParagraphRight; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; WordNet.Paragraph oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Font.Name = "Arial"; oPara.Range.Font.Bold = bold; oPara.Range.Font.Size = fontSize; oPara.Range.Text = toPrint; oPara.Range.InsertParagraphAfter(); oPara.Alignment = walign; } private struct FCMWordAlign { public const string LEFT = "LEFT"; public const string RIGHT = "RIGHT"; public const string CENTER = "CENTER"; } /// <summary> /// Generate word document with register of system documents /// </summary> /// <param name="tv"></param> public string RegisterOfSytemDocumentsXXX( TreeView tv, string clientFolder, string clientName, string processName , string userID) { object oMissing = System.Reflection.Missing.Value; var pastPlannedActivities = string.Empty; //Start Word and create a new document. WordNet._Application oWord = new Application { Visible = false }; WordNet._Document oDoc = oWord.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing ); oDoc.PageSetup.Orientation = WordNet.WdOrientation.wdOrientLandscape; //PrintToWord(oDoc, "Register of System Documents", 16, 0, FCMWordAlign.CENTER); //PrintToWord(oDoc, " ", 8, 0); // Locate client folder // string clientFileLocationName = Utils.getFilePathName( @"%TEMPLATEFOLDER%\ClientSource\", "ROS-001 Register Of System Documents.doc"); FullFileNamePath = clientFileLocationName; FileName = "RegisterOfSystemDocuments.doc"; if ( File.Exists( clientFileLocationName ) ) { // Delete file try { File.Delete( clientFileLocationName ); uioutput.AddOutputMessage( "File replaced: " + clientFileLocationName, processName: processName, userID: userID ); } catch ( Exception ) { uioutput.AddOutputMessage( "Error deleting file " + clientFileLocationName, processName: processName, userID: userID ); uioutput.AddErrorMessage( "Error deleting file " + clientFileLocationName, processName: processName, userID: userID ); return clientFileLocationName; } } // string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetTempFileName(), "doc")); oDoc.SaveAs( clientFileLocationName ); string msg = ">>> Generating file... "; if ( uioutput != null ) uioutput.AddOutputMessage( msg, processName: processName, userID: userID ); PrintToWord( oDoc, " ", 8, 1 ); WordNet.Range wrdRng; WordNet.Table oTable; wrdRng = oDoc.Bookmarks.get_Item( oEndOfDoc ).Range; int rowCount = 30; foreach ( Section wordSection in oDoc.Sections ) { HeaderFooter footer = wordSection.Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ); footer.Range.Select(); footer.Range.Text = FullFileNamePath; footer.PageNumbers.Add(); HeaderFooter header = wordSection.Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ); header.Range.Select(); //header.Range.Text = client.Name + " Register of System Documents " ; header.Range.Font.Size = 20; header.Range.Cells.Add( client.Name ); header.Range.Cells.Add( "Register of System Documents" ); oWord.Selection.Paragraphs [1].Alignment = WordNet.WdParagraphAlignment.wdAlignParagraphLeft; } // Get number of rows for a client document, client document set // var cds = new BUSClientDocumentSet( Utils.ClientID, Utils.ClientSetID ); rowCount = cds.DocumentCount; if ( rowCount < 1 ) return clientFileLocationName; oTable = oDoc.Tables.Add( wrdRng, rowCount, 8, ref vkFalse, ref vkFalse ); oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlack; oTable.Borders.InsideLineStyle = WordNet.WdLineStyle.wdLineStyleDouble; oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlueGray; oTable.Borders.OutsideLineStyle = WordNet.WdLineStyle.wdLineStyleEmboss3D; //oTable.Borders.InsideLineWidth = WordNet.WdLineWidth.wdLineWidth050pt; //oTable.Borders.OutsideLineWidth = WordNet.WdLineWidth.wdLineWidth025pt; //oTable.Borders.InsideColor = WordNet.WdColor.wdColorAutomatic; //oTable.Borders.OutsideColor = WordNet.WdColor.wdColorAutomatic; oTable.Rows [1].HeadingFormat = -1; WordNet.Row headingRow = oTable.Rows [1]; ApplyHeadingStyle( headingRow.Cells [1], 200 ); headingRow.Cells [1].Range.Text = "Directory"; ApplyHeadingStyle( headingRow.Cells [2], 60 ); headingRow.Cells [2].Range.Text = "Sub Directory"; ApplyHeadingStyle( headingRow.Cells [3], 80 ); headingRow.Cells [3].Range.Text = "Document Number"; ApplyHeadingStyle( headingRow.Cells [4], 30 ); headingRow.Cells [4].Range.Text = "Sml"; ApplyHeadingStyle( headingRow.Cells [5], 40 ); headingRow.Cells [5].Range.Text = "Med"; ApplyHeadingStyle( headingRow.Cells [6], 30 ); headingRow.Cells [6].Range.Text = "Lrg"; ApplyHeadingStyle( headingRow.Cells [7], 50 ); headingRow.Cells [7].Range.Text = "Version"; ApplyHeadingStyle( headingRow.Cells [8], 200 ); headingRow.Cells [8].Range.Text = "Document Name"; int line = 0; foreach ( var treeNode in tv.Nodes ) { line++; WriteLineToRoSD( tv.Nodes [0], oDoc, oTable, prefix: "", parent: "", seqnum: line ); } msg = ">>> End "; if ( uioutput != null ) uioutput.AddOutputMessage( msg, processName, userID ); PrintToWord( oDoc, " ", 12, 1 ); oDoc.Save(); oDoc.Close(); oWord.Visible = true; oWord.Documents.Open( FileName: clientFileLocationName ); oWord.Activate(); return clientFileLocationName; } } } <file_sep>using System; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentSetDocument { public int UID; public int FKDocumentUID; public int FKDocumentSetUID; public string Location; public DateTime StartDate; public DateTime EndDate; public char IsVoid; public int FKParentDocumentUID; public int FKParentDocumentSetUID; public int SequenceNumber; public void LinkDocument(DocumentSet documentSet, Model.ModelDocument.Document document) { // This method creates a document set link // // It links a document to a document set // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO DocumentSetDocument " + "(UID "+ ",FKDocumentUID " + ",FKDocumentSetUID" + ",SequenceNumber" + ",Location" + ",StartDate" + ",EndDate" + ",IsVoid" + ",FKParentDocumentUID" + ",FKParentDocumentSetUID" + ")" + " VALUES " + "( @UID " + ", @FKDocumentUID " + ", @FKDocumentSetUID " + ", @SequenceNumber" + ", @Location" + ", @StartDate" + ", @EndDate" + ", @IsVoid" + ", @FKParentDocumentUID" + ", @FKParentDocumentSetUID" + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@FKDocumentUID", MySqlDbType.Int32).Value = FKDocumentUID; command.Parameters.Add("@FKDocumentSetUID", MySqlDbType.Int32).Value = FKDocumentSetUID; command.Parameters.Add("@SequenceNumber", MySqlDbType.Int32).Value = SequenceNumber; command.Parameters.Add("@Location", MySqlDbType.Text).Value = Location; command.Parameters.Add("@StartDate", MySqlDbType.DateTime).Value = StartDate; command.Parameters.Add("@EndDate", MySqlDbType.DateTime).Value = EndDate; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = IsVoid; command.Parameters.Add("@FKParentDocumentUID", MySqlDbType.Int32).Value = FKParentDocumentUID; command.Parameters.Add("@FKParentDocumentSetUID", MySqlDbType.Int32).Value = documentSet.UID; connection.Open(); command.ExecuteNonQuery(); } } return; } public void UnlinkDocument(DocumentSet documentSet, Model.ModelDocument.Document document) { // This method deletes a document set link // // 1) Look for connection that is not voided // 2) Update the IsVoid flag to "Y"; EndDate to Today string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE DocumentSetDocument " + " SET " + " EndDate = @EndDate" + ",IsVoid = @IsVoid " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = UID; command.Parameters.Add("@EndDate", MySqlDbType.DateTime).Value = DateTime.Today; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } public void LinkDocumentListToSet(ListOfscDocoSetDocumentLink docListToLink) { // for each document in the list // check if it is already linked with document set // if it is not linked, add a new link record // otherwise, ignore link. foreach (var doco in docListToLink.list) { DocumentSetDocument dslLocate = new DocumentSetDocument(); dslLocate.StartDate = DateTime.Today; dslLocate.IsVoid = 'N'; dslLocate.FKDocumentUID = doco.document.UID; dslLocate.FKDocumentSetUID = doco.documentSet.UID; if (dslLocate.Find(doco.document.UID, doco.documentSet.UID, 'N' )) { // Fact: There is an existing non-voided row // Intention (1): Make it void // Intention (2): Do nothing // // Check for Intention (1) // if (doco.DocumentSetDocument.IsVoid == 'Y') { // Update row to make it voided... // Update(doco.DocumentSetDocument.UID); } // else, do nothing } else { // if the pair does not exist, check if it is void. // If void = Y, just ignore. if (doco.DocumentSetDocument.IsVoid == 'Y') { // just ignore. The pair was not saved initially. } else { // add document to set DocumentSetDocument dslAdd = new DocumentSetDocument(); dslAdd.StartDate = DateTime.Today; dslAdd.IsVoid = 'N'; dslAdd.FKDocumentUID = doco.document.UID; dslAdd.FKDocumentSetUID = doco.documentSet.UID; dslAdd.Add(); } } } } // ----------------------------------------------------- // Get DocumentSetDocument details // ----------------------------------------------------- public bool Read(bool readVoid) { // // EA SQL database // bool ret = false; string voidRead = ""; if (!readVoid) { voidRead = "AND IsVoid <> 'Y'"; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKDocumentUID " + " ,FKDocumentSetUID " + " ,StartDate " + " ,EndDate " + " ,IsVoid " + " FROM DocumentSetDocument" + " WHERE UID = '{0}' "+ voidRead , this.UID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32( reader["UID"].ToString() ); this.FKDocumentUID = Convert.ToInt32( reader["FKDocumentUID"].ToString()); this.FKDocumentSetUID = Convert.ToInt32( reader["FKDocumentSetUID"].ToString() ); this.StartDate = Convert.ToDateTime( reader["StartDate"].ToString()); this.EndDate = Convert.ToDateTime( reader["EndDate"].ToString()); this.IsVoid = Convert.ToChar(reader["IsVoid"]); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Get Client details // ----------------------------------------------------- public bool Find(int documentUID, int docSetUID, char voidRead) { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKDocumentUID " + " ,FKDocumentSetUID " + " ,StartDate " + " ,EndDate " + " ,IsVoid " + " FROM DocumentSetDocument" + " WHERE FKDocumentUID = '{0}' " + " AND FKDocumentSetUID = '{1}' " + " AND IsVoid = '{2}' " , documentUID , docSetUID , voidRead); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.FKDocumentUID = Convert.ToInt32(reader["FKDocumentUID"].ToString()); this.FKDocumentSetUID = Convert.ToInt32(reader["FKDocumentSetUID"].ToString()); this.StartDate = Convert.ToDateTime(reader["StartDate"].ToString()); this.EndDate = Convert.ToDateTime(reader["EndDate"].ToString()); this.IsVoid = Convert.ToChar(reader["IsVoid"]); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Add new Document Set Link // ----------------------------------------------------- public void Add() { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO DocumentSetDocument " + "(UID " + ",FKDocumentUID " + ",FKDocumentSetUID" + ",Location" + ",IsVoid" + ",StartDate" + ",EndDate" + ",FKParentDocumentUID" + ",FKParentDocumentSetUID" + ",SequenceNumber" + ")" + " VALUES " + "( @UID " + ", @FKDocumentUID " + ", @FKDocumentSetUID " + ", @Location" + ", @IsVoid " + ", @StartDate " + ", @EndDate " + " ,@FKParentDocumentUID " + " ,@FKParentDocumentSetUID " + ", @SequenceNumber" + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = GetLastUID() + 1; command.Parameters.Add("@FKDocumentUID", MySqlDbType.Int32).Value = FKDocumentUID; command.Parameters.Add("@FKDocumentSetUID", MySqlDbType.Int32).Value = FKDocumentSetUID; command.Parameters.Add("@Location", MySqlDbType.Text).Value = Location; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = IsVoid; command.Parameters.AddWithValue("@StartDate", StartDate); command.Parameters.AddWithValue("@EndDate", "9999-12-31"); command.Parameters.Add("@FKParentDocumentUID", MySqlDbType.Int32).Value = FKParentDocumentUID; command.Parameters.Add("@FKParentDocumentSetUID", MySqlDbType.Int32).Value = FKParentDocumentSetUID; command.Parameters.Add("@SequenceNumber", MySqlDbType.Int32).Value = SequenceNumber; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Update Document Set Link // ----------------------------------------------------- private static void Update(int docLinkUID ) { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE DocumentSetDocument " + " SET " + " IsVoid = @IsVoid" + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = docLinkUID; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Update Document Set Document Sequence Number // ----------------------------------------------------- public static void UpdateSequenceNumber(int DocumentSetUID, int DocumentUID, int SequenceNumber) { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE DocumentSetDocument " + " SET " + " SequenceNumber = @SequenceNumber" + " WHERE FKDocumentUID = @FKDocumentUID " + " AND FKDocumentSetUID = @FKDocumentSetUID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKDocumentUID", MySqlDbType.VarChar).Value = DocumentUID; command.Parameters.Add("@FKDocumentSetUID", MySqlDbType.VarChar).Value = DocumentSetUID; command.Parameters.Add("@SequenceNumber", MySqlDbType.VarChar).Value = SequenceNumber; connection.Open(); command.ExecuteNonQuery(); } } return; } // ----------------------------------------------------- // Retrieve last Document Set UID // ----------------------------------------------------- public int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM DocumentSetDocument"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Delete Link // ----------------------------------------------------- public static void Delete(int DocumentSetUID, int DocumentUID) { // Links have to be deleted first // DocumentSetDocument dsd = new DocumentSetDocument(); dsd.Find(documentUID: DocumentUID, docSetUID: DocumentSetUID, voidRead: 'N'); if (dsd.UID <= 0) return; DocumentSetDocumentLink.DeleteAllRelated(dsd.UID); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "DELETE FROM DocumentSetDocument " + " WHERE FKDocumentUID = @FKDocumentUID " + " AND FKDocumentSetUID = @FKDocumentSetUID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKDocumentUID", MySqlDbType.Int32).Value = DocumentUID; command.Parameters.Add("@FKDocumentSetUID", MySqlDbType.Int32).Value = DocumentSetUID; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Load a document from a given reader /// </summary> /// <param name="retDocument"></param> /// <param name="tablePrefix"></param> /// <param name="reader"></param> public static void LoadDocumentFromReader( Model.ModelDocument.Document retDocument, string tablePrefix, MySqlDataReader reader) { retDocument.UID = Convert.ToInt32(reader[tablePrefix + "UID"].ToString()); retDocument.CUID = reader[tablePrefix + "SimpleFileName"].ToString(); retDocument.Name = reader[tablePrefix + "Name"].ToString(); retDocument.SequenceNumber = Convert.ToInt32(reader[tablePrefix + "SequenceNumber"].ToString()); retDocument.IssueNumber = Convert.ToInt32(reader[tablePrefix + "IssueNumber"].ToString()); retDocument.Location = reader[tablePrefix + "Location"].ToString(); retDocument.Comments = reader[tablePrefix + "Comments"].ToString(); retDocument.SourceCode = reader[tablePrefix + "SourceCode"].ToString(); retDocument.FileName = reader[tablePrefix + "FileName"].ToString(); retDocument.SimpleFileName = reader[tablePrefix + "SimpleFileName"].ToString(); retDocument.FKClientUID = Convert.ToInt32(reader[tablePrefix + "FKClientUID"].ToString()); retDocument.ParentUID = Convert.ToInt32(reader[tablePrefix + "ParentUID"].ToString()); retDocument.RecordType = reader[tablePrefix + "RecordType"].ToString(); retDocument.IsProjectPlan = reader[tablePrefix + "IsProjectPlan"].ToString(); retDocument.DocumentType = reader[tablePrefix + "DocumentType"].ToString(); return; } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> public static string SQLDocumentConcat(string tablePrefix) { string ret = " " + tablePrefix + ".UID " + tablePrefix + "UID, " + tablePrefix + ".FKDocumentUID " + tablePrefix + "FKDocumentUID, " + tablePrefix + ".FKDocumentSetUID " + tablePrefix + "FKDocumentSetUID, " + tablePrefix + ".Location " + tablePrefix + "Location, " + tablePrefix + ".IsVoid " + tablePrefix + "IsVoid, " + tablePrefix + ".StartDate " + tablePrefix + "StartDate, " + tablePrefix + ".EndDate " + tablePrefix + "EndDate, " + tablePrefix + ".FKParentDocumentUID " + tablePrefix + "FKParentDocumentUID, " + tablePrefix + ".SequenceNumber " + tablePrefix + "SequenceNumber, " + tablePrefix + ".FKParentDocumentSetUID " + tablePrefix + "FKParentDocumentSetUID, " + tablePrefix + ".DocumentType " + tablePrefix + "DocumentType "; return ret; } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentSetDocumentList { public List<scDocoSetDocumentLink> documentSetDocumentList; // // It returns a list of links for a given document set UID // public void List(DocumentSet documentSet) { documentSetDocumentList = new List<scDocoSetDocumentLink>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,FKDocumentUID " + " ,FKDocumentSetUID " + " ,StartDate " + " ,EndDate " + " ,IsVoid " + " FROM DocumentSetDocument " + " WHERE FKDocumentSetUID = {0} ", documentSet.UID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Ignore voids if (Convert.ToChar(reader["IsVoid"]) == 'Y') continue; var docItem = new scDocoSetDocumentLink(); // Get document // docItem.document = new Model.ModelDocument.Document(); docItem.document.UID = Convert.ToInt32( reader["FKDocumentUID"] ); // 11.01.2013 // // docItem.document.Read(); docItem.document = RepDocument.Read(true, docItem.document.UID); // Get DocumentSet // docItem.documentSet = new DocumentSet(); docItem.documentSet.UID = Convert.ToInt32(reader["FKDocumentSetUID"].ToString()); // Set DocumentSetDocument docItem.DocumentSetDocument = new DocumentSetDocument(); docItem.DocumentSetDocument.UID = Convert.ToInt32(reader["UID"].ToString()); docItem.DocumentSetDocument.FKDocumentUID = Convert.ToInt32(reader["FKDocumentUID"].ToString()); docItem.DocumentSetDocument.FKDocumentSetUID = Convert.ToInt32(reader["FKDocumentSetUID"].ToString()); docItem.DocumentSetDocument.IsVoid = Convert.ToChar(reader["IsVoid"].ToString()); docItem.DocumentSetDocument.StartDate = Convert.ToDateTime(reader["StartDate"].ToString()); if (reader["EndDate"] == null) { docItem.DocumentSetDocument.EndDate = System.DateTime.MaxValue; } else { docItem.DocumentSetDocument.EndDate = Convert.ToDateTime(reader["EndDate"].ToString()); } documentSetDocumentList.Add(docItem); } } } return; } } // This method links the list of documents requested to // the document set requested // public void CopyDocumentList(DocumentList documentList, DocumentSet documentSet) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using MackkadoITFramework.Helper; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { /// <summary> /// It represents a document, folder or appendix. /// </summary> public class Document { [Display( Name = "Unique Identifier" )] public int UID { get; set; } [Display( Name = "Document Unique Identifier (String)" )] public string CUID { get; set; } [Display( Name = "Document Name" )] public string Name { get; set; } [Display( Name = "Display Name" )] public string DisplayName { get; set; } [Display( Name = "Sequence Number" )] public int SequenceNumber { get; set; } [Display( Name = "Version Number" )] public int IssueNumber { get; set; } public string Location { get; set; } public string Comments { get; set; } [Display( Name = "File Extension" )] public string FileExtension { get; set; } /// <summary> /// It is the file name with extension /// </summary> public string FileName { get; set; } /// <summary> /// Indicates the source of the document. It could be from FCM or a Client Document. /// </summary> public string SourceCode { get; set; } [Display( Name = "Client Unique ID" )] public int FKClientUID { get; set; } [Display( Name = "Parent Document ID" )] public int ParentUID { get; set; } /// <summary> /// Indicates if it is a Folder, Document or Appendix /// </summary> /// [Display( Name = "Record Type" )] public string RecordType { get; set; } /// <summary> /// Indicates if the document is a project plan. /// Project plans are special and can hold other documents. /// </summary> [Display( Name = "Is a Project Plan" )] public string IsProjectPlan { get; set; } /// <summary> /// Indicates the type of document: Word, Excel, PDF, Undefined etc. /// Use Utils.DocumentType /// </summary> [Display( Name = "Document Type" )] public string DocumentType { get; set; } /// <summary> /// It includes the client and version number of the document /// </summary> // public string ComboIssueNumber { get { return _ComboIssueNumber; } set { _ComboIssueNumber = value; } } /// <summary> /// It does not include the prefix (CUID) or version number /// </summary> [Display( Name = "Simple File Name" )] public string SimpleFileName { get; set; } /// <summary> /// Indicates whether the record is logically deleted. /// </summary> public string IsVoid { get; set; } /// <summary> /// Document Status (Draft, Finalised, Deleted) /// </summary> public string Status { get; set; } [Display( Name = "Record Version" )] public int RecordVersion { get; set; } /// <summary> /// Indicate if document has to be skipped during generation /// </summary> public string Skip { get; set; } // Audit fields // public string UserIdCreatedBy { get; set; } public string UserIdUpdatedBy { get; set; } public DateTime CreationDateTime { get; set; } public DateTime UpdateDateTime { get; set; } public List<Document> documentList; public Document() { } public Document(HeaderInfo headerInfo) { } } } <file_sep>using System; namespace MackkadoITFramework.Utils { public class HeaderInfo { private static HeaderInfo instance; public string UserID; public string Passcode; // encrypted password public DateTime CurrentDateTime; private HeaderInfo() { } public static HeaderInfo Instance { get { return instance ?? (instance = new HeaderInfo()); } } } } <file_sep>using System; using System.IO; using System.Threading; using FCMMySQLBusinessLibrary; namespace MackkadoITFramework.Utils { /// <summary> /// Class to handle log files /// </summary> public static class LogFile { /// <summary> /// Constructor with the file name /// </summary> /// <param name="fileName"></param> /// <param name="userID"> </param> public static string WriteToTodaysLogFile( string what, string userID = "User Not Supplied", string messageCode = "", string programName = "", string processname = "") { string _Location = MakConstant.SYSFOLDER.LOGFILEFOLDER; StreamWriter log; // Generate File Name // string currYear = DateTime.Today.Year.ToString("0000"); string currMonth = DateTime.Today.Month.ToString("00"); string currDay = DateTime.Today.Day.ToString("00"); string fileName = "FCM_" + currYear + currMonth + currDay + processname + ".txt"; // interesting how I can code remotely // // get path //string filePathName = Utils.getFilePathName(_Location, fileName); string filePathName = XmlConfig.Read(MakConstant.ConfigXml.AuditLogPath) + "\\" + fileName; if (! File.Exists(filePathName)) { try { log = new StreamWriter(filePathName); } catch (Exception ex) { return "Error: " + ex.ToString(); } } else { try { log = File.AppendText( filePathName ); } catch ( Exception ex1 ) { // Sleep a bit just to minimise conflict Thread.Sleep( 1000 ); try { log = File.AppendText( filePathName ); } catch ( Exception ex ) { return "Error: " + ex.ToString(); } } } // Write to the file: log.WriteLine( processname + ": " + DateTime.Now + ": " + userID + ": " + messageCode + ": " + programName + ": " + what ); // Close the stream: log.Close(); return "Ok"; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.ReferenceData { public class RelatedCodeValue { public string FKRelatedCodeID { get; set; } public string FKCodeTypeFrom { get; set; } public string FKCodeValueFrom { get; set; } public string FKCodeTypeTo { get; set; } public string FKCodeValueTo { get; set; } public void Add() { DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO rdRelatedCodeValue " + "(FKRelatedCodeID, FKCodeTypeFrom, FKCodeValueFrom, FKCodeTypeTo,FKCodeValueTo" + ")" + " VALUES " + "( " + " @FKRelatedCodeID " + ", @FKCodeTypeFrom " + ", @FKCodeValueFrom " + ", @FKCodeTypeTo " + ", @FKCodeValueTo " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKRelatedCodeID", MySqlDbType.VarChar).Value = FKRelatedCodeID; command.Parameters.Add("@FKCodeTypeFrom", MySqlDbType.VarChar).Value = FKCodeTypeFrom; command.Parameters.Add("@FKCodeValueFrom", MySqlDbType.VarChar).Value = FKCodeValueFrom; command.Parameters.Add("@FKCodeTypeTo", MySqlDbType.VarChar).Value = FKCodeTypeTo; command.Parameters.Add("@FKCodeValueTo", MySqlDbType.VarChar).Value = FKCodeValueTo; connection.Open(); command.ExecuteNonQuery(); } } return; } public void Delete() { DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "DELETE FROM rdRelatedCodeValue " + " WHERE " + " FKRelatedCodeID = @FKRelatedCodeID " + ", FKCodeTypeFrom = @FKCodeTypeFrom " + ", FKCodeValueFrom = @FKCodeValueFrom " + ", FKCodeTypeTo = @FKCodeTypeTo " + ", FKCodeValueTo = @FKCodeValueTo " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKRelatedCodeID", MySqlDbType.VarChar).Value = FKRelatedCodeID; command.Parameters.Add("@FKCodeTypeFrom", MySqlDbType.VarChar).Value = FKCodeTypeFrom; command.Parameters.Add("@FKCodeValueFrom", MySqlDbType.VarChar).Value = FKCodeValueFrom; command.Parameters.Add("@FKCodeTypeTo", MySqlDbType.VarChar).Value = FKCodeTypeTo; command.Parameters.Add("@FKCodeValueTo", MySqlDbType.VarChar).Value = FKCodeValueTo; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Retrieve list of related codes for give related code type, code type, code value /// </summary> /// <param name="codeType"></param> /// <returns></returns> public static List<RelatedCodeValue> ListS(string RelatedCodeID, string CodeTypeFrom, string CodeValueFrom) { List<RelatedCodeValue> list = new List<RelatedCodeValue>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " FKRelatedCodeID " + " ,FKCodeTypeFrom " + " ,FKCodeValueFrom " + " ,FKCodeTypeTo " + " ,FKCodeValueTo " + " FROM rdRelatedCodeValue " + " WHERE FKRelatedCodeID = '{0}' " + " AND FKCodeTypeFrom = '{1}' " + " AND FKCodeValueFrom = '{2}' " , RelatedCodeID , CodeTypeFrom , CodeValueFrom); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _codeValue = new RelatedCodeValue(); _codeValue.FKRelatedCodeID = reader["FKRelatedCodeID"].ToString(); _codeValue.FKCodeTypeFrom = reader["FKCodeTypeFrom"].ToString(); _codeValue.FKCodeValueFrom = reader["FKCodeValueFrom"].ToString(); _codeValue.FKCodeTypeTo = reader["FKCodeTypeTo"].ToString(); _codeValue.FKCodeValueTo = reader["FKCodeValueTo"].ToString(); list.Add(_codeValue); } } } } return list; } /// <summary> /// Retrieve list of related codes for give related code type, code type, code value /// </summary> /// <param name="codeType"></param> /// <returns></returns> public static List<RelatedCodeValue> ListAllS() { List<RelatedCodeValue> list = new List<RelatedCodeValue>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " FKRelatedCodeID " + " ,FKCodeTypeFrom " + " ,FKCodeValueFrom " + " ,FKCodeTypeTo " + " ,FKCodeValueTo " + " FROM rdRelatedCodeValue " + " ORDER BY FKRelatedCodeID, FKCodeTypeFrom, FKCodeValueFrom " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _codeValue = new RelatedCodeValue(); _codeValue.FKRelatedCodeID = reader["FKRelatedCodeID"].ToString(); _codeValue.FKCodeTypeFrom = reader["FKCodeTypeFrom"].ToString(); _codeValue.FKCodeValueFrom = reader["FKCodeValueFrom"].ToString(); _codeValue.FKCodeTypeTo = reader["FKCodeTypeTo"].ToString(); _codeValue.FKCodeValueTo = reader["FKCodeValueTo"].ToString(); list.Add(_codeValue); } } } } return list; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.ErrorHandling; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public class BUSEmployee { public static SCEmployee.EmployeeListResponse EmployeeList( int clientUID ) { var employeeList = new SCEmployee.EmployeeListResponse(); var list = Model.ModelClient.Employee.List( clientUID ); employeeList.response = new ResponseStatus(); employeeList.employeeList = list; return employeeList; } public static SCEmployee.EmployeeReadResponse EmployeeRead( int clientUID, int employeeUID ) { var employeeResponse = new SCEmployee.EmployeeReadResponse(); employeeResponse.response = new ResponseStatus(); employeeResponse.employee = new Employee(); employeeResponse.employee.UID = employeeUID; employeeResponse.employee.Read(); return employeeResponse; } public static ResponseStatus EmployeeUpdate( Employee employee ) { var employeeResponse = new ResponseStatus(); employee.Update(); return employeeResponse; } public static SCEmployee.EmployeeCreateResponse EmployeeCreate( Employee employee ) { var employeeResponse = new SCEmployee.EmployeeCreateResponse(); employee.Insert(); employeeResponse.employee = employee; return employeeResponse; } public static ResponseStatus EmployeeDelete( Employee employee ) { var employeeResponse = new ResponseStatus(); employee.Delete(); return employeeResponse; } } } <file_sep>namespace FCMMySQLBusinessLibrary.FCMUtils { /// <summary> /// Class with every constant used in the system /// </summary> public class FCMConstant { /// <summary> /// It represents the attribute for the database ConnectionString /// </summary> public class fcmConfigXml { public static string ConnectionString = "ConnectionString"; public static string ConnectionStringMySql = "ConnectionStringMySql"; public static string ConnectionStringServer = "ConnectionStringServer"; public static string ConnectionStringLocal = "ConnectionStringLocal"; public static string LocalAssemblyFolder = "LocalAssemblyFolder"; public static string ServerAssemblyFolder = "ServerAssemblyFolder"; public static string EnableLocalDB = "EnableLocalDB"; public static string EnableServerDB = "EnableServerDB"; public static string DefaultDB = "DefaultDB"; public static string AuditLogPath = "AuditLogPath"; } /// <summary> /// It represents the attribute for the database ConnectionString /// </summary> public enum DataBaseType { SQLSERVER, MYSQL } /// <summary> /// Integer represent the sequence of the image on the Image List. /// </summary> public struct Image { public const int Selected = 0; public const int Document = 1; public const int Folder = 2; public const int Client = 3; public const int Appendix = 4; public const int Excel = 5; public const int PDF = 6; public const int Undefined = 7; public const int Checked = 8; public const int Unchecked = 9; public const int Word32 = 10; public const int WordFileExists32 = 11; public const int WordFileNotFound32 = 12; public const int WordFileSourceNoDestinationNo = 13; public const int WordFileSourceNoDestinationYes = 14; public const int WordFileSourceYesDestinationNo = 15; public const int WordFileSourceYesDestinationYes = 16; public const int ExcelFileSourceNoDestinationNo = 17; public const int ExcelFileSourceNoDestinationYes = 18; public const int ExcelFileSourceYesDestinationNo = 19; public const int ExcelFileSourceYesDestinationYes = 20; public const int PDFFileSourceNoDestinationNo = 21; public const int PDFFileSourceNoDestinationYes = 22; public const int PDFFileSourceYesDestinationNo = 23; public const int PDFFileSourceYesDestinationYes = 24; } /// <summary> /// This is the name of the image file representing the file type /// </summary> public struct ImageFileName { public const string Selected = "ImageSelected.jpg"; public const string Document = "ImageWordDocument.jpg"; public const string Folder = "ImageFolder.jpg"; public const string Client = "ImageClient.jpg"; public const string Appendix = "Appendix.jpg"; public const string Excel = "Excel.jpg"; public const string PDF = "PDF.jpg"; public const string Undefined = "ImageWordDocument.jpg"; public const string Checked = "Checked.jpg"; public const string Unchecked = "Unchecked.jpg"; public const string WordFile32 = "WordFile32.jpg"; public const string WordFileExists32 = "WordFileExists32.jpg"; public const string WordFileNotFound32 = "WordFileNotFound32.jpg"; public const string WordFileSourceNoDestinationNo = "WordFileSourceNoDestinationNo"; public const string WordFileSourceNoDestinationYes = "WordFileSourceNoDestinationYes"; public const string WordFileSourceYesDestinationNo = "WordFileSourceYesDestinationNo"; public const string WordFileSourceYesDestinationYes = ""; public const string ExcelFileSourceNoDestinationNo = "ExcelFileSourceNoDestinationNo"; public const string ExcelFileSourceNoDestinationYes = "ExcelFileSourceNoDestinationYes"; public const string ExcelFileSourceYesDestinationNo = "ExcelFileSourceYesDestinationNo"; public const string ExcelFileSourceYesDestinationYes = "ExcelFileSourceYesDestinationYes"; public const string PDFFileSourceNoDestinationNo = "PDFFileSourceNoDestinationNo"; public const string PDFFileSourceNoDestinationYes = "PDFFileSourceNoDestinationYes"; public const string PDFFileSourceYesDestinationNo = "PDFFileSourceYesDestinationNo"; public const string PDFFileSourceYesDestinationYes = "PDFFileSourceYesDestinationYes"; } /// <summary> /// List of code types /// </summary> public struct CodeTypeString { public const string RoleType = "ROLETYPE"; public const string ErrorCode = "ERRORCODE"; public const string SYSTSET = "SYSTSET"; public const string SCREENCODE = "SCREENCODE"; public const string ERRORCODE = "ERRORCODE"; } /// <summary> /// List of Role Types /// </summary> public struct RoleTypeCode { public const string AdministrationPerson = "ADMIN"; public const string ManagingDirector = "MD1"; public const string ProjectManager = "PM1"; public const string ProjectOHSRepresentative = "POHSEREP"; public const string OHSEAuditor = "OHSEAUDITOR"; public const string SystemsManager = "SMN1"; public const string SiteManager = "SM1"; public const string Supervisor = "SUP1"; public const string LeadingHand1 = "LEADHAND1"; public const string LeadingHand2 = "LEADHAND2"; public const string HealthAndSafetyRep = "HSR1"; public const string WorkersCompensationCoordinator = "WCPERSON"; } /// <summary> /// List of folder variables /// </summary> public struct SYSFOLDER { public const string TEMPLATEFOLDER = "%TEMPLATEFOLDER%"; public const string CLIENTFOLDER = "%CLIENTFOLDER%"; public const string VERSIONFOLDER = "%VERSIONFOLDER%"; public const string PDFEXEPATH = "PDFEXEPATH"; public const string LOGOFOLDER = "%LOGOFOLDER%"; public const string WEBLOGOFOLDER = "%WEBLOGOFOLDER%"; public const string WEBTEMPLATEFOLDER = "%WEBTEMPLATEFOLDER%"; public const string WEBCLIENTFOLDER = "%WEBCLIENTFOLDER%"; public const string WEBVERSIONFOLDER = "%WEBVERSIONFOLDER%"; public const string LOGFILEFOLDER = "%LOGFILEFOLDER%"; } /// <summary> /// Document list mode /// </summary> public struct DocumentListMode { public const string SELECT = "SELECT"; public const string MAINTAIN = "MAINTAIN"; } /// <summary> /// Screen Codes /// </summary> public struct ScreenCode { public const string Document = "DOCUMENT"; public const string ClientRegistration = "CLNTREG"; public const string ClientList = "CLNTLIST"; public const string ClientDocument = "CLNTDOC"; public const string ClientDocumentSet = "CLNTDOCSET"; public const string ClientDocumentSetLink = "CLNTDOCSETLINK"; public const string DocumentList = "DOCLIST"; public const string DocumentLink = "DOCLINK"; public const string DocumentSetLink = "DOCSETLINK"; public const string DocumentSetList = "DOCSETLIST"; public const string UserAccess = "USERACCESS"; public const string ImpactedDocuments = "IMPACTEDDOCUMENTS"; public const string ProcessRequest = "PROCESSREQUEST"; public const string ReferenceData = "REFERENCEDATA"; public const string ReportMetadata = "REPORTMETADATA"; public const string Users = "USERS"; public const string UserSettings = "USERSETTINGS"; } /// <summary> /// Screen Codes /// </summary> public struct ScreenControl { public const string TreeViewClientDocumentList = "TVCLNTDOCLIST"; public const string TreeViewClientDocumentListDocSet = "TVCLNTDOCLISTDOCSET"; public const string TreeViewDocumentList = "TVCLNTDOCLIST"; } /// <summary> /// Font Size /// </summary> public struct ScreenProperty { public const string FontSize = "FONTSIZE"; public const string IconSize = "ICONSIZE"; } public struct DocumentStatus { public const string ACTIVE = "ACTIVE"; public const string INACTIVE = "INACTIVE"; } public struct DocumentSetStatus { public const string COMPLETED = "COMPLETED"; public const string DRAFT = "DRAFT"; } public struct DocumentListType { public const string FCM = "FCM"; public const string DOCUMENTSET = "DOCUMENTSET"; } public struct MetadataRecordType { public const string CLIENT = "CL"; public const string DEFAULT = "DF"; } public struct FieldCode { public const string COMPANYLOGO = "COMPANYLOGO"; } public struct SaveType { public const string NEWONLY = "NEWONLY"; public const string UPDATE = "UPDATE"; } /// <summary> /// Indicates the source of the document. It could be FCM or Client /// </summary> public struct SourceCode { public const string CLIENT = "CLIENT"; public const string FCM = "FCM"; } public struct RecordType { public const string FOLDER = "FOLDER"; public const string DOCUMENT = "DOCUMENT"; public const string APPENDIX = "APPENDIX"; } public struct UserRoleType { public const string ADMIN = "ADMIN"; public const string USER = "USER"; public const string CLIENT = "CLIENT"; public const string POWERUSER = "POWERUSER"; } public struct DocumentLinkType { public const string PROJECTPLAN = "PROJPLAN"; public const string APPENDIX = "APPENDIX"; } } } <file_sep>using System; using System.Configuration; using System.Web.Configuration; using FCMMySQLBusinessLibrary; namespace MackkadoITFramework.Utils { public class ConnString { private static string connectionString; private static string connectionStringServer; private static string connectionStringFramework; private static string connectionStringLocal; private static string connectionStringMySql; private static string connectionStringODBC; public static string ConnectionString { get { if (string.IsNullOrEmpty(connectionString)) { connectionString = XmlConfig.Read(MakConstant.ConfigXml.ConnectionStringMySql); //"Persist Security info=false;" + //"integrated security=sspi;"; } return connectionString; } set { connectionString = value; } } public static string ConnectionStringODBC { get { if (string.IsNullOrEmpty(connectionStringODBC)) { connectionString = XmlConfig.Read(MakConstant.ConfigXml.ConnectionStringODBC); //"Persist Security info=false;" + //"integrated security=sspi;"; } return connectionString; } set { connectionString = value; } } public static string ConnectionStringServer { get { if (string.IsNullOrEmpty(connectionStringServer)) { connectionStringServer = XmlConfig.Read(MakConstant.ConfigXml.ConnectionStringServer); } return connectionStringServer; } set { connectionStringServer = value; } } public static string ConnectionStringFramework { get { if (string.IsNullOrEmpty(connectionStringFramework)) { connectionStringFramework = XmlConfig.Read(MakConstant.ConfigXml.ConnectionStringFramework); } if (string.IsNullOrEmpty(connectionStringFramework)) { string webconstring = GetConnectionStringFromWebConfig("makkframework"); if (!(string.IsNullOrEmpty(webconstring) || webconstring == "Empty")) { return webconstring; } } return connectionStringFramework; } set { connectionStringFramework = value; } } public static string ConnectionStringLocal { get { if (string.IsNullOrEmpty(connectionStringLocal)) { connectionStringLocal = XmlConfig.Read(MakConstant.ConfigXml.ConnectionStringLocal); } return connectionStringLocal; } set { connectionStringLocal = value; } } public static string GetConnectionStringFromWebConfig(string csapp = "mainapplication") { Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot"); string connstring = "Not found"; if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0) { ConnectionStringSettings connString = rootWebConfig.ConnectionStrings.ConnectionStrings[csapp]; if (connString != null) connstring = connString.ConnectionString; else connstring = "Empty"; } return connstring; } private static string Toshiba { get { return "Data Source=TOSHIBAPC\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string DeanPC { get { return "Data Source=DEAN-PC\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string HPLaptop { get { return "Data Source=HPLAPTOP\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string Desktop { get { return "Data Source=DESKTOHP\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string HPMINI { get { return "Data Source=HPMINI\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.Data; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using ConnString = MackkadoITFramework.Utils.ConnString; using HeaderInfo = MackkadoITFramework.Utils.HeaderInfo; using Utils = MackkadoITFramework.Helper.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace FCMMySQLBusinessLibrary.Repository.RepositoryClient { public class RepClientExtraInformation : ClientExtraInformation { private HeaderInfo _headerInfo; public RepClientExtraInformation(HeaderInfo headerInfo) { _headerInfo = headerInfo; } /// <summary> /// Get Client Extra Information /// </summary> public static ResponseStatus Read( ClientExtraInformation clientExtraInfo) { // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientFieldString() + " FROM ClientExtraInformation" + " WHERE FKClientUID = @UID"; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = clientExtraInfo.FKClientUID; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadClientObject(reader, clientExtraInfo); } catch (Exception) { clientExtraInfo.UID = 0; } } else { return new ResponseStatus(){ReturnCode = 1, ReasonCode = 2, Message = "Not found",XMessageType = MessageType.Warning}; } } } return new ResponseStatus(); } // ----------------------------------------------------- // Add new Client // ----------------------------------------------------- public static ResponseStatus Insert( HeaderInfo headerInfo, ClientExtraInformation clientExtraInfo, MySqlConnection connection) { ResponseStatus response = new ResponseStatus(); response.ReturnCode = 1; response.ReasonCode = 1; response.Message = "Client Added Successfully"; int _uid = 0; int nextUID = GetLastUID() + 1; // 2010100000 clientExtraInfo.UID = nextUID; DateTime _now = DateTime.Today; clientExtraInfo.RecordVersion = 1; clientExtraInfo.IsVoid = "N"; clientExtraInfo.CreationDateTime = headerInfo.CurrentDateTime; clientExtraInfo.UpdateDateTime = headerInfo.CurrentDateTime; clientExtraInfo.UserIdCreatedBy = headerInfo.UserID; clientExtraInfo.UserIdUpdatedBy = headerInfo.UserID; var commandString = ( "INSERT INTO ClientExtraInformation " + "(" + ClientFieldString() + ")" + " VALUES " + "( @UID " + ", @FKClientUID " + ", @DateToEnterOnPolicies " + ", @ScopeOfServices " + ", @ActionPlanDate " + ", @CertificationTargetDate " + ", @TimeTrading " + ", @RegionsOfOperation " + ", @OperationalMeetingsFrequency " + ", @ProjectMeetingsFrequency " + ", @IsVoid " + ", @RecordVersion " + ", @UpdateDateTime " + ", @UserIdUpdatedBy " + ", @CreationDateTime " + ", @UserIdCreatedBy ) " ); using (var command = new MySqlCommand(commandString, connection)) { clientExtraInfo.RecordVersion = 1; clientExtraInfo.IsVoid = "N"; AddSQLParameters(command, MakConstant.SQLAction.CREATE, clientExtraInfo); if (connection.State != ConnectionState.Open) connection.Open(); command.ExecuteNonQuery(); } response.Contents = _uid; return response; } /// <summary> /// Update client details /// </summary> /// <returns></returns> public static ResponseStatus Update( HeaderInfo headerInfo, ClientExtraInformation clientExtraInfo, MySqlConnection connection) { var response = new ResponseStatus {ReturnCode = 1, ReasonCode = 1, Message = "Client Updated Successfully."}; // using (var connection = new MySqlConnection(ConnString.ConnectionString)) using (connection) { var commandString = ( "UPDATE ClientExtraInformation " + " SET " + FCMDBFieldName.ClientExtraInformation.ActionPlanDate + " = @" + FCMDBFieldName.ClientExtraInformation.ActionPlanDate + ", " + FCMDBFieldName.ClientExtraInformation.CertificationTargetDate + " = @" + FCMDBFieldName.ClientExtraInformation.CertificationTargetDate + ", " + FCMDBFieldName.ClientExtraInformation.DateToEnterOnPolicies + " = @" + FCMDBFieldName.ClientExtraInformation.DateToEnterOnPolicies + ", " + FCMDBFieldName.ClientExtraInformation.OperationalMeetingsFrequency + " = @" + FCMDBFieldName.ClientExtraInformation.OperationalMeetingsFrequency + ", " + FCMDBFieldName.ClientExtraInformation.ProjectMeetingsFrequency + " = @" + FCMDBFieldName.ClientExtraInformation.ProjectMeetingsFrequency + ", " + FCMDBFieldName.ClientExtraInformation.RecordVersion + " = @" + FCMDBFieldName.ClientExtraInformation.RecordVersion + ", " + FCMDBFieldName.ClientExtraInformation.RegionsOfOperation + " = @" + FCMDBFieldName.ClientExtraInformation.RegionsOfOperation + ", " + FCMDBFieldName.ClientExtraInformation.ScopeOfServices + " = @" + FCMDBFieldName.ClientExtraInformation.ScopeOfServices + ", " + FCMDBFieldName.ClientExtraInformation.TimeTrading + " = @" + FCMDBFieldName.ClientExtraInformation.TimeTrading + ", " + FCMDBFieldName.ClientExtraInformation.IsVoid + " = @" + FCMDBFieldName.ClientExtraInformation.IsVoid + ", " + FCMDBFieldName.ClientExtraInformation.UpdateDateTime + " = @" + FCMDBFieldName.ClientExtraInformation.UpdateDateTime + ", " + FCMDBFieldName.ClientExtraInformation.UserIdUpdatedBy + " = @" + FCMDBFieldName.ClientExtraInformation.UserIdUpdatedBy + " WHERE FKClientUID = @FKClientUID " ); clientExtraInfo.RecordVersion++; clientExtraInfo.UpdateDateTime = DateTime.Now; clientExtraInfo.UserIdUpdatedBy = headerInfo.UserID; clientExtraInfo.IsVoid = "N"; using (var command = new MySqlCommand( cmdText: commandString, connection: connection)) { AddSQLParameters(command, MakConstant.SQLAction.UPDATE, clientExtraInfo); try { if (connection.State != ConnectionState.Open) connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), headerInfo.UserID); response.ReturnCode = -0020; response.ReasonCode = 0001; response.Message = "Error saving Client Extra Information. " + ex.ToString(); return response; } } } return response; } /// <summary> /// Retrieve last UID /// </summary> /// <returns></returns> public static int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientExtraInformation"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add SQL Parameters /// </summary> /// <param name="_uid"></param> /// <param name="command"></param> /// <param name="action"></param> private static void AddSQLParameters(MySqlCommand command, string action, ClientExtraInformation clientExtraInfo) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = clientExtraInfo.UID; command.Parameters.Add("@FKClientUID", MySqlDbType.VarChar).Value = clientExtraInfo.FKClientUID; command.Parameters.Add("@ActionPlanDate", MySqlDbType.Date).Value = clientExtraInfo.ActionPlanDate; command.Parameters.Add("@CertificationTargetDate", MySqlDbType.Date).Value = clientExtraInfo.CertificationTargetDate; command.Parameters.Add("@DateToEnterOnPolicies", MySqlDbType.Date).Value = clientExtraInfo.DateToEnterOnPolicies; command.Parameters.Add("@OperationalMeetingsFrequency", MySqlDbType.VarChar).Value = clientExtraInfo.OperationalMeetingsFrequency; command.Parameters.Add("@ProjectMeetingsFrequency", MySqlDbType.VarChar).Value = clientExtraInfo.ProjectMeetingsFrequency; command.Parameters.Add("@RegionsOfOperation", MySqlDbType.VarChar).Value = clientExtraInfo.RegionsOfOperation; command.Parameters.Add("@ScopeOfServices", MySqlDbType.VarChar).Value = clientExtraInfo.ScopeOfServices; command.Parameters.Add("@TimeTrading", MySqlDbType.VarChar).Value = clientExtraInfo.TimeTrading; command.Parameters.Add("@UpdateDateTime", MySqlDbType.DateTime).Value = clientExtraInfo.UpdateDateTime; command.Parameters.Add("@UserIdUpdatedBy", MySqlDbType.VarChar).Value = clientExtraInfo.UserIdUpdatedBy; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = clientExtraInfo.IsVoid; command.Parameters.Add("@RecordVersion", MySqlDbType.Int32).Value = clientExtraInfo.RecordVersion; if (action == MakConstant.SQLAction.CREATE) { command.Parameters.Add("@CreationDateTime", MySqlDbType.DateTime, 8).Value = clientExtraInfo.CreationDateTime; command.Parameters.Add("@UserIdCreatedBy", MySqlDbType.VarChar).Value = clientExtraInfo.UserIdCreatedBy; } } /// <summary> /// Client string of fields. /// </summary> /// <returns></returns> private static string ClientFieldString() { string ret = FCMDBFieldName.ClientExtraInformation.UID + "," + FCMDBFieldName.ClientExtraInformation.FKClientUID + "," + FCMDBFieldName.ClientExtraInformation.DateToEnterOnPolicies + "," + FCMDBFieldName.ClientExtraInformation.ScopeOfServices + "," + FCMDBFieldName.ClientExtraInformation.ActionPlanDate + "," + FCMDBFieldName.ClientExtraInformation.CertificationTargetDate + "," + FCMDBFieldName.ClientExtraInformation.TimeTrading + "," + FCMDBFieldName.ClientExtraInformation.RegionsOfOperation + "," + FCMDBFieldName.ClientExtraInformation.OperationalMeetingsFrequency + "," + FCMDBFieldName.ClientExtraInformation.ProjectMeetingsFrequency + "," + FCMDBFieldName.ClientExtraInformation.IsVoid + "," + FCMDBFieldName.ClientExtraInformation.RecordVersion + "," + FCMDBFieldName.ClientExtraInformation.UpdateDateTime + "," + FCMDBFieldName.ClientExtraInformation.UserIdUpdatedBy + "," + FCMDBFieldName.ClientExtraInformation.CreationDateTime + "," + FCMDBFieldName.ClientExtraInformation.UserIdCreatedBy; return ret; } /// <summary> /// Load client object /// </summary> /// <param name="reader"></param> private static void LoadClientObject(MySqlDataReader reader, ClientExtraInformation clientExtraInfo) { clientExtraInfo.UID = Convert.ToInt32(reader[FCMDBFieldName.ClientExtraInformation.UID]); try { clientExtraInfo.ActionPlanDate = Convert.ToDateTime(reader[FCMDBFieldName.ClientExtraInformation.ActionPlanDate].ToString()); } catch { clientExtraInfo.ActionPlanDate = Utils.MinDate; } try { clientExtraInfo.CertificationTargetDate = Convert.ToDateTime(reader[FCMDBFieldName.ClientExtraInformation.CertificationTargetDate].ToString()); } catch { clientExtraInfo.CertificationTargetDate = Utils.MinDate; } try { clientExtraInfo.DateToEnterOnPolicies = Convert.ToDateTime(reader[FCMDBFieldName.ClientExtraInformation.DateToEnterOnPolicies].ToString()); } catch { clientExtraInfo.DateToEnterOnPolicies = Utils.MinDate; } clientExtraInfo.FKClientUID = Convert.ToInt32(reader[FCMDBFieldName.ClientExtraInformation.FKClientUID]); clientExtraInfo.OperationalMeetingsFrequency = (reader[FCMDBFieldName.ClientExtraInformation.OperationalMeetingsFrequency].ToString()); clientExtraInfo.ProjectMeetingsFrequency = (reader[FCMDBFieldName.ClientExtraInformation.ProjectMeetingsFrequency].ToString()); clientExtraInfo.RegionsOfOperation = (reader[FCMDBFieldName.ClientExtraInformation.RegionsOfOperation].ToString()); clientExtraInfo.ScopeOfServices = (reader[FCMDBFieldName.ClientExtraInformation.ScopeOfServices].ToString()); clientExtraInfo.TimeTrading = (reader[FCMDBFieldName.ClientExtraInformation.TimeTrading].ToString()); // Audit Info // try { clientExtraInfo.UpdateDateTime = Convert.ToDateTime(reader[FCMDBFieldName.ClientExtraInformation.UpdateDateTime].ToString()); } catch { clientExtraInfo.UpdateDateTime = DateTime.Now; } try { clientExtraInfo.CreationDateTime = Convert.ToDateTime(reader[FCMDBFieldName.ClientExtraInformation.CreationDateTime].ToString()); } catch { clientExtraInfo.CreationDateTime = DateTime.Now; } try { clientExtraInfo.IsVoid = reader[FCMDBFieldName.ClientExtraInformation.IsVoid].ToString(); } catch { clientExtraInfo.IsVoid = "N"; } try { clientExtraInfo.UserIdCreatedBy = reader[FCMDBFieldName.ClientExtraInformation.UserIdCreatedBy].ToString(); } catch { clientExtraInfo.UserIdCreatedBy = "N"; } try { clientExtraInfo.UserIdUpdatedBy = reader[FCMDBFieldName.ClientExtraInformation.UserIdCreatedBy].ToString(); } catch { clientExtraInfo.UserIdCreatedBy = "N"; } clientExtraInfo.RecordVersion = Convert.ToInt32(reader[FCMDBFieldName.ClientExtraInformation.RecordVersion]); } } } <file_sep>using System; using System.Collections.Generic; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.ReferenceData; namespace fcm.Windows { public partial class UIClientEmployee : Form, IEmployee { public Employee SelectedEmployee; // --------------------------------------- // 2) Event declaration // --------------------------------------- public event EventHandler<EventArgs> EmployeeList; public event EventHandler<EventArgs> EmployeeAdd; public event EventHandler<EventArgs> EmployeeUpdate; public event EventHandler<EventArgs> EmployeeDelete; public ClientContract clientContract { set; get; } public Employee employee { set; get; } public List<Employee> employeeList { get; set; } public List<ClientContract> clientContractList { get; set; } public ResponseStatus response { get; set; } private Client client; /// <summary> /// Constructor /// </summary> public UIClientEmployee(Client iclient) { InitializeComponent(); client = iclient; // --------------------------------------- // 1) Create an instance of the controller // --------------------------------------- new ControllerEmployee(this); employee = new Employee(); SelectedEmployee = new Employee(); employeeList = new List<Employee>(); clientContract = new ClientContract(); txtClientName.Text = client.UID + " " + client.Name; } /// <summary> /// Form load event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UIClientEmployee_Load(object sender, EventArgs e) { var empRoleType = new CodeValue(); empRoleType.ListInCombo(true, "ROLETYPE", cbxEmployeeRoleType); ListEmployee(); } // --------------------------------------- // 4) UI Events // --------------------------------------- private void btnSaveEmployee_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtEmployeeUID.Text)) { AddEmployee(); } else { UpdateEmployee(); } if (response.ReturnCode == 1 && response.ReasonCode == 1) { // Reset screen // ResetScreen(); } ListEmployee(); } /// <summary> /// Reset screen (IEmployee interface) /// </summary> public void ResetScreen() { txtEmployeeUID.Text = ""; txtAddress.Text = ""; txtEmail.Text = ""; txtEmployeeName.Text = ""; txtFax.Text = ""; txtPhone.Text = ""; this.txtEmployeeName.Focus(); } /// <summary> /// Save employee details /// </summary> private void AddEmployee() { if (EmployeeAdd == null) return; // Set variable details // employee.FKCompanyUID = Utils.ClientID; employee.Name = txtEmployeeName.Text; employee.Address = txtAddress.Text; employee.EmailAddress = txtEmail.Text; employee.Phone = txtPhone.Text; employee.Fax = txtFax.Text; employee.IsAContact = checkIsContact.Checked ? 'Y' : 'N'; string[] roleType = cbxEmployeeRoleType.Text.Split(';'); employee.RoleType = roleType[0]; EmployeeAdd(this, EventArgs.Empty); return; } /// <summary> /// Save employee details /// </summary> private void UpdateEmployee() { if (EmployeeUpdate == null) return; // Set variable details // employee.UID = Convert.ToInt32( txtEmployeeUID.Text ); employee.FKCompanyUID = Utils.ClientID; employee.Name = txtEmployeeName.Text; employee.Address = txtAddress.Text; employee.EmailAddress = txtEmail.Text; employee.Phone = txtPhone.Text; employee.Fax = txtFax.Text; employee.IsAContact = checkIsContact.Checked ? 'Y' : 'N'; string[] roleType = cbxEmployeeRoleType.Text.Split(';'); employee.RoleType = roleType[0]; employee.UpdateDateTime = DateTime.Now; employee.CreationDateTime = SelectedEmployee.CreationDateTime; employee.UserIdCreatedBy = SelectedEmployee.UserIdCreatedBy; employee.UserIdUpdatedBy = SelectedEmployee.UserIdUpdatedBy; EmployeeUpdate(this, EventArgs.Empty); return; } private void btnEmployeeDelete_Click(object sender, EventArgs e) { if (EmployeeDelete == null) return; if (string.IsNullOrEmpty(txtEmployeeUID.Text)) { MessageBox.Show("Employee must be selected first."); return; } Employee employeeNew = new Employee(); employeeNew.UID = Convert.ToInt32(txtEmployeeUID.Text); EmployeeDelete(this, EventArgs.Empty); ListEmployee(); } /// <summary> /// List employees /// </summary> private void ListEmployee() { if (EmployeeUpdate == null) return; employee.FKCompanyUID = Utils.ClientID; EmployeeList(this, EventArgs.Empty); try { employeeBindingSource.DataSource = employeeList; } catch (Exception ex) { MessageBox.Show("P2 " + ex.ToString()); } return; } public void DisplayMessage(string message) { MessageBox.Show(message); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvEmployeeList_SelectionChanged(object sender, EventArgs e) { if (dgvEmployeeList.SelectedRows.Count <= 0) return; var selectedRow = dgvEmployeeList.SelectedRows; txtEmployeeUID.Text = selectedRow[0].Cells["dgv"+Employee.FieldName.UID].Value.ToString(); cbxEmployeeRoleType.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.RoleType].Value.ToString() + ";" + selectedRow[0].Cells["dgv" + Employee.FieldName.RoleDescription].Value.ToString(); txtEmployeeName.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.Name].Value.ToString(); txtEmail.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.EmailAddress].Value.ToString(); txtAddress.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.Address].Value.ToString(); txtPhone.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.Phone].Value.ToString(); txtFax.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.Fax].Value.ToString(); cbxEmployeeRoleType.Text = selectedRow[0].Cells["dgv" + Employee.FieldName.RoleType].Value.ToString() + ";" + selectedRow[0].Cells["dgv" + Employee.FieldName.RoleDescription].Value.ToString(); // checkIsContact.Checked ? 'Y' : 'N'; checkIsContact.Checked = false; if (Convert.ToChar(selectedRow[0].Cells["dgv" + Employee.FieldName.IsAContact].Value) == 'Y') checkIsContact.Checked = true; } private void btnNewEmployee_Click(object sender, EventArgs e) { ResetScreen(); } private void btnCancel_Click(object sender, EventArgs e) { ResetScreen(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { this.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIDocumentEdit : Form { private UIDocumentList uidl; public UIDocumentEdit() { InitializeComponent(); } public UIDocumentEdit(UIDocumentList _uidl) { InitializeComponent(); uidl = new UIDocumentList(); uidl = _uidl; txtCUID.Enabled = false; txtCUID.ReadOnly = true; txtDirectory.Focus(); } private void btnDelete_Click(object sender, EventArgs e) { } private void btnNew_Click(object sender, EventArgs e) { New(); } // // Clear fields // private void New() { txtCUID.Text = ""; txtDirectory.Text = ""; txtLatestIssueLocation.Text = ""; txtLatestIssueNumber.Text = ""; txtName.Text = ""; txtSeqNum.Text = ""; txtSubDirectory.Text = ""; txtComments.Text = ""; txtCUID.Enabled = true; txtCUID.ReadOnly = false; txtCUID.Focus(); } public void SetValues(Document inDoco) { txtCUID.Text = inDoco.CUID; txtDirectory.Text = inDoco.Directory; txtLatestIssueLocation.Text = inDoco.LatestIssueLocation; txtLatestIssueNumber.Text = inDoco.LatestIssueNumber; txtName.Text = inDoco.Name; txtSeqNum.Text = inDoco.SequenceNumber; txtSubDirectory.Text = inDoco.Subdirectory; txtComments.Text = inDoco.Comments; } private void btnSave_Click(object sender, EventArgs e) { Document docSave = new Document(); docSave.CUID = txtCUID.Text; docSave.Comments = txtComments.Text; docSave.Directory = txtDirectory.Text; docSave.LatestIssueLocation = txtLatestIssueLocation.Text; docSave.LatestIssueNumber = txtLatestIssueNumber.Text; docSave.Name = txtName.Text; docSave.SequenceNumber = txtSeqNum.Text; docSave.Subdirectory = txtSubDirectory.Text; docSave.Comments = txtComments.Text; docSave.Save(); if (uidl != null) uidl.Refresh(); } private void btnOpenFile_Click(object sender, EventArgs e) { var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { txtLatestIssueLocation.Text = openFileDialog1.FileName; } } private void UIDocumentEdit_Load(object sender, EventArgs e) { } private void btnNewIssue_Click(object sender, EventArgs e) { UIDocumentIssue uidi = new } } } <file_sep>using ServiceStack.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using StackExchange.Redis; namespace MackkadoITFramework.RedisDan { public class RedisDan { ConnectionMultiplexer redis; IDatabase db; int databaseid; StackExchange.Redis.IServer redisserver; public RedisDan(int dbid, string cachetarget = "local") { string cachetouse = "danielw10-s37p2ob0.cloudapp.net,allowAdmin=true"; string cachedbserver = "danielw10-s37p2ob0.cloudapp.net:6379"; if (cachetarget == "remote") { cachetouse = "danielw10-s37p2ob0.cloudapp.net,allowAdmin=true"; cachedbserver = "danielw10-s37p2ob0.cloudapp.net:6379"; } //if (cachetarget == "local") //{ // cachetouse = "172.16.0.30,allowAdmin=true"; // cachedbserver = "172.16.0.30:6379"; //} if (cachetarget == "local") { cachetouse = "localhost,allowAdmin=true"; cachedbserver = "localhost:6379"; } databaseid = dbid; redis = ConnectionMultiplexer.Connect(cachetouse); db = redis.GetDatabase( dbid ); redisserver = redis.GetServer(cachedbserver); } public void flushdb() { redisserver.FlushDatabase(databaseid); } // POST: api/Redis public bool Post(string key, string keyValue) { return db.StringSet(key, keyValue); //redis.SetEntry(key, keyValue); //using (var redis = new RedisClient("danielw10-s37p2ob0.cloudapp.net", 6379)) //{ // redis.SetEntry(key, keyValue); //} } // GET: api/Redis/key public string Get(string key) { return db.StringGet(key); //using (var redis = new RedisClient("danielw10-s37p2ob0.cloudapp.net", 6379)) //{ // return redis.GetEntry(key); //} } public string Delete(string key) { db.KeyDelete(key); return ""; //using (var redis = new RedisClient("danielw10-s37p2ob0.cloudapp.net", 6379)) //{ // return redis.GetEntry(key); //} } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIReferenceData : Form { // private string _connectionString; private string _userID; public DataTable dtCodeValue; public CodeTypeList codeTypeList; public UIReferenceData() { InitializeComponent(); // _connectionString = Utils.ConnectionString; _userID = Utils.UserID; // // Create datatable = Code Value // var FKCodeType = new DataColumn("FKCodeType", typeof(String)); var ID = new DataColumn("ID", typeof(String)); var Description = new DataColumn("Description", typeof(String)); var Abbreviation = new DataColumn("Abbreviation", typeof(String)); var ValueExtended = new DataColumn("ValueExtended", typeof(String)); dtCodeValue = new DataTable("dtCodeValue"); dtCodeValue.Columns.Add(FKCodeType); dtCodeValue.Columns.Add(ID); dtCodeValue.Columns.Add(Description); dtCodeValue.Columns.Add(Abbreviation); dtCodeValue.Columns.Add(ValueExtended); dgvCodeValue.DataSource = dtCodeValue; } private void btnCodeTypeList_Click(object sender, EventArgs e) { } private void UIReferenceData_Load(object sender, EventArgs e) { LoadCodeType(); cbxCodeType.SelectedIndex = 0; cbxCodeType.Focus(); } private void LoadCodeType() { codeTypeList = new CodeTypeList(); codeTypeList.List(); cbxCodeType.Items.Clear(); foreach (CodeType c in codeTypeList.codeTypeList) { cbxCodeType.Items.Add(c.Code); } ucCodeType1.Visible = false; ucCodeValue1.Visible = false; } private void cbxCodeType_SelectedIndexChanged(object sender, EventArgs e) { string valueSelected = cbxCodeType.SelectedItem.ToString(); loadCodeValue(valueSelected); } // // List values // private void loadCodeValue( string codeType ) { dtCodeValue.Clear(); var codeList = new CodeValueList(); codeList.List( codeType ); foreach (CodeValue code in codeList.codeValueList) { DataRow elementRow = dtCodeValue.NewRow(); elementRow["FKCodeType"] = code.FKCodeType; elementRow["ID"] = code.ID; elementRow["Description"] = code.Description; elementRow["Abbreviation"] = code.Abbreviation; elementRow["ValueExtended"] = code.ValueExtended; dtCodeValue.Rows.Add(elementRow); } } private void groupBox2_Enter(object sender, EventArgs e) { } private void btnNewType_Click(object sender, EventArgs e) { ucCodeValue1.Visible = false; if (ucCodeType1.Visible == true) ucCodeType1.Visible = false; else ucCodeType1.Visible = true; } private void btnCodeValueList_Click(object sender, EventArgs e) { } // // New code value // private void btnNewCodeValue_Click(object sender, EventArgs e) { CodeValueSelected(false); } private void ucCodeValue1_Load(object sender, EventArgs e) { } private void dgvCodeValue_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { CodeValueSelected(false); } private void cbxCodeType_Enter(object sender, EventArgs e) { LoadCodeType(); } // // // private void CodeValueSelected(bool RefreshOnly) { ucCodeType1.Visible = false; if (! RefreshOnly) { if (ucCodeValue1.Visible == true) { ucCodeValue1.Visible = false; string valueSelected = cbxCodeType.SelectedItem.ToString(); loadCodeValue(valueSelected); return; } ucCodeValue1.Visible = true; } if (dgvCodeValue.SelectedRows.Count <= 0) return; var selectedRow = dgvCodeValue.SelectedRows; ucCodeValue1.SetFKCodeType( selectedRow[0].Cells["FKCodeType"].Value.ToString()); ucCodeValue1.SetCodeID( selectedRow[0].Cells["ID"].Value.ToString()); ucCodeValue1.SetCodeDescription( selectedRow[0].Cells["Description"].Value.ToString()); ucCodeValue1.SetAbbreviation( selectedRow[0].Cells["Abbreviation"].Value.ToString()); ucCodeValue1.SetValueExtended( selectedRow[0].Cells["ValueExtended"].Value.ToString()); } private void dgvCodeValue_CellClick(object sender, DataGridViewCellEventArgs e) { CodeValueSelected(true); } private void dgvCodeValue_SelectionChanged(object sender, EventArgs e) { CodeValueSelected(true); } private void dgvCodeValue_CellBorderStyleChanged(object sender, EventArgs e) { } private void newCodeValueToolStripMenuItem_Click(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelClientDocument { public class ClientDocumentSet { [Display( Name = "Document Unique ID" )] public int UID { get; set; } [Display( Name = "Client Unique ID" )] public int FKClientUID { get; set; } [Display( Name = "Description" )] public string Description { get; set; } public string CombinedIDName { get; set; } public string Folder { get; set; } public string FolderOnly { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string IsVoid { get; set; } [Display( Name = "Client Document Set ID" )] public int ClientSetID { get; set; } [Display( Name = "Source Folder" )] public string SourceFolder { get; set; } public string Status { get; set; } public string UserIdCreatedBy { get; set; } public string UserIdUpdatedBy { get; set; } public DateTime CreationDateTime { get; set; } public DateTime UpdateDateTime { get; set ; } public List<ClientDocumentSet> clientDocumentSetList { get; set; } public List<Document> listOfDocumentsInSet { get; set; } /// <summary> /// Constructor - Basic /// </summary> /// <param name="iClientUID"></param> /// <param name="iClientDocumentSetUID"></param> public ClientDocumentSet() { } /// <summary> /// Constructor retrieving client set information /// </summary> /// <param name="iClientUID"></param> /// <param name="iClientDocumentSetUID"></param> public ClientDocumentSet(int iClientUID, int iClientDocumentSetUID) { this.Get(iClientUID, iClientDocumentSetUID); } /// <summary> /// Constructor to set the client /// </summary> /// <param name="iClientUID"></param> /// <param name="iClientDocumentSetUID"></param> public ClientDocumentSet(int iClientUID) { FKClientUID = iClientUID; } // ----------------------------------------------------- // Get Client set // ----------------------------------------------------- public bool Get(int iClientUID, int iClientDocumentSetUID) { bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientDocumentSetFieldString() + " FROM ClientDocumentSet" + " WHERE " + " ClientSetID = " + iClientDocumentSetUID + " AND FKClientUID = " + iClientUID; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadObject(this, reader); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Get Client set using UID // ----------------------------------------------------- public bool Read() { bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = String.Format( " SELECT " + ClientDocumentSetFieldString() + " FROM ClientDocumentSet" + " WHERE " + " UID = {0} AND FKClientUID = {1}", this.UID, this.FKClientUID) ; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadObject(this, reader); } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientDocumentSet"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Retrieve last Document Set for a client // ----------------------------------------------------- private int GetLastUID(int iClientID) { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT FKClientUID , MAX(ClientSetID) LASTUID FROM ClientDocumentSet " + // "WHERE FKClientUID = " + iClientID + " GROUP BY FKClientUID " + " HAVING FKClientUID = " + iClientID; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Calculate the number of documents in the set /// </summary> /// <param name="iClientID"></param> /// <returns></returns> public int GetNumberOfDocuments() { int DocoCount = 0; DocoCount = RepClientDocument.GetNumberOfDocuments(this.FKClientUID, this.ClientSetID); return DocoCount; } // ----------------------------------------------------- // Add new Client Document Set // ----------------------------------------------------- public ResponseStatus Add(HeaderInfo headerInfo, MySqlConnection connection = null) { ResponseStatus response = new ResponseStatus(); response.Message = "Client Document Set Added Successfully"; UID = GetLastUID() + 1; ClientSetID = GetLastUID(this.FKClientUID) + 1; Description = "Client Set Number " + ClientSetID; IsVoid = "N"; Status = "DRAFT"; FolderOnly = "CLIENT" + FKClientUID.ToString().Trim() + "SET" + ClientSetID.ToString().Trim().PadLeft(4, '0'); Folder = MakConstant.SYSFOLDER.CLIENTFOLDER + @"\" + this.FolderOnly; CreationDateTime = headerInfo.CurrentDateTime; UpdateDateTime = headerInfo.CurrentDateTime; UserIdCreatedBy = headerInfo.UserID; UserIdUpdatedBy = headerInfo.UserID; // Default values DateTime _now = DateTime.Today; if (connection == null) { connection = new MySqlConnection(ConnString.ConnectionString); connection.Open(); } var commandString = ( "INSERT INTO ClientDocumentSet " + "(" + ClientDocumentSetFieldString() + ")" + " VALUES " + "( @UID " + ", @FKClientUID " + ", @ClientSetID " + ", @Description " + ", @Folder " + ", @FolderOnly " + ", @Status " + ", @StartDate " + ", @EndDate " + ", @SourceFolder " + ", @IsVoid " + ", @CreationDateTime " + ", @UpdateDateTime " + ", @UserIdCreatedBy " + ", @UserIdUpdatedBy " + ")" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@FKClientUID", MySqlDbType.Int32).Value = FKClientUID; command.Parameters.Add("@ClientSetID", MySqlDbType.Int32).Value = ClientSetID; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@Folder", MySqlDbType.VarChar).Value = Folder; command.Parameters.Add("@FolderOnly", MySqlDbType.VarChar).Value = FolderOnly; command.Parameters.Add("@Status", MySqlDbType.VarChar).Value = Status; command.Parameters.Add("@SourceFolder", MySqlDbType.VarChar).Value = SourceFolder; command.Parameters.Add("@StartDate", MySqlDbType.DateTime).Value = _now; command.Parameters.AddWithValue("@EndDate", "9999-12-31"); command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = IsVoid; command.Parameters.Add("@CreationDateTime", MySqlDbType.DateTime).Value = CreationDateTime; command.Parameters.Add("@UpdateDateTime", MySqlDbType.DateTime).Value = UpdateDateTime; command.Parameters.Add("@UserIdCreatedBy", MySqlDbType.VarChar).Value = UserIdCreatedBy; command.Parameters.Add("@UserIdUpdatedBy", MySqlDbType.VarChar).Value = UserIdUpdatedBy; command.ExecuteNonQuery(); } return response; } /// <summary> /// Create new document set. (Sub transaction) /// </summary> /// <param name="connection"></param> /// <param name="MySqlTransaction"></param> /// <param name="headerInfo"></param> /// <returns></returns> public ResponseStatus AddSubTransaction( MySqlConnection connection, MySqlTransaction MySqlTransaction, HeaderInfo headerInfo) { ResponseStatus response = new ResponseStatus(); response.Message = "Client Document Set Added Successfully"; this.UID = GetLastUID() + 1; this.ClientSetID = GetLastUID(this.FKClientUID) + 1; this.Description = "Client Set Number " + ClientSetID; this.IsVoid = "N"; this.Status = "DRAFT"; this.FolderOnly = "CLIENT" + this.FKClientUID.ToString().Trim() + "SET" + this.ClientSetID.ToString().Trim().PadLeft(4, '0'); this.Folder = MakConstant.SYSFOLDER.CLIENTFOLDER + @"\" + this.FolderOnly; this.CreationDateTime = System.DateTime.Now; this.UpdateDateTime = System.DateTime.Now; this.UserIdCreatedBy = Utils.UserID; this.UserIdUpdatedBy = Utils.UserID; // Default values DateTime _now = DateTime.Today; var commandString = ( "INSERT INTO ClientDocumentSet " + "(" + ClientDocumentSetFieldString() + ")" + " VALUES " + "( @UID " + ", @FKClientUID " + ", @ClientSetID " + ", @Description " + ", @Folder " + ", @FolderOnly " + ", @Status " + ", @StartDate " + ", @EndDate " + ", @SourceFolder " + ", @IsVoid " + ", @CreationDateTime " + ", @UpdateDateTime " + ", @UserIdCreatedBy " + ", @UserIdUpdatedBy " + ")" ); var command = new MySqlCommand(commandString, connection, MySqlTransaction); command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@FKClientUID", MySqlDbType.Int32).Value = FKClientUID; command.Parameters.Add("@ClientSetID", MySqlDbType.Int32).Value = ClientSetID; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@Folder", MySqlDbType.VarChar).Value = Folder; command.Parameters.Add("@FolderOnly", MySqlDbType.VarChar).Value = FolderOnly; command.Parameters.Add("@Status", MySqlDbType.VarChar).Value = Status; command.Parameters.Add("@SourceFolder", MySqlDbType.VarChar).Value = SourceFolder; command.Parameters.Add("@StartDate", MySqlDbType.DateTime).Value = _now; command.Parameters.Add("@EndDate", MySqlDbType.DateTime).Value = DateTime.MaxValue; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = IsVoid; command.Parameters.Add("@CreationDateTime", MySqlDbType.DateTime).Value = CreationDateTime; command.Parameters.Add("@UpdateDateTime", MySqlDbType.DateTime).Value = UpdateDateTime; command.Parameters.Add("@UserIdCreatedBy", MySqlDbType.VarChar).Value = UserIdCreatedBy; command.Parameters.Add("@UserIdUpdatedBy", MySqlDbType.VarChar).Value = UserIdUpdatedBy; command.ExecuteNonQuery(); return response; } // ----------------------------------------------------- // Update Client Document Set // ----------------------------------------------------- public ResponseStatus Update() { ResponseStatus responseStatus = new ResponseStatus(MessageType.Informational); responseStatus.Message = "Document Set updated successfully"; // Default values this.UpdateDateTime = DateTime.Today; this.UserIdUpdatedBy = Utils.UserID; if (string.IsNullOrEmpty( this.SourceFolder)) { LogFile.WriteToTodaysLogFile("Error: Source folder not supplied. UID: " + this.UID + " Client UID: "+this.FKClientUID); this.SourceFolder = ""; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientDocumentSet " + " SET " + " Description = @Description " + ",Folder = @Folder " + ",SourceFolder = @SourceFolder " + ",UpdateDateTime = @UpdateDateTime " + ",UserIdUpdatedBy = @UserIdUpdatedBy " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = UID; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@Folder", MySqlDbType.VarChar).Value = Folder; command.Parameters.Add("@SourceFolder ", MySqlDbType.VarChar).Value = SourceFolder; command.Parameters.Add("@UpdateDateTime ", MySqlDbType.DateTime).Value = UpdateDateTime; command.Parameters.Add("@UserIdUpdatedBy ", MySqlDbType.VarChar).Value = UserIdUpdatedBy; try { connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), null, null, "ClientDocumentSet.cs"); ResponseStatus responseStatusError = new ResponseStatus(MessageType.Error); responseStatusError.Message = "Error updating documentset " + ex; responseStatusError.ReturnCode = -0010; responseStatusError.ReasonCode = 0002; } } } return responseStatus; } /// <summary> /// Database fields /// </summary> public struct FieldName { public const string UID = "UID"; public const string FKClientUID = "FKClientUID"; public const string ClientSetID = "ClientSetID"; public const string Description = "Description"; public const string Folder = "Folder"; public const string FolderOnly = "FolderOnly"; public const string Status = "Status"; public const string StartDate = "StartDate"; public const string EndDate = "EndDate"; public const string SourceFolder = "SourceFolder"; public const string IsVoid = "IsVoid"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; } /// <summary> /// Client string of fields. /// </summary> /// <returns></returns> private static string ClientDocumentSetFieldString() { return ( FieldName.UID + "," + FieldName.FKClientUID + "," + FieldName.ClientSetID + "," + FieldName.Description + "," + FieldName.Folder + "," + FieldName.FolderOnly + "," + FieldName.Status + "," + FieldName.StartDate + "," + FieldName.EndDate + "," + FieldName.SourceFolder + "," + FieldName.IsVoid + "," + FieldName.CreationDateTime + "," + FieldName.UpdateDateTime + "," + FieldName.UserIdCreatedBy + "," + FieldName.UserIdUpdatedBy ); } /// <summary> /// Load db data into memory /// </summary> /// <param name="obj"></param> /// <param name="reader"></param> private static void LoadObject(ClientDocumentSet obj, MySqlDataReader reader) { obj.UID = Convert.ToInt32(reader[FieldName.UID]); obj.FKClientUID = Convert.ToInt32(reader[FieldName.FKClientUID]); try { obj.Description = reader[FieldName.Description].ToString(); } catch { obj.Description = ""; } obj.Folder = reader[FieldName.Folder].ToString(); obj.FolderOnly = reader[FieldName.FolderOnly].ToString(); obj.StartDate = Convert.ToDateTime(reader[FieldName.StartDate].ToString()); obj.EndDate = Convert.ToDateTime(reader[FieldName.EndDate].ToString()); obj.ClientSetID = Convert.ToInt32(reader[FieldName.ClientSetID].ToString()); obj.SourceFolder = reader[FieldName.SourceFolder].ToString(); obj.Status = reader[FieldName.Status].ToString(); obj.IsVoid = reader[FieldName.IsVoid].ToString(); // Derived field obj.CombinedIDName = obj.FKClientUID + ";" + obj.ClientSetID + "; " + obj.Description + "; " + obj.Status; try { obj.UpdateDateTime = Convert.ToDateTime(reader[FieldName.UpdateDateTime].ToString()); } catch { obj.UpdateDateTime = DateTime.Now; } try { obj.CreationDateTime = Convert.ToDateTime(reader[FieldName.CreationDateTime].ToString()); } catch { obj.CreationDateTime = DateTime.Now; } try { obj.IsVoid = reader[FieldName.IsVoid].ToString(); } catch { obj.IsVoid = "N"; } try { obj.UserIdCreatedBy = reader[FieldName.UserIdCreatedBy].ToString(); } catch { obj.UserIdCreatedBy = "N"; } try { obj.UserIdUpdatedBy = reader[FieldName.UserIdCreatedBy].ToString(); } catch { obj.UserIdCreatedBy = "N"; } } /// <summary> /// Return a list of document sets for a given client. /// </summary> /// <param name="iClientUID"></param> /// <param name="sortOrder"></param> /// <returns></returns> public static List<ClientDocumentSet> List(int iClientUID, string sortOrder = "DESC") { List <ClientDocumentSet> documentSetList = new List<ClientDocumentSet>(); // cds.FKClientUID + ";" + cds.ClientSetID + "; " + cds.Description + "; " +cds.Status // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + ClientDocumentSetFieldString() + " FROM ClientDocumentSet " + " WHERE FKClientUID = '{0}' " + " ORDER BY ClientSetID " + sortOrder , iClientUID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ClientDocumentSet _clientDocumentSet = new ClientDocumentSet(); LoadObject(_clientDocumentSet, reader); documentSetList.Add(_clientDocumentSet); } } } } return documentSetList; } public List<Document> ListDocumentsNotInSet( HeaderInfo headerInfo, int clientUID, int clientDocumentSetUID ) { var documentsNotInSet = new List<Document>(); var documentsInSet = new List<ClientDocument>(); var fullListOfDocuments = new List<Document>(); fullListOfDocuments = RepDocument.ListDocuments( headerInfo ); documentsInSet = RepClientDocument.ListCD( clientUID, clientDocumentSetUID ); bool found = false; foreach ( var document in fullListOfDocuments ) { found = false; foreach ( var documentInSet in documentsInSet ) { // Document already in set if ( document.UID == documentInSet.FKDocumentUID ) { found = true; break; } } if ( found ) continue; // if gets to this point, document is not in set documentsNotInSet.Add( document ); } return documentsNotInSet; } public ClientDocument ListClientDocumentsByFolder( int clientUID, int clientDocumentSetUID) { ClientDocument listofdocuments = new ClientDocument(); listofdocuments.clientDocumentList = new List<ClientDocument>(); listofdocuments.clientDocSetDocLink = new List<scClientDocSetDocLink>(); listofdocuments.FKClientUID = clientUID; listofdocuments.clientDocumentSet.UID = clientDocumentSetUID; listofdocuments.FKClientDocumentSetUID = clientDocumentSetUID; // 1 - Get list of documents var clientDocumentListRequest = new BUSClientDocument.ClientDocumentListRequest(); clientDocumentListRequest.clientDocumentSetUID = clientDocumentSetUID; clientDocumentListRequest.clientUID = clientUID; var clientDocumentListResponse = BUSClientDocument.List(clientDocumentListRequest); // 2 - Move into a tree to order TreeView tvFileList = new TreeView(); tvFileList.Nodes.Clear(); ListInTree(tvFileList, "CLIENT", clientDocumentListResponse.clientList); if (tvFileList.Nodes.Count > 0) tvFileList.Nodes[0].Expand(); // 3 - Move to an ordered list foreach (TreeNode documentNode in tvFileList.Nodes) { var docnode = (scClientDocSetDocLink) documentNode.Tag; listofdocuments.clientDocSetDocLink.Add(docnode); // If there are inner nodes // if (documentNode.Nodes.Count > 0) { ListInOrder(documentNode, listofdocuments.clientDocSetDocLink); } } // 4 - Return list return listofdocuments; } private void ListInOrder(TreeNode treeNode, List<scClientDocSetDocLink> documentList) { foreach (TreeNode node in treeNode.Nodes) { var scClientDocSetDocLink = (scClientDocSetDocLink) node.Tag; documentList.Add(scClientDocSetDocLink); if (node.Nodes.Count > 0) { ListInOrder(node, documentList); } } } private static void ListInTree(TreeView fileList, string listType, List<scClientDocSetDocLink> clientDocSetDocLink) { // listType = CLIENT // listType = FCM = default; string ListType = listType; if (ListType == null) ListType = "FCM"; foreach (var docLinkSet in clientDocSetDocLink) { // Check if folder has a parent string cdocumentUID = docLinkSet.clientDocument.UID.ToString(); string cparentIUID = docLinkSet.clientDocument.ParentUID.ToString(); TreeNode treeNode = new TreeNode(); int image = 0; int imageSelected = 0; docLinkSet.clientDocument.RecordType = docLinkSet.clientDocument.RecordType.Trim(); image = FCMUtils.Utils.GetFileImage(docLinkSet.clientDocument.SourceFilePresent, docLinkSet.clientDocument.DestinationFilePresent, docLinkSet.clientDocument.DocumentType); imageSelected = image; string treenodename = docLinkSet.document.FileName; if (string.IsNullOrEmpty(treenodename)) treenodename = docLinkSet.clientDocument.FileName; if (string.IsNullOrEmpty(treenodename)) treenodename = "Error: Name not found"; treeNode = new TreeNode(treenodename, image, imageSelected); if (docLinkSet.clientDocument.ParentUID == 0) { treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find(cparentIUID, true); if (node.Count() > 0) { treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; node[0].Nodes.Add(treeNode); } else { // Add Element to the root // treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add(treeNode); } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCDocument.Service { public class BUSDocument { /// <summary> /// List of documents /// </summary> public static DocumentListResponse DocumentListX(DocumentListRequest documentListRequest) { var documentListResponse = new DocumentListResponse(); documentListResponse.response = new ResponseStatus(); documentListResponse.documentList = RepDocument.List( documentListRequest.headerInfo, documentListRequest.inCondition ); return documentListResponse; } /// <summary> /// List of documents /// </summary> public static DocumentListResponse DocumentListDocuments( DocumentListRequest documentListRequest ) { var documentListResponse = new DocumentListResponse(); documentListResponse.response = new ResponseStatus(); documentListResponse.documentList = RepDocument.ListDocuments( documentListRequest.headerInfo ); return documentListResponse; } /// <summary> /// List of documents /// </summary> public static DocumentListResponse FolderAndDocumentList(DocumentListRequest documentListRequest) { var documentListResponse = new DocumentListResponse(); documentListResponse.response = new ResponseStatus(); documentListResponse.documentList = RepDocument.ListFoldersAndDocuments(documentListRequest.headerInfo); return documentListResponse; } /// <summary> /// List of documents /// </summary> public static DocumentListResponse DocumentListFolders( DocumentListRequest documentListRequest ) { var documentListResponse = new DocumentListResponse(); documentListResponse.response = new ResponseStatus(); documentListResponse.documentList = RepDocument.ListFolders( documentListRequest.headerInfo ); return documentListResponse; } /// <summary> /// Retrieve document details /// </summary> /// <param name="documentReadRequest"></param> /// <returns></returns> public static DocumentReadResponse DocumentRead(DocumentReadRequest documentReadRequest) { var documentRead = RepDocument.Read( documentReadRequest.retrieveVoidedDocuments, documentReadRequest.UID, documentReadRequest.CUID); var documentReadResponse = new DocumentReadResponse(); documentReadResponse.document = documentRead; documentReadResponse.response = new ResponseStatus(MessageType.Informational); return documentReadResponse; } /// <summary> /// Retrieve document details /// </summary> /// <returns></returns> public static Document GetRootDocument() { var documentRead = RepDocument.Read(false,0,"ROOT"); return documentRead; } /// <summary> /// Set document to void /// </summary> /// <param name="documentUID"></param> public static void SetToVoid(int documentUID) { RepDocument.SetToVoid(documentUID); return; } /// <summary> /// Delete document /// </summary> /// <param name="documentUID"></param> public static void DeleteDocument(int documentUID) { RepDocument.Delete(documentUID); return; } /// <summary> /// Update or Create document /// </summary> /// <param name="documentSaveRequest"></param> /// <returns></returns> public static DocumentSaveResponse DocumentSave(DocumentSaveRequest documentSaveRequest) { var repDocSaveResp = RepDocument.Save( documentSaveRequest.headerInfo, documentSaveRequest.inDocument, documentSaveRequest.saveType); var documentSaveResponse = new DocumentSaveResponse(); documentSaveResponse.document = documentSaveRequest.inDocument; documentSaveResponse.document.UID = repDocSaveResp; if( repDocSaveResp == 0) { documentSaveResponse.response = new ResponseStatus( MessageType.Error); documentSaveResponse.response.Message = "Error Saving Document."; documentSaveResponse.response.Successful = false; documentSaveResponse.response.ReturnCode = -0010; } else { documentSaveResponse.response = new ResponseStatus( MessageType.Informational ); } return documentSaveResponse; } /// <summary> /// Update or Create document /// </summary> /// <returns></returns> public static Document DocumentCreate( HeaderInfo headerInfo, string filename, string filelocation, int parentUID, string recordtype = "DOCUMENT" ) { string documenttype = "WORD"; // Just setting as initial value Document document = new Document(); document.ParentUID = parentUID; document.CUID = filename.Substring( 0, 6 ); document.Location = filelocation; document.Location = Utils.getReferenceFilePathName(filelocation); document.DisplayName = filename.Substring(10); // Starts after HRM-01-01 HERExxxxxxxx document.SimpleFileName = filename.Substring(10); // Starts after HRM-01-01 HERExxxxxxxx document.Name = filename; var filesplit = filename.Split('.'); document.FileExtension = String.Concat("." + filesplit[1]); document.FileName = filename; document.RecordType = recordtype; string wordExtensions = ".doc .docx .dotx"; string excelExtensions = ".xls .xlsx"; string pdfExtensions = ".pdf"; // Not every extension will be loaded // if (wordExtensions.Contains(document.FileExtension)) documenttype = "WORD"; if (excelExtensions.Contains(document.FileExtension)) documenttype = "EXCEL"; if (pdfExtensions.Contains(document.FileExtension)) documenttype = "PDF"; document.DocumentType = documenttype; document.SequenceNumber = 1; document.IssueNumber = 1; document.SourceCode = "FCM"; document.Status = "ACTIVE"; document.Skip = "N"; document.IsVoid = "N"; document.IsProjectPlan = "N"; document.FKClientUID = 0; document.Comments = "Web Upload"; var documentSaveRequest = new DocumentSaveRequest(); documentSaveRequest.inDocument = document; documentSaveRequest.headerInfo = headerInfo; var docresp = BUSDocument.DocumentSave( documentSaveRequest ); if (docresp.response.ReturnCode <= 0) { LogFile.WriteToTodaysLogFile(docresp.response.Message); } document = docresp.document; return document; } /// <summary> /// Create new versions /// </summary> /// <param name="documentSaveRequest"></param> /// <returns></returns> public static DocumentNewVersionResponse DocumentNewVersion( DocumentNewVersionRequest documentSaveRequest) { var repNewVersionResp = RepDocument.NewVersion( documentSaveRequest.headerInfo, documentSaveRequest.inDocument); return repNewVersionResp; } /// <summary> /// List of clients /// </summary> public static DocumentListResponse DocumentList(HeaderInfo headerInfo) { var documentListResponse = new DocumentListResponse(); documentListResponse.response = new ResponseStatus(); documentListResponse.documentList = RepDocument.List(headerInfo); return documentListResponse; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using MackkadoITFramework.Utils; using System.Configuration; namespace MackkadoITFramework.Helper { public class WebAPIHelper { private static string gufcWebAPIURI; private static string gufcConnectionString; public static string GUFCWebAPIURI { get { if (string.IsNullOrEmpty(gufcWebAPIURI)) { // gufcWebAPIURI = XmlConfig.GUFCRead(MakConstant.ConfigXml.GUFCWebAPIURI); gufcWebAPIURI = ConfigurationManager.AppSettings["gufcapiuri"]; } return gufcWebAPIURI; } set { gufcWebAPIURI = value; } } public static string GUFCConnectionString { get { if (string.IsNullOrEmpty(gufcWebAPIURI)) { gufcWebAPIURI = XmlConfig.GUFCRead(MakConstant.ConfigXml.GUFCConnectionString); } return gufcWebAPIURI; } set { gufcWebAPIURI = value; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary { public class BUSUserSetting { /// <summary> /// Client document read /// </summary> /// <param name="clientContract"></param> /// <returns></returns> public static ResponseStatus Save(UserSettings inUserSetting) { ResponseStatus response = new ResponseStatus(); UserSettings userSetting = new UserSettings(); userSetting.FKUserID = inUserSetting.FKUserID; userSetting.FKScreenCode = inUserSetting.FKScreenCode; userSetting.FKControlCode = inUserSetting.FKControlCode; userSetting.FKPropertyCode = inUserSetting.FKPropertyCode; userSetting.Value = inUserSetting.Value; userSetting.Save(); FCMUtils.Utils.RefreshCache(); response.Contents = userSetting.ListOfUserSettings; return response; } } } <file_sep>using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Contract { public class ClientContractAddRequest { public HeaderInfo headerInfo; public ClientContract clientContract; } public class ClientContractAddResponse { public ClientContract clientContract; public ResponseStatus responseStatus; } public class ClientContractUpdateRequest { public HeaderInfo headerInfo; public ClientContract clientContract; } public class ClientContractUpdateResponse { public ClientContract clientContract; public ResponseStatus responseStatus; } public class ClientContractDeleteRequest { public HeaderInfo headerInfo; public ClientContract clientContract; } public class ClientContractDeleteResponse { public ClientContract clientContract; public ResponseStatus responseStatus; } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using Google.GData.Client; using Google.GData.Documents; using fcm.Windows.Google.Model; using System.Diagnostics; using FCMMySQLBusinessLibrary; namespace fcm.Windows { public partial class UIGoogleDocs : Form { //The parent form to this one. ModelGoogle modelGoogle; private TreeNode tndocSelected; string destinationFolder; public UIGoogleDocs(string DestinationFolder) { InitializeComponent(); modelGoogle = new ModelGoogle(); destinationFolder = DestinationFolder; Username.Text = "<EMAIL>"; } private void UIGoogleDocs_Load( object sender, EventArgs e ) { // Image list // ImageList imageList = ControllerUtils.GetImageList(); tvFileList.ImageList = imageList; tvGoogle.ImageList = imageList; // Clear nodes tvFileList.Nodes.Clear(); tvGoogle.Nodes.Clear(); loadDocumentList(); } // // Load documents for a Client Document Set // private void loadDocumentList() { // List client document list // var documentSetList = new ClientDocument(); //documentSetList.List( Utils.ClientID, Utils.ClientSetID ); var request = new BUSClientDocument.ClientDocumentListRequest(); request.clientDocumentSetUID = Utils.ClientSetID; request.clientUID = Utils.ClientID; BUSClientDocument.List( request ); tvFileList.Nodes.Clear(); // documentSetList.ListInTree( tvFileList, "CLIENT" ); BUSClientDocument.ListInTree(documentSetList, tvFileList, "CLIENT" ); if (tvFileList.Nodes.Count > 0) tvFileList.Nodes[0].Expand(); } private void LoginButton_Click( object sender, EventArgs e ) { if (Username.Text == "") { MessageBox.Show( "Please specify a username", "No user name", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } if (Password.Text == "") { MessageBox.Show( "Please specify a password", "No password", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } try { LoginButton.Text = "Logging In"; UploaderStatus.Text = "Connecting to server..."; LoginButton.Enabled = false; LogoutButton.Enabled = true; RefreshButton.Enabled = true; Username.Enabled = false; Password.Enabled = false; modelGoogle.Login( Username.Text, Password.Text ); LoginButton.Text = "Logged In"; UploaderStatus.Text = "Login complete"; } catch (Exception ex) { LoginButton.Enabled = true; LogoutButton.Enabled = false; Username.Enabled = true; Password.Enabled = true; RefreshButton.Enabled = false; LoginButton.Text = "Login"; UploaderStatus.Text = "Error authenticating"; MessageBox.Show( "Error logging into Google Docs: " + ex.Message, "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } /// <summary> /// Gets a new list of documents from the server and renders /// them in the ListView called DocList on the form. /// </summary> public void UpdateDocList() { if (!modelGoogle.loggedIn) { MessageBox.Show( "Log in before retrieving documents.", "Log in", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } DocList.Items.Clear(); tvGoogle.Nodes.Clear(); try { DocumentsFeed feed = modelGoogle.GetDocs(); foreach (DocumentEntry entry in feed.Entries) { string imageKey = ""; if (entry.IsDocument) { imageKey = "Document.gif"; } else if (entry.IsSpreadsheet) { imageKey = "Spreadsheet.gif"; } else { imageKey = "Presentation.gif"; } ListViewItem item = new ListViewItem( entry.Title.Text, imageKey ); item.SubItems.Add( entry.Updated.ToString() ); item.Tag = entry; DocList.Items.Add( item ); } foreach (ColumnHeader column in DocList.Columns) { column.AutoResize( ColumnHeaderAutoResizeStyle.ColumnContent ); } ModelGoogle.LoadGoogleDocsInTree( tvGoogle, feed ); } catch (Exception e) { MessageBox.Show( "Error retrieving documents: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } /// <summary> /// Logout from google /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LogoutButton_Click( object sender, EventArgs e ) { modelGoogle.Logout(); LoginButton.Enabled = true; LogoutButton.Enabled = false; Username.Enabled = true; Password.Enabled = true; RefreshButton.Enabled = false; LoginButton.Text = "Login"; UploaderStatus.Text = "Logged out."; } private void uploadDocumentToolStripMenuItem_Click( object sender, EventArgs e ) { if (!modelGoogle.loggedIn) { MessageBox.Show( "Please log in before uploading documents", "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // // Get selected document from tree // tndocSelected = tvFileList.SelectedNode; var rm = new scClientDocSetDocLink(); if (tndocSelected == null) return; UploadDocument( tndocSelected ); } /// <summary> /// Upload document list /// </summary> /// <param name="document"></param> private void UploadDocument( TreeNode docSelected ) { var rm = new scClientDocSetDocLink(); rm = (scClientDocSetDocLink)docSelected.Tag; // Cast if (rm.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.FOLDER) { foreach (TreeNode tn in docSelected.Nodes) { // Print Document var docToPrint = new scClientDocSetDocLink(); docToPrint = (scClientDocSetDocLink)docSelected.Tag; UploadDocument( tn ); } } else { // Utils.OpenDocument( txtDestinationFolder.Text + rm.clientDocument.Location, rm.clientDocument.FileName, rm.clientDocument.DocumentType ); string file = Utils.getFilePathName(destinationFolder + rm.clientDocument.Location, rm.clientDocument.FileName ); try { UploaderStatus.Text = "Uploading " + file; this.Refresh(); modelGoogle.UploadFile( file ); UploaderStatus.Text = "Successfully uploaded " + file; UpdateDocList(); } catch (ArgumentException) { DialogResult result = MessageBox.Show( "Error, unable to upload the file: '" + file + "'. It is not one of the valid types.", "Upload Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error ); UploaderStatus.Text = "Problems uploading"; if (result == DialogResult.Cancel) { return; } } catch (Exception ex) { DialogResult result = MessageBox.Show( "Error, unable to upload the file: '" + file + "'. " + ex.Message, "Upload Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error ); UploaderStatus.Text = "Problems uploading"; if (result == DialogResult.Cancel) { return; } } } } private void OpenMenuItem_Click( object sender, EventArgs e ) { if (DocList.SelectedItems.Count > 0) { DocumentEntry entry = (DocumentEntry)DocList.SelectedItems[0].Tag; try { Process.Start( entry.AlternateUri.ToString() ); } catch (Win32Exception) { //nothing is registered to handle URLs, so let's use IE! Process.Start( "IExplore.exe", entry.AlternateUri.ToString() ); } } TreeNode tn = tvGoogle.SelectedNode; if (tn != null) { DocumentEntry entry = (DocumentEntry)tn.Tag; try { Process.Start( entry.AlternateUri.ToString() ); } catch (Win32Exception) { //nothing is registered to handle URLs, so let's use IE! Process.Start( "IExplore.exe", entry.AlternateUri.ToString() ); } } } private void DeleteMenuItem_Click( object sender, EventArgs e ) { if (DocList.SelectedItems.Count > 0) { DocumentEntry entry = (DocumentEntry)DocList.SelectedItems[0].Tag; DialogResult result = MessageBox.Show( "Are you sure you want to delete " + entry.Title.Text + "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning ); if (result == DialogResult.Yes) { try { entry.Delete(); UpdateDocList(); } catch (Exception ex) { MessageBox.Show( "Error when deleting: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } TreeNode tn = tvGoogle.SelectedNode; if (tn != null && tvGoogle.Tag != null) { DocumentEntry entry = (DocumentEntry)tvGoogle.Tag; DialogResult result = MessageBox.Show( "Are you sure you want to delete " + entry.Title.Text + "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning ); if (result == DialogResult.Yes) { try { entry.Delete(); UpdateDocList(); } catch (Exception ex) { MessageBox.Show( "Error when deleting: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } } private void RefreshButton_Click( object sender, EventArgs e ) { UpdateDocList(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary { public class UserSettings { public List<UserSettings> ListOfUserSettings; #region Properties public string FKUserID { get { return _FKUserID; } set { _FKUserID = value; } } public string FKScreenCode { get { return _FKScreenCode; } set { _FKScreenCode = value; } } public string FKControlCode { get { return _FKControlCode; } set { _FKControlCode = value; } } public string FKPropertyCode { get { return _FKPropertyCode; } set { _FKPropertyCode = value; } } public string Value { get { return _Value; } set { _Value = value; } } #endregion Properties #region Attributes private string _FKUserID; // Key private string _FKScreenCode; // Key private string _FKControlCode; // Key private string _FKPropertyCode; // Key private string _Value; #endregion Attributes #region FieldName public struct FieldName { public const string FKUserID = "FKUserID"; public const string FKScreenCode = "FKScreenCode"; public const string FKControlCode = "FKControlCode"; public const string FKPropertyCode = "FKPropertyCode"; public const string Value = "Value"; } #endregion FieldName /// <summary> /// Constructor /// </summary> public UserSettings() { ListOfUserSettings = new List<UserSettings>(); } /// <summary> /// List user settings for a given user /// </summary> /// <returns></returns> public static List<UserSettings> List( string userID ) { List<UserSettings> userSettingList = new List<UserSettings>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + SQLConcat() + " FROM UserSettings " + " WHERE " + " FKUserID = @FKUserID " + " ORDER BY FKUserID ASC, FKScreenCode ASC "; using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add("@FKUserID", MySqlDbType.VarChar).Value = userID.Trim(); connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var docItem = SetDocumentItem(reader); // Check if document exists // userSettingList.Add(docItem); } } } } return userSettingList; } /// <summary> /// Save details. Create or Update accordingly. /// </summary> public void Save() { var checkOnly = new UserSettings(); checkOnly._FKUserID = _FKUserID; checkOnly._FKScreenCode = _FKScreenCode; checkOnly._FKControlCode = _FKControlCode; checkOnly._FKPropertyCode = _FKPropertyCode; if (checkOnly.Read()) { Update(); } else { Insert(); } } /// <summary> /// Retrieve user setting details /// </summary> public bool Read() { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + UserSettingString() + " FROM UserSettings" + " WHERE " + FieldName.FKUserID + " = @FKUserID AND " + FieldName.FKScreenCode + " = @FKScreenCode AND " + FieldName.FKControlCode + " = @FKControlCode AND " + FieldName.FKPropertyCode + " = @FKPropertyCode "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKUserID", MySqlDbType.VarChar).Value = FKUserID; command.Parameters.Add("@FKScreenCode", MySqlDbType.VarChar).Value = FKScreenCode; command.Parameters.Add("@FKControlCode", MySqlDbType.VarChar).Value = FKControlCode; command.Parameters.Add("@FKPropertyCode", MySqlDbType.VarChar).Value = FKPropertyCode; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadClientObject(reader, this); ret = true; } catch (Exception) { FKUserID = ""; } } } } return ret; } /// <summary> /// Load client object /// </summary> /// <param name="reader"></param> private static void LoadClientObject(MySqlDataReader reader, UserSettings client) { client.FKUserID = reader[FieldName.FKUserID].ToString(); client.FKScreenCode = reader[FieldName.FKScreenCode].ToString(); client.FKControlCode = reader[FieldName.FKControlCode].ToString(); client.FKPropertyCode = reader[FieldName.FKPropertyCode].ToString(); client.Value = reader[FieldName.Value].ToString(); } /// <summary> /// Update user setting details /// </summary> public void Update() { DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE UserSettings " + " SET " + FieldName.Value + " = @" + FieldName.Value + " WHERE " + FieldName.FKUserID + " = @" + FieldName.FKUserID + " AND " + FieldName.FKScreenCode + " = @" + FieldName.FKScreenCode + " AND " + FieldName.FKControlCode + " = @" + FieldName.FKControlCode + " AND " + FieldName.FKPropertyCode + " = @" + FieldName.FKPropertyCode ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command, MakConstant.SQLAction.UPDATE); connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Add new user setting /// </summary> /// <returns></returns> public void Insert() { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO UserSettings " + "(" + UserSettingString() + ")" + " VALUES " + "( @FKUserID " + ", @FKScreenCode " + ", @FKControlCode " + ", @FKPropertyCode " + ", @Value " + ")" ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command, MakConstant.SQLAction.CREATE); connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Client string of fields. /// </summary> /// <returns></returns> private static string UserSettingString() { return ( FieldName.FKUserID + "," + FieldName.FKScreenCode + "," + FieldName.FKControlCode + "," + FieldName.FKPropertyCode + "," + FieldName.Value ); } /// <summary> /// Add SQL Parameters /// </summary> /// <param name="command"></param> /// <param name="action"></param> private void AddSQLParameters(MySqlCommand command, string action) { command.Parameters.Add("@Value", MySqlDbType.VarChar).Value = Value; command.Parameters.Add("@FKUserID", MySqlDbType.VarChar).Value = FKUserID; command.Parameters.Add("@FKScreenCode", MySqlDbType.VarChar).Value = FKScreenCode; command.Parameters.Add("@FKControlCode", MySqlDbType.VarChar).Value = FKControlCode; command.Parameters.Add("@FKPropertyCode", MySqlDbType.VarChar).Value = FKPropertyCode; } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <returns></returns> public static string SQLConcat() { string ret = " " + FieldName.FKScreenCode+ "," + FieldName.FKControlCode + "," + FieldName.FKPropertyCode + "," + FieldName.FKUserID + "," + FieldName.Value + " " ; return ret; } /// <summary> /// Set user setting values /// </summary> /// <param name="reader"></param> /// <returns></returns> private static UserSettings SetDocumentItem(MySqlDataReader reader) { var userSetting = new UserSettings(); userSetting.FKUserID = reader[FieldName.FKUserID].ToString(); userSetting.FKScreenCode = reader[FieldName.FKScreenCode].ToString(); userSetting.FKControlCode = reader[FieldName.FKControlCode].ToString(); userSetting.FKPropertyCode = reader[FieldName.FKPropertyCode].ToString(); userSetting.Value = reader[FieldName.Value].ToString(); return userSetting; } } } <file_sep>using System.IO; using Microsoft.Office.Interop.Word; namespace FCMMySQLBusinessLibrary.FCMWord { public class WordReportEngine { object missing = System.Reflection.Missing.Value; private object oFalse = false; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ _Application oWord; _Document oDoc; public string CreateReport() { if (oWord == null) { StartupWord(); } Clean(); var tempFile = Path.GetTempFileName(); Paste(); SaveAsRtf(tempFile); return tempFile; } private void Clean() { if (oDoc != null) { oDoc.Close(ref oFalse, ref missing, ref missing); } oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing); } private void StartupWord() { oWord = new Application(); oWord.Visible = false; oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing); } public void CloseWord() { if (oDoc != null) { oDoc.Close(ref oFalse, ref missing, ref missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); } if (oWord != null) { oWord.Quit(ref missing, ref missing, ref missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); } oDoc = null; oWord = null; } private void addText(string toPrint, int fontSize, int bold) { Paragraph oPara; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Font.Bold = bold; oPara.Range.Font.Size = fontSize; oPara.Range.Text = toPrint; oPara.Range.InsertParagraphAfter(); } public void Paste() { Paragraph oPara; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Paste(); oPara.Range.InsertParagraphAfter(); } internal void SaveAsRtf(object fileName) { object format = WdSaveFormat.wdFormatRTF; oDoc.SaveAs(ref fileName, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } } }<file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using System.Windows.Forms; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentSetDocumentLinkList { public List<DocumentSetDocumentLink> documentSetDocumentLinkList; public static DocumentSetDocumentLinkList ListRelatedDocuments(int documentSetUID, int documentUID, string type) { DocumentSetDocumentLinkList ret = new DocumentSetDocumentLinkList(); ret.documentSetDocumentLinkList = new List<DocumentSetDocumentLink>(); string linktype = ""; if (type == "ALL" || string.IsNullOrEmpty(type)) { // do nothing } else { linktype = " AND DSDL.LinkType = '" + type + "'"; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format ( "SELECT DSDL.UID DSDLUID " + " ,DSDL.FKParentDocumentUID DSDLFKParentDocumentUID " + " ,DSDL.FKChildDocumentUID DSDLFKChildDocumentUID " + " ,DSDL.LinkType DSDLLinkType " + " ,DSDL.IsVoid DSDLIsVoid " + " ," + RepDocument.SQLDocumentConcat("DOCUMENTCHILD") + " ," + RepDocument.SQLDocumentConcat("DOCUMENTPARENT") + " ," + RepDocumentSetDocument.SQLDocumentConcat("DSDCHILD") + " ," + RepDocumentSetDocument.SQLDocumentConcat("DSDPARENT") + " " + " FROM DocumentSetDocumentLink DSDL " + " ,DocumentSetDocument DSDCHILD " + " ,DocumentSetDocument DSDPARENT " + " ,Document DOCUMENTCHILD " + " ,Document DOCUMENTPARENT " + " WHERE " + " DSDL.IsVoid = 'N' " + " AND DSDL.FKParentDocumentUID = {0} " + linktype + " AND DSDL.FKDocumentSetUID = {1} " + " AND DSDL.FKChildDocumentUID = DSDCHILD.UID " + " AND DSDL.FKParentDocumentUID = DSDPARENT.UID " + " AND DSDCHILD.FKDocumentUID = DOCUMENTCHILD.UID " + " AND DSDPARENT.FKDocumentUID = DOCUMENTPARENT.UID " , documentUID , documentSetUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { DocumentSetDocumentLink _Document = new DocumentSetDocumentLink(); _Document.documentChild = new Model.ModelDocument.Document(); _Document.documentParent = new Model.ModelDocument.Document(); _Document.documentSetDocumentChild = new DocumentSetDocument(); _Document.documentSetDocumentParent = new DocumentSetDocument(); // Link information // _Document.FKChildDocumentUID = Convert.ToInt32(reader["DSDLFKChildDocumentUID"].ToString()); _Document.FKParentDocumentUID = Convert.ToInt32(reader["DSDLFKParentDocumentUID"].ToString()); _Document.LinkType = reader["DSDLLinkType"].ToString(); _Document.documentParent.UID = Convert.ToInt32(reader["DOCUMENTPARENTUID"].ToString()); _Document.documentParent.SimpleFileName = reader["DOCUMENTPARENTUID"].ToString(); _Document.documentParent.CUID = reader["DOCUMENTPARENTSimpleFileName"].ToString(); _Document.documentParent.Name = reader["DOCUMENTPARENTName"].ToString(); _Document.documentChild.UID = Convert.ToInt32(reader["DOCUMENTCHILDUID"].ToString()); _Document.documentChild.CUID = reader["DOCUMENTCHILDSimpleFileName"].ToString(); _Document.documentChild.Name = reader["DOCUMENTCHILDName"].ToString(); _Document.documentChild.SequenceNumber = Convert.ToInt32(reader["DOCUMENTCHILDSequenceNumber"].ToString()); _Document.documentChild.IssueNumber = Convert.ToInt32(reader["DOCUMENTCHILDIssueNumber"].ToString()); _Document.documentChild.Location = reader["DOCUMENTCHILDLocation"].ToString(); _Document.documentChild.Comments = reader["DOCUMENTCHILDComments"].ToString(); _Document.documentChild.SourceCode = reader["DOCUMENTCHILDSourceCode"].ToString(); _Document.documentChild.FileName = reader["DOCUMENTCHILDFileName"].ToString(); _Document.documentChild.SimpleFileName = reader["DOCUMENTCHILDSimpleFileName"].ToString(); _Document.documentChild.FKClientUID = Convert.ToInt32(reader["DOCUMENTCHILDFKClientUID"].ToString()); _Document.documentChild.ParentUID = Convert.ToInt32(reader["DOCUMENTCHILDParentUID"].ToString()); _Document.documentChild.RecordType = reader["DOCUMENTCHILDRecordType"].ToString(); _Document.documentChild.IsProjectPlan = reader["DOCUMENTCHILDIsProjectPlan"].ToString(); _Document.documentChild.DocumentType = reader["DOCUMENTCHILDDocumentType"].ToString(); _Document.documentSetDocumentChild.UID = Convert.ToInt32(reader["DSDCHILDUID"].ToString()); _Document.documentSetDocumentChild.FKDocumentUID = Convert.ToInt32(reader["DSDCHILDFKDocumentUID"].ToString()); _Document.documentSetDocumentChild.FKDocumentSetUID = Convert.ToInt32(reader["DSDCHILDFKDocumentSetUID"].ToString()); _Document.documentSetDocumentChild.Location = reader["DSDCHILDLocation"].ToString(); _Document.documentSetDocumentChild.StartDate = Convert.ToDateTime(reader["DSDCHILDStartDate"].ToString()); _Document.documentSetDocumentChild.EndDate = Convert.ToDateTime(reader["DSDCHILDEndDate"].ToString()); _Document.documentSetDocumentChild.FKParentDocumentUID = Convert.ToInt32(reader["DSDCHILDFKParentDocumentUID"].ToString()); _Document.documentSetDocumentChild.SequenceNumber = Convert.ToInt32(reader["DSDCHILDSequenceNumber"].ToString()); _Document.documentSetDocumentChild.FKParentDocumentSetUID = Convert.ToInt32(reader["DSDCHILDFKParentDocumentSetUID"].ToString()); ret.documentSetDocumentLinkList.Add(_Document); } } } } return ret; } public static void ListInTree( TreeView fileList, DocumentSetDocumentLinkList documentList, Model.ModelDocument.Document root) { // Find root folder // Model.ModelDocument.Document rootDocument = new Model.ModelDocument.Document(); rootDocument.CUID = root.CUID; rootDocument.RecordType = root.RecordType; rootDocument.UID = root.UID; // rootDocument.Read(); rootDocument = RepDocument.Read(false, root.UID); // Create root // var rootNode = new TreeNode(rootDocument.Name, MakConstant.Image.Folder, MakConstant.Image.Folder); // Add root node to tree // fileList.Nodes.Add(rootNode); rootNode.Tag = rootDocument; rootNode.Name = rootDocument.Name; foreach (var document in documentList.documentSetDocumentLinkList) { int image = 0; image = Utils.ImageSelect(document.documentChild.RecordType.Trim()); var treeNode = new TreeNode(document.documentChild.Name, image, image); treeNode.Tag = document; treeNode.Name = document.LinkType; rootNode.Nodes.Add(treeNode); } } } } <file_sep>using System; using System.Windows.Forms; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class MasterSystemDocument { /// <summary> /// Generate master of system documents /// </summary> /// <param name="tv"></param> private ResponseStatus GenerateMasterOfSystemDocuments(TreeView tv) { ResponseStatus ret = new ResponseStatus(); object destinationFileName = "temp01.doc"; object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; Word.Application vkWordApp = new Word.Application(); Word.Document vkMyDoc; try { vkMyDoc = vkWordApp.Documents.Open( ref destinationFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); } catch (Exception ex) { ret.ReturnCode = -1; ret.ReasonCode = 1000; ret.Message = "Error creating file."; ret.Contents = ex; return ret; } return ret; } } } <file_sep>CREATE TABLE Client ( UID bigint NOT NULL, Name varchar NOT NULL, Address varchar, Phone varchar, Fax varchar, MainContactPersonName varchar, EmailAddress varchar, CreationDateTime datetime NOT NULL, EmailAddress varchar, UpdateDateTime datetime NOT NULL, UserIdCreatedBy char NOT NULL, UserIdUpdatedBy char NOT NULL, ABN varchar, IsVoid char, FKUserID varchar, FKDocumentSetUID bigint, RecordVersion bigint ) ; CREATE TABLE ClientContract ( FKCompanyUID bigint, UID bigint NOT NULL, ExternalID varchar, StartDate datetime, EndDate datetime, UserIdCreatedBy char, UserIdUpdatedBy char, CreationDateTime datetime, UpdateDateTime datetime, Status varchar, Type varchar ) ; CREATE TABLE ClientDocument ( UID bigint NOT NULL, DocumentCUID varchar, FKClientUID bigint, FKClientDocumentSetUID bigint, FKDocumentUID bigint, ComboIssueNumber varchar, ClientIssueNumber int, SourceIssueNumber int, Location varchar, EndDate datetime, StartDate datetime, IsVoid char NOT NULL, FileName varchar, SequenceNumber int, SourceLocation varchar, SourceFileName varchar, Generated char, ParentUID bigint, RecordType char, IsProjectPlan char, DocumentType varchar, Status varchar, IsRoot char, IsFlag char, IsFolder char ) ; CREATE TABLE ClientDocumentIssue ( UID bigint NOT NULL, FKClientDocumentUID bigint NOT NULL, ClientIssueNumber int NOT NULL, Location varchar(200), FileName varchar(100), IssueNumberText varchar(4), SourceIssueNumber int, ComboIssueNumber varchar(100) NOT NULL, DocumentCUID varchar(20), FKClientUID bigint ) ; CREATE TABLE ClientDocumentLink ( UID bigint NOT NULL, FKParentDocumentUID bigint NOT NULL, FKChildDocumentUID bigint NOT NULL, LinkType varchar NOT NULL, IsVoid char NOT NULL, FKClientDocumentSetUID bigint NOT NULL, FKClientUID bigint NOT NULL ) ; CREATE TABLE ClientDocumentSet ( UID bigint NOT NULL, FKClientUID bigint, Description varchar, Folder varchar, StartDate datetime, EndDate datetime, IsVoid char, ClientSetID bigint, SourceFolder varchar, Status varchar, CreationDateTime datetime, UpdateDateTime date, UserIdCreatedBy char, UserIdUpdatedBy char, FolderOnly varchar ) ; CREATE TABLE ClientDocumentVersion ( UID bigint NOT NULL, FKClientDocumentUID bigint NOT NULL, ClientIssueNumber int NOT NULL, Location varchar, FileName varchar, IssueNumberText varchar, SourceIssueNumber int, ComboIssueNumber varchar NOT NULL, DocumentCUID varchar, FKClientUID bigint ) ; CREATE TABLE ClientExtraInformation ( UID bigint NOT NULL, FKClientUID bigint, DateToEnterOnPolicies date, ScopeOfServices varchar, ActionPlanDate date, CertificationTargetDate date, TimeTrading varchar, RegionsOfOperation varchar, FrequencyOfOperations varchar, FrequencyOfProjectMeetings varchar, RecordVersion bigint ) ; CREATE TABLE ClientOtherInfo ( UID bigint NOT NULL, FKClientUID bigint, RCFieldCode varchar, FieldValueText varchar ) ; CREATE TABLE CodeRelated ( FKCodeTypeFrom varchar NOT NULL, FKCodeValueFrom varchar NOT NULL, FKCodeTypeTo varchar NOT NULL, FKCodeValueTo varchar NOT NULL ) ; CREATE TABLE CodeType ( CodeType varchar NOT NULL, Description varchar, ShortCodeType char ) ; CREATE TABLE CodeValue ( FKCodeType varchar NOT NULL, ID varchar NOT NULL, Description varchar, Abbreviation varchar, ValueExtended varchar ) ; CREATE TABLE Document ( UID bigint NOT NULL, SimpleFileName varchar, CUID varchar NOT NULL, Name varchar, SequenceNumber bigint NOT NULL, IssueNumber int, Location varchar, Comments varchar, FileName varchar, SourceCode varchar, FKClientUID bigint, IsVoid char, ParentUID bigint NOT NULL, RecordType char, FileExtension varchar, IsProjectPlan varchar, DocumentType varchar, Status varchar, CreationDateTime datetime, UpdateDateTime datetime, UserIdCreatedBy varchar, UserIdUpdatedBy varchar, RecordVersion bigint ) ; CREATE TABLE DocumentLink ( UID bigint NOT NULL, FKParentDocumentUID bigint NOT NULL, FKChildDocumentUID bigint NOT NULL, LinkType varchar NOT NULL, IsVoid char NOT NULL ) ; CREATE TABLE DocumentSet ( UID bigint NOT NULL, TemplateType varchar, TemplateFolder varchar, IsVoid char ) ; CREATE TABLE DocumentSetDocument ( UID bigint NOT NULL, FKDocumentUID bigint, FKDocumentSetUID bigint, Location varchar, IsVoid char, StartDate datetime, EndDate datetime, FKParentDocumentUID bigint, SequenceNumber bigint, FKParentDocumentSetUID bigint, DocumentType varchar ) ; CREATE TABLE DocumentSetDocumentLink ( UID bigint NOT NULL, FKDocumentSetUID bigint NOT NULL, FKParentDocumentUID bigint NOT NULL, FKChildDocumentUID bigint NOT NULL, LinkType varchar NOT NULL, IsVoid char NOT NULL ) ; CREATE TABLE DocumentSetLink ( UID bigint NOT NULL, FKDocumentUID bigint, FKDocumentSetUID bigint, DocumentIdentifier varchar(50), Location varchar(200), IsVoid char(1), StartDate datetime, EndDate datetime ) ; CREATE TABLE DocumentVersion ( UID bigint, FKDocumentUID bigint NOT NULL, FKDocumentCUID varchar NOT NULL, IssueNumber int NOT NULL, Location varchar, FileName varchar, CreationDateTime datetime, UpdateDateTime datetime, UserIdCreatedBy varchar, UserIdUpdatedBy varchar, IsVoid char ) ; CREATE TABLE Employee ( FKCompanyUID bigint, UID bigint NOT NULL, Name varchar, RoleType varchar, SequenceNumber int, Address varchar, Phone varchar, Fax varchar, EmailAddress varchar, IsAContact char, UserIdCreatedBy varchar, UserIdUpdatedBy varchar, CreationDateTime datetime, UpdateDateTime datetime ) ; CREATE TABLE FCMRole ( Role varchar NOT NULL, Description varchar NOT NULL ) ; CREATE TABLE FCMUser ( UserID varchar NOT NULL, Password varchar NOT NULL, Salt varchar NOT NULL, UserName varchar, LogonAttempts int ) ; CREATE TABLE FCMUserRole ( UniqueID int NOT NULL, FK_UserID varchar NOT NULL, FK_Role varchar NOT NULL, StartDate date NOT NULL, EndDate date, IsActive char, IsVoid char ) ; CREATE TABLE Metadata ( UID , FieldCode , CompanyType , CompanyUID , InformationType , TableName , FieldName , FilePath , FileName ) ; CREATE TABLE ProcessRequest ( UID bigint NOT NULL, Description varchar NOT NULL, FKClientUID bigint, Type varchar NOT NULL, Status varchar NOT NULL, WhenToProcess varchar NOT NULL, CreationDateTime datetime NOT NULL, PlannedDateTime datetime NOT NULL, StatusDateTime datetime NOT NULL, RequestedByUser varchar ) ; CREATE TABLE ProcessRequestArguments ( FKRequestUID bigint NOT NULL, Code varchar NOT NULL, ValueType varchar, Value varchar ) ; CREATE TABLE ProcessRequestResults ( FKRequestUID bigint NOT NULL, SequenceNumber bigint NOT NULL, FKClientUID bigint, LongText varchar NOT NULL, Type varchar ) ; CREATE TABLE RegisterofSystemDocuments ( DocumentNumber varchar NOT NULL, Directory varchar, SubDirectory varchar, IssueNumber decimal, DocumentName varchar, Comments varchar ) ; CREATE TABLE ReportMetadata ( UID bigint NOT NULL, RecordType varchar NOT NULL, FieldCode varchar, Description ntext, ClientType varchar, ClientUID bigint, InformationType varchar NOT NULL, TableNameX varchar, FieldNameX varchar, FilePathX varchar, FileNameX varchar, Condition ntext, CompareWith varchar, Enabled char ) ; CREATE TABLE sysdiagrams ( name sysname NOT NULL, principal_id int NOT NULL, diagram_id int identity(1,1) NOT NULL, version int, definition varbinary(max) ) ; CREATE TABLE UserSettings ( FKUserID varchar(50) NOT NULL, FKScreenCode varchar(50) NOT NULL, FKControlCode varchar(50) NOT NULL, FKPropertyCode varchar(50) NOT NULL, Value nchar(10) NOT NULL ) ; CREATE INDEX Client_idx ON Client (IsVoid ASC) ; CREATE INDEX ClientDocument_idx ON ClientDocument (FKClientUID ASC, FKClientDocumentSetUID ASC) ; CREATE INDEX ClientDocument_idx2 ON ClientDocument (FKClientUID ASC, FKDocumentUID ASC, FKClientDocumentSetUID ASC, IsVoid ASC) ; CREATE INDEX Document_idx2 ON Document (SourceCode ASC, FKClientUID ASC) ; CREATE INDEX IX_ClientUID_UID ON Document (FKClientUID ASC, UID ASC) ; CREATE INDEX IX_SourceCode_ClientID_IsVoid ON Document (SourceCode ASC, FKClientUID ASC, IsVoid ASC) ; CREATE INDEX IX_SourceCode_IsVoid ON Document (SourceCode ASC, IsVoid ASC) ; CREATE UNIQUE INDEX IX_DocumentSetDocument ON DocumentSetDocument (FKDocumentSetUID ASC, FKDocumentUID ASC) ; ALTER TABLE sysdiagrams ADD CONSTRAINT UK_principal_name UNIQUE (principal_id, name) ; ALTER TABLE Client ADD CONSTRAINT PK_Company PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientContract ADD CONSTRAINT PK_ClientContract PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientDocument ADD CONSTRAINT PK_ClientDocument PRIMARY KEY NONCLUSTERED (UID) ; ALTER TABLE ClientDocumentIssue ADD CONSTRAINT PK_ClientDocumentIssue PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientDocumentLink ADD CONSTRAINT PK__ClientDo__C5B196022610A626 PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientDocumentSet ADD CONSTRAINT PK_ClientDocumentSet PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientDocumentVersion ADD CONSTRAINT PK_ClientDocumentIssue PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientExtraInformation ADD CONSTRAINT PK_ClientExtraInformation PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ClientOtherInfo ADD CONSTRAINT PK_ClientOtherInfo PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE CodeRelated ADD CONSTRAINT PK_CodeRelated PRIMARY KEY CLUSTERED (FKCodeTypeFrom, FKCodeValueFrom, FKCodeTypeTo, FKCodeValueTo) ; ALTER TABLE CodeType ADD CONSTRAINT PK_CodeType PRIMARY KEY CLUSTERED (CodeType) ; ALTER TABLE CodeValue ADD CONSTRAINT PK_DirectoryType PRIMARY KEY CLUSTERED (FKCodeType, ID) ; ALTER TABLE Document ADD CONSTRAINT PK_Document PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE DocumentLink ADD CONSTRAINT PK__Document__C5B1960222401542 PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE DocumentSet ADD CONSTRAINT PK_DocumentTemplateType PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE DocumentSetDocument ADD CONSTRAINT PK_TemplateDocumentInstance PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE DocumentSetDocumentLink ADD CONSTRAINT PK__Document__C5B196022DB1C7EE PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE DocumentSetLink ADD CONSTRAINT PK_TemplateDocumentInstance PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE Employee ADD CONSTRAINT PK_Employee PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE FCMRole ADD CONSTRAINT PK_FCMRole PRIMARY KEY CLUSTERED (Role) ; ALTER TABLE FCMUser ADD CONSTRAINT PK_FCMUser PRIMARY KEY CLUSTERED (UserID) ; ALTER TABLE FCMUserRole ADD CONSTRAINT PK_FCMUserRole PRIMARY KEY CLUSTERED (UniqueID) ; ALTER TABLE ProcessRequest ADD CONSTRAINT PK_Request PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE ProcessRequestArguments ADD CONSTRAINT PK_ProcessRequestArguments PRIMARY KEY CLUSTERED (FKRequestUID, Code) ; ALTER TABLE ProcessRequestResults ADD CONSTRAINT PK_ProcessRequestResults PRIMARY KEY CLUSTERED (FKRequestUID, SequenceNumber) ; ALTER TABLE RegisterofSystemDocuments ADD CONSTRAINT PK_RegisterofSystemDocuments PRIMARY KEY CLUSTERED (DocumentNumber) ; ALTER TABLE ReportMetadata ADD CONSTRAINT PK_WordFieldReference PRIMARY KEY CLUSTERED (UID) ; ALTER TABLE sysdiagrams ADD CONSTRAINT PK__sysdiagrams__023D5A04 PRIMARY KEY CLUSTERED (diagram_id) ; ALTER TABLE UserSettings ADD CONSTRAINT PK_UserSettings PRIMARY KEY CLUSTERED (FKUserID, FKScreenCode, FKControlCode, FKPropertyCode) ; ALTER TABLE Client ADD CONSTRAINT FK_Client_FCMUser FOREIGN KEY (FKUserID) REFERENCES FCMUser (UserID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientContract ADD CONSTRAINT FK_ClientContract_Client FOREIGN KEY (FKCompanyUID) REFERENCES Client (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocument ADD CONSTRAINT FK_ClientDocument_Client FOREIGN KEY (FKClientUID) REFERENCES Client (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocument ADD CONSTRAINT FK_ClientDocument_ClientDocumentSetLink FOREIGN KEY (FKClientDocumentSetUID) REFERENCES ClientDocumentSet (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocument ADD CONSTRAINT FK_Document_1_ClientDocument_n FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocumentIssue ADD CONSTRAINT FK_ClientDocumentIssue_ClientDocument FOREIGN KEY (FKClientDocumentUID) REFERENCES ClientDocument (UID) ; ALTER TABLE ClientDocumentLink ADD CONSTRAINT FK_ClientDocumentLink_ClientDocument_Parent FOREIGN KEY (FKParentDocumentUID) REFERENCES ClientDocument (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocumentLink ADD CONSTRAINT FK_ClientDocumentLink_ClientDocument_child FOREIGN KEY (FKChildDocumentUID) REFERENCES ClientDocument (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocumentSet ADD CONSTRAINT FK_ClientDocumentSetLink_Client FOREIGN KEY (FKClientUID) REFERENCES Client (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientDocumentVersion ADD CONSTRAINT FK_ClientDocumentIssue_ClientDocument FOREIGN KEY (FKClientDocumentUID) REFERENCES ClientDocument (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientExtraInformation ADD CONSTRAINT FK_ClientExtraInformation_Client FOREIGN KEY (FKClientUID) REFERENCES Client (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ClientOtherInfo ADD CONSTRAINT FK_ClientOtherInfo_Client FOREIGN KEY (FKClientUID) REFERENCES Client (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE CodeRelated ADD CONSTRAINT FK_Source FOREIGN KEY (FKCodeTypeFrom) REFERENCES CodeValue (FKCodeType, ID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE CodeRelated ADD CONSTRAINT FK_Destination FOREIGN KEY (FKCodeTypeTo, FKCodeValueTo, FKCodeValueFrom) REFERENCES CodeValue (FKCodeType, ID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE CodeValue ADD CONSTRAINT FK_CodeValue_CodeType FOREIGN KEY (FKCodeType) REFERENCES CodeType (CodeType) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentLink ADD CONSTRAINT FK_DocumentLink_Document_from FOREIGN KEY (FKParentDocumentUID) REFERENCES Document (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentLink ADD CONSTRAINT FK_DocumentLink_Document_to FOREIGN KEY (FKChildDocumentUID) REFERENCES Document (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentSetDocument ADD CONSTRAINT FK_Document_1_DocumentSetDocument_n FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentSetDocument ADD CONSTRAINT FK_TemplateDocumentInstance_DocumentTemplateType FOREIGN KEY (FKDocumentSetUID) REFERENCES DocumentSet (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentSetDocumentLink ADD CONSTRAINT FK_Parent_DSDL_DSD FOREIGN KEY (FKParentDocumentUID) REFERENCES DocumentSetDocument (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentSetDocumentLink ADD CONSTRAINT FK_Child_DSDL_DSD FOREIGN KEY (FKChildDocumentUID) REFERENCES DocumentSetDocument (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE DocumentSetLink ADD CONSTRAINT FK_DocumentSetLink_Document FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ; ALTER TABLE DocumentSetLink ADD CONSTRAINT FK_TemplateDocumentInstance_DocumentTemplateType FOREIGN KEY (FKDocumentSetUID) REFERENCES DocumentSet (UID) ; ALTER TABLE DocumentVersion ADD CONSTRAINT FK_DocumentIssue_Document FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE Employee ADD CONSTRAINT FK_Employee_Client FOREIGN KEY (FKCompanyUID) REFERENCES Client (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE FCMUserRole ADD CONSTRAINT FK_FCMUserRole_FCMRole FOREIGN KEY (FK_Role) REFERENCES FCMRole (Role) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE FCMUserRole ADD CONSTRAINT FK_FCMUserRole_FCMUser FOREIGN KEY (FK_UserID) REFERENCES FCMUser (UserID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ProcessRequestArguments ADD CONSTRAINT FK_ProcessRequestArguments_ProcessRequest FOREIGN KEY (FKRequestUID) REFERENCES ProcessRequest (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; ALTER TABLE ProcessRequestResults ADD CONSTRAINT FK_ProcessRequestResults_ProcessRequest FOREIGN KEY (FKRequestUID) REFERENCES ProcessRequest (UID) ON DELETE RESTRICT ON UPDATE RESTRICT ; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.Utils; using System.ServiceModel; using System.ServiceModel.Channels; [ServiceContract] public interface IAsyncBUSClient { [OperationContract(AsyncPattern = true)] IAsyncResult BeginClientList(HeaderInfo headerInfo, AsyncCallback callback, object asyncState); ClientListResponse EndClientList(IAsyncResult result); } public class ClientAsync : ClientBase<IAsyncBUSClient>, IAsyncBUSClient { public IAsyncResult BeginClientList(HeaderInfo headerInfo, AsyncCallback callback, object asyncState) { return Channel.BeginClientList(headerInfo, callback, asyncState); } public ClientListResponse EndClientList(IAsyncResult result) { return Channel.EndClientList(result); } } <file_sep>using System; using System.Data; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelMetadata; namespace fcm.Windows { public partial class UIClientMetadata : Form { public DataTable elementSourceDataTable; public DataTable dtAvailableMetadata; private Client client; private Form _comingFromForm; public UIClientMetadata(Form comingFromForm) { InitializeComponent(); _comingFromForm = comingFromForm; // // Create datatable // var UID = new DataColumn("UID", typeof(String)); var RecordType = new DataColumn("RecordType", typeof(String)); var FieldCode = new DataColumn("FieldCode", typeof(String)); var Description = new DataColumn("Description", typeof(String)); var ClientType = new DataColumn("ClientType", typeof(String)); var ClientUID = new DataColumn("ClientUID", typeof(String)); var InformationType = new DataColumn("InformationType", typeof(String)); var Condition = new DataColumn("Condition", typeof(String)); var CompareWith = new DataColumn("CompareWith", typeof(String)); // Client Metadata // elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(UID); elementSourceDataTable.Columns.Add(RecordType); elementSourceDataTable.Columns.Add(FieldCode); elementSourceDataTable.Columns.Add(Description); elementSourceDataTable.Columns.Add(ClientType); elementSourceDataTable.Columns.Add(ClientUID); elementSourceDataTable.Columns.Add(InformationType); elementSourceDataTable.Columns.Add(Condition); elementSourceDataTable.Columns.Add(CompareWith); dgvClientMetadata.DataSource = elementSourceDataTable; // // Create Available Metadata datatable // var AMUID = new DataColumn("UID", typeof(String)); var AMRecordType = new DataColumn("RecordType", typeof(String)); var AMFieldCode = new DataColumn("FieldCode", typeof(String)); var AMDescription = new DataColumn("Description", typeof(String)); var AMClientType = new DataColumn("ClientType", typeof(String)); var AMClientUID = new DataColumn("ClientUID", typeof(String)); var AMInformationType = new DataColumn("InformationType", typeof(String)); var AMCondition = new DataColumn("Condition", typeof(String)); var AMCompareWith = new DataColumn("CompareWith", typeof(String)); // Available Metadata // dtAvailableMetadata = new DataTable("dtAvailableMetadata"); dtAvailableMetadata.Columns.Add(AMUID); dtAvailableMetadata.Columns.Add(AMRecordType); dtAvailableMetadata.Columns.Add(AMFieldCode); dtAvailableMetadata.Columns.Add(AMDescription); dtAvailableMetadata.Columns.Add(AMClientType); dtAvailableMetadata.Columns.Add(AMClientUID); dtAvailableMetadata.Columns.Add(AMInformationType); dtAvailableMetadata.Columns.Add(AMCondition); dtAvailableMetadata.Columns.Add(AMCompareWith); dgvAvailableMetadata.DataSource = dtAvailableMetadata; } private void UIClientMetadata_Load(object sender, EventArgs e) { // Get client list from background and load into the list // foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // Get selected client from the background // cbxClient.SelectedIndex = Utils.ClientIndex; cbxDocumentSet.Text = Utils.ClientSetText; cbxDocumentSet.Enabled = false; cbxClient.Enabled = false; // // Retrieve document set for a client // ClientDocumentSet clientDocSet = new ClientDocumentSet(); clientDocSet.Get(Utils.ClientID, Utils.ClientSetID); cbxDocumentSet.SelectedItem = 0; txtSourceFolder.Text = clientDocSet.SourceFolder; txtDestinationFolder.Text = clientDocSet.Folder; loadList(); } private void dgvAvailableMetadata_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { // This is the double-click on the available list // // Get selected row if (dgvAvailableMetadata.SelectedRows.Count <= 0) return; var selectedRow = dgvAvailableMetadata.SelectedRows; ReportMetadata rm = new ReportMetadata(); ConvertSelectedRow(rm, selectedRow[0]); // Insert into db with client id rm.ClientUID = Utils.ClientID; rm.UID = 0; rm.RecordType = "CL"; rm.Save(); // Reload lists // loadList(); } private void loadList() { elementSourceDataTable.Rows.Clear(); dtAvailableMetadata.Rows.Clear(); // Load client metadata ReportMetadataList rmd = new ReportMetadataList(); rmd.ListMetadataForClient(Utils.ClientID); foreach (ReportMetadata metadata in rmd.reportMetadataList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["UID"] = metadata.UID; elementRow["RecordType"] = metadata.RecordType; elementRow["FieldCode"] = metadata.FieldCode; elementRow["Description"] = metadata.Description; elementRow["ClientType"] = metadata.ClientType; elementRow["ClientUID"] = metadata.ClientUID; elementRow["InformationType"] = metadata.InformationType; elementRow["Condition"] = metadata.Condition; elementRow["CompareWith"] = metadata.CompareWith; elementSourceDataTable.Rows.Add(elementRow); } // Load available metadata ReportMetadataList rmdavailable = new ReportMetadataList(); rmdavailable.ListAvailableForClient(Utils.ClientID); foreach (ReportMetadata metadata in rmdavailable.reportMetadataList) { DataRow elementRow = dtAvailableMetadata.NewRow(); elementRow["UID"] = metadata.UID; elementRow["RecordType"] = metadata.RecordType; elementRow["FieldCode"] = metadata.FieldCode; elementRow["Description"] = metadata.Description; elementRow["ClientType"] = metadata.ClientType; elementRow["ClientUID"] = metadata.ClientUID; elementRow["InformationType"] = metadata.InformationType; elementRow["Condition"] = metadata.Condition; elementRow["CompareWith"] = metadata.CompareWith; dtAvailableMetadata.Rows.Add(elementRow); } } private void GetSelectedRow(ReportMetadata rm, int rowSubscript) { if (dgvAvailableMetadata.SelectedRows.Count <= 0) return; if (dgvAvailableMetadata.SelectedRows.Count < rowSubscript) return; var selectedRow = dgvAvailableMetadata.SelectedRows; ConvertSelectedRow(rm, selectedRow[rowSubscript]); return; } private void ConvertSelectedRow(ReportMetadata rm, DataGridViewRow selectedRow) { rm.UID = Convert.ToInt32(selectedRow.Cells["UID"].Value.ToString()); rm.RecordType = selectedRow.Cells["RecordType"].Value.ToString(); rm.FieldCode = selectedRow.Cells["FieldCode"].Value.ToString(); rm.Description = selectedRow.Cells["Description"].Value.ToString(); rm.ClientType = selectedRow.Cells["ClientType"].Value.ToString(); rm.ClientUID = Convert.ToInt32(selectedRow.Cells["ClientUID"].Value.ToString()); rm.InformationType = selectedRow.Cells["InformationType"].Value.ToString(); rm.Condition = selectedRow.Cells["Condition"].Value.ToString(); rm.CompareWith = selectedRow.Cells["CompareWith"].Value.ToString(); return; } // // Double click on client metadata list // The idea is to remove the metadata // private void dgvClientMetadata_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { // This is the double-click on the available list // // Get selected row if (dgvClientMetadata.SelectedRows.Count <= 0) return; var selectedRow = dgvClientMetadata.SelectedRows; ReportMetadata rm = new ReportMetadata(); ConvertSelectedRow(rm, selectedRow[0]); // Insert into db with client id rm.Delete(); // Reload lists // loadList(); } private void UIClientMetadata_FormClosed(object sender, FormClosedEventArgs e) { _comingFromForm.Activate(); _comingFromForm.Refresh(); UIClientDocumentSet uicds = new UIClientDocumentSet(); uicds = (UIClientDocumentSet)_comingFromForm; uicds.RefreshMetadata(); } // Back to previous form // private void btnBack_Click(object sender, EventArgs e) { _comingFromForm.Activate(); _comingFromForm.Refresh(); this.Dispose(); } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void editToolStripMenuItem_Click(object sender, EventArgs e) { UIReportMetadata uirmdt = new UIReportMetadata(this, Utils.ClientID); uirmdt.ShowDialog(); this.loadList(); } private void btnSave_Click(object sender, EventArgs e) { } private void dgvClientMetadata_CellMouseDown( object sender, DataGridViewCellMouseEventArgs e ) { if (e.ColumnIndex >= 0 && e.RowIndex >= 0) { dgvClientMetadata.CurrentCell = dgvClientMetadata.Rows[e.RowIndex].Cells[e.ColumnIndex]; } } private void dgvAvailableMetadata_CellMouseDown( object sender, DataGridViewCellMouseEventArgs e ) { if (e.ColumnIndex >= 0 && e.RowIndex >= 0) { dgvAvailableMetadata.CurrentCell = dgvAvailableMetadata.Rows[e.RowIndex].Cells[e.ColumnIndex]; } } } } <file_sep>namespace MackkadoITFramework.Utils { /// <summary> /// Class with every constant used in the system /// </summary> public class MakConstant { /// <summary> /// It represents the attribute for the database ConnectionString /// </summary> public class ConfigXml { public static string ConnectionString = "ConnectionString"; public static string ConnectionStringMySql = "ConnectionStringMySql"; public static string ConnectionStringServer = "ConnectionStringServer"; public static string ConnectionStringLocal = "ConnectionStringLocal"; public static string ConnectionStringODBC = "ConnectionStringODBC"; public static string ConnectionStringFramework = "ConnectionStringFramework"; public static string LocalAssemblyFolder = "LocalAssemblyFolder"; public static string ServerAssemblyFolder = "ServerAssemblyFolder"; public static string EnableLocalDB = "EnableLocalDB"; public static string EnableServerDB = "EnableServerDB"; public static string DefaultDB = "DefaultDB"; public static string AuditLogPath = "AuditLogPath"; public static string StopGeneration = "StopGeneration"; public static string GUFCWebAPIURI = "GUFCWebAPIURI"; public static string GUFCConnectionString = "GUFCConnectionString "; } /// <summary> /// It represents the attribute for the database ConnectionString /// </summary> public enum DataBaseType { SQLSERVER, MYSQL } /// <summary> /// Integer represent the sequence of the image on the Image List. /// </summary> public struct Image { public const int Selected = 0; public const int Document = 1; public const int Folder = 2; public const int Client = 3; public const int Appendix = 4; public const int Excel = 5; public const int PDF = 6; public const int Undefined = 7; public const int Checked = 8; public const int Unchecked = 9; public const int Word32 = 10; public const int WordFileExists32 = 11; public const int WordFileNotFound32 = 12; public const int WordFileSourceNoDestinationNo = 13; public const int WordFileSourceNoDestinationYes = 14; public const int WordFileSourceYesDestinationNo = 15; public const int WordFileSourceYesDestinationYes = 16; public const int ExcelFileSourceNoDestinationNo = 17; public const int ExcelFileSourceNoDestinationYes = 18; public const int ExcelFileSourceYesDestinationNo = 19; public const int ExcelFileSourceYesDestinationYes = 20; public const int PDFFileSourceNoDestinationNo = 21; public const int PDFFileSourceNoDestinationYes = 22; public const int PDFFileSourceYesDestinationNo = 23; public const int PDFFileSourceYesDestinationYes = 24; } /// <summary> /// This is the name of the image file representing the file type /// </summary> public struct ImageFileName { public const string Selected = "ImageSelected.jpg"; public const string Document = "ImageWordDocument.jpg"; public const string Folder = "ImageFolder.jpg"; public const string Client = "ImageClient.jpg"; public const string Appendix = "Appendix.jpg"; public const string Excel = "Excel.jpg"; public const string PDF = "PDF.jpg"; public const string Undefined = "ImageWordDocument.jpg"; public const string Checked = "Checked.jpg"; public const string Unchecked = "Unchecked.jpg"; public const string WordFile32 = "WordFile32.jpg"; public const string WordFileExists32 = "WordFileExists32.jpg"; public const string WordFileNotFound32 = "WordFileNotFound32.jpg"; public const string WordFileSourceNoDestinationNo = "WordFileSourceNoDestinationNo"; public const string WordFileSourceNoDestinationYes = "WordFileSourceNoDestinationYes"; public const string WordFileSourceYesDestinationNo = "WordFileSourceYesDestinationNo"; public const string WordFileSourceYesDestinationYes = ""; public const string ExcelFileSourceNoDestinationNo = "ExcelFileSourceNoDestinationNo"; public const string ExcelFileSourceNoDestinationYes = "ExcelFileSourceNoDestinationYes"; public const string ExcelFileSourceYesDestinationNo = "ExcelFileSourceYesDestinationNo"; public const string ExcelFileSourceYesDestinationYes = "ExcelFileSourceYesDestinationYes"; public const string PDFFileSourceNoDestinationNo = "PDFFileSourceNoDestinationNo"; public const string PDFFileSourceNoDestinationYes = "PDFFileSourceNoDestinationYes"; public const string PDFFileSourceYesDestinationNo = "PDFFileSourceYesDestinationNo"; public const string PDFFileSourceYesDestinationYes = "PDFFileSourceYesDestinationYes"; } /// <summary> /// List of code types /// </summary> public struct CodeTypeString { public const string RoleType = "ROLETYPE"; public const string ErrorCode = "ERRORCODE"; public const string SYSTSET = "SYSTSET"; public const string SCREENCODE = "SCREENCODE"; public const string ERRORCODE = "ERRORCODE"; } /// <summary> /// Represents action to database /// </summary> public struct SQLAction { public const string CREATE = "CREATE"; public const string UPDATE = "UPDATE"; } /// <summary> /// List of folder variables /// </summary> public struct SYSFOLDER { public const string TEMPLATEFOLDER = "%TEMPLATEFOLDER%"; public const string CLIENTFOLDER = "%CLIENTFOLDER%"; public const string VERSIONFOLDER = "%VERSIONFOLDER%"; public const string PDFEXEPATH = "PDFEXEPATH"; public const string LOGOFOLDER = "%LOGOFOLDER%"; public const string WEBLOGOFOLDER = "%WEBLOGOFOLDER%"; public const string WEBTEMPLATEFOLDER = "%WEBTEMPLATEFOLDER%"; public const string WEBCLIENTFOLDER = "%WEBCLIENTFOLDER%"; public const string WEBVERSIONFOLDER = "%WEBVERSIONFOLDER%"; public const string LOGFILEFOLDER = "%LOGFILEFOLDER%"; } /// <summary> /// Document list mode /// </summary> public struct DocumentListMode { public const string SELECT = "SELECT"; public const string MAINTAIN = "MAINTAIN"; } /// <summary> /// Screen Codes /// </summary> public struct ScreenCode { public const string Document = "DOCUMENT"; public const string ClientRegistration = "CLNTREG"; public const string ClientList = "CLNTLIST"; public const string ClientDocument = "CLNTDOC"; public const string ClientDocumentSet = "CLNTDOCSET"; public const string ClientDocumentSetLink = "CLNTDOCSETLINK"; public const string DocumentList = "DOCLIST"; public const string DocumentLink = "DOCLINK"; public const string DocumentSetLink = "DOCSETLINK"; public const string DocumentSetList = "DOCSETLIST"; public const string UserAccess = "USERACCESS"; public const string ImpactedDocuments = "IMPACTEDDOCUMENTS"; public const string ProcessRequest = "PROCESSREQUEST"; public const string ReferenceData = "REFERENCEDATA"; public const string ReportMetadata = "REPORTMETADATA"; public const string Users = "USERS"; public const string UserSettings = "USERSETTINGS"; } /// <summary> /// Screen Codes /// </summary> public struct ScreenControl { public const string TreeViewClientDocumentList = "TVCLNTDOCLIST"; public const string TreeViewClientDocumentListDocSet = "TVCLNTDOCLISTDOCSET"; public const string TreeViewDocumentList = "TVCLNTDOCLIST"; } /// <summary> /// Font Size /// </summary> public struct ScreenProperty { public const string FontSize = "FONTSIZE"; public const string IconSize = "ICONSIZE"; } /// <summary> /// List of error codes /// </summary> //public struct ErrorCode //{ // // ---------------------- // // // ERROR MESSAGES // // // ---------------------- // // /// <summary> // /// Invalid logon. // /// </summary> // public const string FCMERR00000001 = "FCMERR00.00.0001"; // /// <summary> // /// Error deleting User Role. // /// </summary> // public const string FCMERR00000002 = "FCMERR00.00.0002"; // /// <summary> // /// User ID is mandatory. // /// </summary> // public const string FCMERR00000003 = "FCMINF00.00.0003"; // /// <summary> // /// Password is mandatory. // /// </summary> // public const string FCMERR00000004 = "FCMINF00.00.0004"; // /// <summary> // /// Salt is mandatory. // /// </summary> // public const string FCMERR00000005 = "FCMINF00.00.0005"; // /// <summary> // /// Error creating new version. Source file not found. // /// </summary> // public const string FCMERR00000006 = "FCMINF00.00.0006"; // /// <summary> // /// Client name is mandatory. // /// </summary> // public const string FCMERR00000007 = "FCMINF00.00.0007"; // /// <summary> // /// Role Name is mandatory. // /// </summary> // public const string FCMERR00000008 = "FCMINF00.00.0008"; // /// <summary> // /// Error. // /// </summary> // public const string FCMERR00009999 = "FCMINF00.00.9999"; // // ---------------------- // // // INFORMATIONAL MESSAGES // // // ---------------------- // // /// <summary> // /// Generic Successful. // /// </summary> // public const string FCMINF00000001 = "FCMINF00.00.0001"; // /// <summary> // /// User role added successfully. // /// </summary> // public const string FCMINF00000002 = "FCMINF00.00.0002"; // /// <summary> // /// User role deleted successfully. // /// </summary> // public const string FCMINF00000003 = "FCMINF00.00.0003"; // /// <summary> // /// User added successfully. // /// </summary> // public const string FCMINF00000004 = "FCMINF00.00.0004"; // /// <summary> // /// User updated successfully. // /// </summary> // public const string FCMINF00000005 = "FCMINF00.00.0005"; // /// <summary> // /// User added successfully. // /// </summary> // public const string FCMINF00000006 = "FCMINF00.00.0006"; // /// <summary> // /// Client deleted successfully. // /// </summary> // public const string FCMINF00000007 = "FCMINF00.00.0007"; // // ---------------------- // // // WARNING MESSAGES // // // ---------------------- // // /// <summary> // /// Generic Warning. // /// </summary> // public const string FCMWAR00000001 = "FCMWAR00.00.0001"; // /// <summary> // /// No valid contract was found for client. // /// </summary> // public const string FCMWAR00000002 = "FCMWAR00.00.0002"; //} } } <file_sep>using System; using System.IO; using System.Collections.Generic; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCFCMBackendStatus.Service; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Interfaces; using MackkadoITFramework.APIDocument; using MackkadoITFramework.Utils; using System.Threading; using System.Threading.Tasks; namespace FCMMySQLBusinessLibrary.Model.ModelClientDocument { public class DocumentGeneration { private object vkFalse; private Word.Application vkWordApp; // private Microsoft.Office.Interop.Excel.Application vkExcelApp; private ReportMetadataList clientMetadata; private List<WordDocumentTasks.TagStructure> listOfWordsToReplace; private int clientID; private int clientDocSetID; private double fileprocessedcount; private double valueForProgressBar; private string startTime; private int filecount; private IOutputMessage uioutput; private string overrideDocuments; private ClientDocumentSet cds; private DateTime estimated; private double averageSpanInSec; private double acumulatedSpanInSec; private string processName; private string userID; /// <summary> /// Constructor /// </summary> /// <param name="ClientID"></param> /// <param name="ClientDocSetID"></param> /// <param name="UIoutput"> </param> public DocumentGeneration( int ClientID, int ClientDocSetID, IOutputMessage UIoutput, string OverrideDocuments, string inprocessName, string inuserID) { processName = inprocessName; userID = inuserID; if ( OverrideDocuments == null ) OverrideDocuments = "N"; // Assign to internal variables // // iconMessage = IconMessage; // Set private attributes clientID = ClientID; clientDocSetID = ClientDocSetID; uioutput = UIoutput; overrideDocuments = OverrideDocuments; // Instantiate Word // vkFalse = false; vkWordApp = new Word.Application(); // Make it not visible vkWordApp.Visible = false; //vkExcelApp = new Microsoft.Office.Interop.Excel.Application(); // Make it not visible // vkExcelApp.Visible = false; // Get Metadata for client clientMetadata = new ReportMetadataList(); // Daniel 31/12/2011 // // clientMetadata.ListMetadataForClient(clientID); // The intention is to always use the full set of variables. // There is need to use all in order to replace the tags not used. // clientMetadata.ListDefault(); listOfWordsToReplace = new List<WordDocumentTasks.TagStructure>(); // Load variables/ metadata into memory // #region ClientMetadata foreach ( ReportMetadata metadata in clientMetadata.reportMetadataList ) { // Add client ID metadata.ClientUID = this.clientID; // Retrieve value for the field selected // string value = metadata.GetValue(); // If the field is not enabled, the program has to replace the value with spaces. // 01-Jan-2012 - No longer necessary. // All the variables have to be used // var valueOfTag = metadata.Enabled == 'Y' ? value : string.Empty; // Set to the value. If value is null, set to spaces. var valueOfTag = string.IsNullOrEmpty( value ) ? string.Empty : value; // When the field is an image and it is not enable, do not include the "No image" icon in the list // //if (metadata.InformationType == Utils.InformationType.IMAGE && metadata.Enabled == 'N') // continue; // If the field is an image but it has no value, no need to include. // Regular fields must be included because they need to be replaced. // Images uses bookmarks, no need to be replace. It is not displayed in the document. // if ( metadata.InformationType == MackkadoITFramework.Helper.Utils.InformationType.IMAGE ) { if ( string.IsNullOrEmpty( value ) ) continue; } // Add label before value to print. // if ( metadata.UseAsLabel == 'Y' ) valueOfTag = metadata.Description + " " + valueOfTag; listOfWordsToReplace.Add( new WordDocumentTasks.TagStructure() { TagType = metadata.InformationType, Tag = metadata.FieldCode, TagValue = valueOfTag } ); } #endregion ClientMetadata // Get Client Document Set Details // To get the source and destination folders cds = new ClientDocumentSet(); cds.Get( clientID, clientDocSetID ); fileprocessedcount = 0; valueForProgressBar = 0; startTime = System.DateTime.Now.ToString(); } /// <summary> /// Destructor /// </summary> ~DocumentGeneration() { // close word application if ( vkWordApp != null ) { try { vkWordApp.Quit( ref vkFalse, ref vkFalse, ref vkFalse ); } catch { } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject( vkWordApp ); } } //if ( vkExcelApp != null ) //{ // try // { // vkExcelApp.Quit(); // } // catch // { } // finally // { // System.Runtime.InteropServices.Marshal.ReleaseComObject( vkExcelApp ); // } //} } /// <summary> /// Generate documents selected for a client /// </summary> /// <param name="clientID"></param> /// <param name="clientDocSetID"></param> /// <param name="uioutput"></param> /// <param name="overrideDocuments"></param> private void TBD_GenerateDocumentsForClient( int clientID, int clientDocSetID, string overrideDocuments ) { uioutput.AddOutputMessage( "Start time: " + System.DateTime.Now.ToString(), processName, userID ); // Instantiate Word // object vkFalse = false; object vkTrue = true; Word.Application vkWordApp = new Word.Application(); // Make it not visible vkWordApp.Visible = false; Microsoft.Office.Interop.Excel.Application vkExcelApp = new Microsoft.Office.Interop.Excel.Application(); // Make it not visible vkExcelApp.Visible = false; // Get Metadata for client ReportMetadataList clientMetadata = new ReportMetadataList(); clientMetadata.ListMetadataForClient( clientID ); var ts = new List<WordDocumentTasks.TagStructure>(); // Load variables/ metadata into memory // foreach ( ReportMetadata metadata in clientMetadata.reportMetadataList ) { // Retrieve value for the field selected // string value = metadata.GetValue(); // If the field is not enabled, the program has to replace the value with spaces. // var valueOfTag = metadata.Enabled == 'Y' ? value : string.Empty; // When the field is an image and it is not enable, do not include the "No image" icon in the list // if ( metadata.InformationType == MackkadoITFramework.Helper.Utils.InformationType.IMAGE && metadata.Enabled == 'N' ) continue; ts.Add( new WordDocumentTasks.TagStructure() { TagType = metadata.InformationType, Tag = metadata.FieldCode, TagValue = valueOfTag } ); } // Get Client Document Set Details // To get the source and destination folders ClientDocumentSet cds = new ClientDocumentSet(); cds.Get( clientID, clientDocSetID ); // Get List of documents for a client // var cdl = new ClientDocument(); //cdl.List( Utils.ClientID, Utils.ClientSetID ); RepClientDocument.List( cdl, Utils.ClientID, Utils.ClientSetID ); bool fileNotFound = false; // --------------------------------------------------------------------------- // Check if source files exist before generation starts // --------------------------------------------------------------------------- int filecount = 0; foreach ( scClientDocSetDocLink doco in cdl.clientDocSetDocLink ) { #region File Inspection filecount++; // Ignore for now // if ( doco.clientDocument.RecordType.Trim() == FCMConstant.RecordType.FOLDER ) { string er = "Folder " + doco.document.Name; uioutput.AddOutputMessage( er, processName, userID ); continue; } // Retrieve updated file name from source Model.ModelDocument.Document document = new Model.ModelDocument.Document(); document.UID = doco.clientDocument.FKDocumentUID; // document.Read(); document = RepDocument.Read( false, doco.clientDocument.FKDocumentUID ); uioutput.AddOutputMessage( "Inspecting file: " + document.UID + " === " + document.Name, processName, userID ); // Client Document.SourceFileName is the name for the FCM File // Client Document.FileName is the client file name // Update client records with new file name // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // cd.FileName = document.FileName; cd.SourceFileName = document.FileName; RepClientDocument.UpdateSourceFileName( cd ); // Update memory with latest file name // doco.clientDocument.SourceFileName = cd.FileName; doco.clientDocument.SourceFileName = cd.SourceFileName; string sourceFileLocationName = Utils.getFilePathName( doco.clientDocument.SourceLocation, doco.clientDocument.SourceFileName ); // check if source folder/ file exists if ( string.IsNullOrEmpty( doco.clientDocument.Location ) ) { MessageBox.Show( "Document Location is empty." ); return; } if ( string.IsNullOrEmpty( doco.clientDocument.FileName ) ) { MessageBox.Show( "File Name is empty." ); return; } if ( !File.Exists( sourceFileLocationName ) ) { string er = "File does not exist " + sourceFileLocationName + " - File Name: " + doco.clientDocument.SourceFileName; uioutput.AddOutputMessage( er, processName: processName, userID: userID ); uioutput.AddErrorMessage( er, processName:processName, userID:userID ); fileNotFound = true; continue; } #endregion File Inspection } // Can't proceed if file not found if ( fileNotFound ) return; // Check if destination folder exists // if ( string.IsNullOrEmpty( cds.Folder ) ) { MessageBox.Show( "Destination folder not set. Generation stopped." ); return; } string PhysicalCDSFolder = Utils.GetPathName( cds.Folder ); if ( !Directory.Exists( PhysicalCDSFolder ) ) Directory.CreateDirectory( PhysicalCDSFolder ); // ----------------------------------------------------------------------- // Generation starts here // ----------------------------------------------------------------------- fileprocessedcount = 0; valueForProgressBar = 0; startTime = System.DateTime.Now.ToString(); estimated = System.DateTime.Now.AddSeconds( 5 * filecount ); var previousTime = System.DateTime.Now; var agora = System.DateTime.Now; foreach ( scClientDocSetDocLink doco in cdl.clientDocSetDocLink ) { fileprocessedcount++; valueForProgressBar = ( fileprocessedcount / filecount ) * 100; // Get current time agora = System.DateTime.Now; // Get the time it took to process one file TimeSpan span = agora.Subtract( previousTime ); // Calculate the estimated time to complete estimated = System.DateTime.Now.AddSeconds( span.TotalSeconds * filecount ); uioutput.UpdateProgressBar( valueForProgressBar, estimated ); previousTime = System.DateTime.Now; // Retrieve latest version // Model.ModelDocument.Document document = new Model.ModelDocument.Document(); document.UID = doco.clientDocument.FKDocumentUID; // document.Read(); document = RepDocument.Read( false, doco.clientDocument.FKDocumentUID ); uioutput.AddOutputMessage( ">>> Generating file: " + document.UID + " === " + document.SimpleFileName, processName, userID ); string sourceFileLocationName = Utils.getFilePathName( doco.clientDocument.SourceLocation, doco.clientDocument.SourceFileName ); // This is the client file name // string clientFileLocation = cds.Folder.Trim() + doco.clientDocument.Location.Trim(); string clientFileLocationName = Utils.getFilePathName( clientFileLocation, doco.clientDocument.FileName.Trim() ); // Check if file destination directory exists // string PhysicalLocation = Utils.GetPathName( clientFileLocation ); if ( string.IsNullOrEmpty( PhysicalLocation ) ) { string er = "Location is empty " + doco.clientDocument.Location + "\n" + "File Name: " + doco.document.Name; uioutput.AddOutputMessage( er, processName, userID ); continue; } if ( !Directory.Exists( PhysicalLocation ) ) Directory.CreateDirectory( PhysicalLocation ); if ( File.Exists( clientFileLocationName ) ) { // Proceed but report in list // if ( overrideDocuments == "Yes" ) { // Delete file try { File.Delete( clientFileLocationName ); uioutput.AddOutputMessage( "File replaced " + document.SimpleFileName, processName, userID ); } catch ( Exception ) { uioutput.AddOutputMessage( "Error deleting file " + document.SimpleFileName, processName, userID ); uioutput.AddErrorMessage( "Error deleting file " + document.SimpleFileName, processName, userID ); continue; } } else { uioutput.AddOutputMessage( "File already exists " + document.SimpleFileName, processName, userID ); continue; } } // Copy and fix file // // Word Documents // if ( doco.clientDocument.RecordType.Trim() == FCMConstant.RecordType.FOLDER ) { // Update file - set as GENERATED. // uioutput.AddOutputMessage( "FOLDER: " + doco.clientDocument.SourceFileName, processName, userID ); } else { // If is is not a folder, it must be a regular file. // Trying to copy it as well... // var currentDocumentPath = Path.GetExtension( doco.clientDocument.FileName ); if ( doco.clientDocument.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.WORD ) { #region Word // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ var results = WordDocumentTasks.CopyDocument( sourceFileLocationName, clientFileLocationName, ts, vkWordApp, uioutput, processName, userID ); if ( results.ReturnCode < 0 ) { // Error has occurred // var er = (System.Exception) results.Contents; uioutput.AddOutputMessage( "ERROR: " + er.ToString(), processName, userID ); uioutput.AddErrorMessage( "ERROR: " + er.ToString(), processName, userID ); continue; } // // Instantiate client document var cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // Update file - set as GENERATED. // // cd.SetGeneratedFlagVersion( 'Y', document.IssueNumber ); RepClientDocument.SetGeneratedFlagVersion( cd, 'Y', document.IssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " - Generated successfully" ); uioutput.AddOutputMessage( "Document generated: " + clientFileLocationName, processName, userID ); #endregion Word } else if ( doco.clientDocument.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL ) { // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ ExcelSpreadsheetTasks.CopyDocument( sourceFileLocationName, clientFileLocationName, ts, uioutput, processName, userID ); // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // Update file - set as GENERATED. // //cd.SetGeneratedFlagVersion( 'Y', document.IssueNumber ); RepClientDocument.SetGeneratedFlagVersion( cd, 'Y', document.IssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " - Generated successfully - " + clientFileLocationName ); uioutput.AddOutputMessage( "Document generated: " + clientFileLocationName, processName, userID ); } else { File.Copy( sourceFileLocationName, clientFileLocationName ); uioutput.AddOutputMessage( "File copied but not modified: " + Path.GetExtension( doco.clientDocument.FileName ) + " == File: " + clientFileLocationName, processName, userID ); } } } // close word application vkWordApp.Quit( SaveChanges: ref vkTrue, OriginalFormat: ref vkTrue, RouteDocument: ref vkFalse ); vkExcelApp.Quit(); uioutput.AddOutputMessage( "End time: " + System.DateTime.Now.ToString(), processName, userID ); } /// <summary> /// Generate document for client (no treeview required) /// </summary> public void GenerateDocumentForClient() { // Load documents in tree // TreeView tvFileList = new TreeView(); // List client document list // var documentSetList = new ClientDocument(); //documentSetList.List(this.clientID, this.clientDocSetID); RepClientDocument.List( documentSetList, this.clientID, this.clientDocSetID ); tvFileList.Nodes.Clear(); // documentSetList.ListInTree(tvFileList, "CLIENT"); RepClientDocument.ListInTree( documentSetList, tvFileList, "CLIENT" ); // Generate document // this.GenerateDocumentsForClient( tvFileList.Nodes [0] ); } /// <summary> /// Generate documents based on tree /// </summary> /// <param name="clientID"></param> /// <param name="clientDocSetID"></param> /// <param name="uioutput"></param> /// <param name="overrideDocuments"></param> /// <param name="documentsTreeNode"></param> public void GenerateDocumentsForClient( TreeNode documentsTreeNode ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Start time: " + System.DateTime.Now.ToString(), processName, userID ); filecount = documentsTreeNode.GetNodeCount( includeSubTrees: true ); estimated = System.DateTime.Now.AddSeconds( 5 * filecount ); if ( uioutput != null ) uioutput.UpdateProgressBar( valueForProgressBar, estimated ); GenerateDocumentsController( documentsTreeNode ); if ( uioutput != null ) uioutput.AddOutputMessage( "End time: " + System.DateTime.Now.ToString(), processName, userID ); // Set end bar if ( uioutput != null ) uioutput.UpdateProgressBar( 100, estimated ); } /// <summary> /// This operation updates the destination folder following the /// hierarchy of the tree instead of the initial location. /// </summary> /// <param name="documentsTreeNode"></param> public static ResponseStatus UpdateDestinationFolder( int clientID, int clientDocumentSetUID ) { ResponseStatus response = new ResponseStatus(); response.Contents = "Destination folder updated successfully."; // Fix root folder first // ClientDocument clientDocument = new ClientDocument(); RepClientDocument.FixRootFolder(clientID, clientDocumentSetUID); var listOfDocuments = RepClientDocument.ListS( clientID, clientDocumentSetUID ); foreach ( var doco in listOfDocuments ) { // Update location // ResponseStatus destLocationDerivedClient = RepClientDocument.GetDocumentPath( doco.clientDocument ); string destLocationDerived = destLocationDerivedClient.Contents.ToString(); RepClientDocument.UpdateFieldString( doco.clientDocument.UID, "Location", destLocationDerived ); // Update file name // if ( doco.clientDocument.IsFolder == 'Y' ) { if ( doco.clientDocument.IsRoot == 'Y') RepClientDocument.UpdateFieldString( doco.clientDocument.UID, "FileName", doco.clientDocument.FileName ); else RepClientDocument.UpdateFieldString( doco.clientDocument.UID, "FileName", doco.document.FileName ); } response.Contents = destLocationDerived; } return response; } /// <summary> /// Generate Documents Controller (Word must be previously initialised /// </summary> private void GenerateDocumentsController( TreeNode documentsTreeNode ) { scClientDocSetDocLink documentTN = new scClientDocSetDocLink(); // Get List of documents for a client // if ( documentsTreeNode.Tag.GetType().Name == "scClientDocSetDocLink" ) { documentTN = (scClientDocSetDocLink) documentsTreeNode.Tag; } else { if ( documentsTreeNode.Tag.GetType().Name == "Document" ) { if ( documentTN.clientDocument == null ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Error CDISNULL019202 - client document is null.", processName, userID ); if ( uioutput != null ) uioutput.AddErrorMessage( "Error CDISNULL019202 - client document is null. Generation stopped.", processName, userID ); return; } documentTN.clientDocument.RecordType = FCMConstant.RecordType.DOCUMENT; documentTN.document = (Model.ModelDocument.Document) documentsTreeNode.Tag; } } // If it is a document, generate if ( documentTN.clientDocument.RecordType.Trim() != FCMConstant.RecordType.FOLDER ) { #region Generate Document // Generate // Retrieve updated file name from source Model.ModelDocument.Document document = new Model.ModelDocument.Document(); document.UID = documentTN.clientDocument.FKDocumentUID; // document.Read(); document = RepDocument.Read( false, documentTN.clientDocument.FKDocumentUID ); if ( uioutput != null ) uioutput.AddOutputMessage( "Inspecting file: " + document.UID + " === " + document.Name, processName, userID ); // if (iconMessage != null) iconMessage.Text = "Start time: " + System.DateTime.Now.ToString(); // Update client records with new file name // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = documentTN.clientDocument.UID; cd.SourceFileName = document.FileName; // cd.Read(); // Set comboIssueNumber and File Name // RepClientDocument.SetClientDestinationFile( clientDocument: cd, clientUID: documentTN.clientDocument.FKClientUID, documentCUID: document.CUID, sourceVersionNumber: document.IssueNumber, simpleFileName: document.SimpleFileName ); //cd.UpdateSourceFileName(); // RepClientDocument.UpdateSourceFileName( cd ); // Update memory with latest file name documentTN.clientDocument.SourceFileName = cd.SourceFileName; string sourceFileLocationName = Utils.getFilePathName( documentTN.clientDocument.SourceLocation, documentTN.clientDocument.SourceFileName ); // check if source folder/ file exists if ( string.IsNullOrEmpty( documentTN.clientDocument.Location ) ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Document Location is empty.", processName, userID ); return; } if ( string.IsNullOrEmpty( documentTN.clientDocument.FileName ) ) { if ( uioutput != null ) uioutput.AddOutputMessage( "File Name is empty.", processName, userID ); return; } if ( !File.Exists( sourceFileLocationName ) ) { string er = "File does not exist " + sourceFileLocationName + " - File Name: " + documentTN.clientDocument.SourceFileName; if ( uioutput != null ) uioutput.AddOutputMessage( er, processName, userID ); if ( uioutput != null ) uioutput.AddErrorMessage( er, processName, userID ); return; } // Check if destination folder exists // if ( string.IsNullOrEmpty( cds.Folder ) ) { string er = "Destination folder not set. Generation stopped."; if ( uioutput != null ) uioutput.AddOutputMessage( er, processName, userID ); return; } string PhysicalCDSFolder = Utils.GetPathName( cds.Folder ); if ( !Directory.Exists( PhysicalCDSFolder ) ) Directory.CreateDirectory( PhysicalCDSFolder ); // Generate one document (Folder will also be created in this call) // // Get time before file var previousTime = System.DateTime.Now; // =================================================================== // // try { // GenerateDocument( documentTN ); GenerateSingleDocument( documentTN.clientDocument.UID, isRestart: false, fixDestinationFolder: true ); } catch ( Exception ex ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Error generating document. " + documentTN.document.FileName + " " + ex, processName, userID ); } // // // =================================================================== // Get time after file var agora = System.DateTime.Now; fileprocessedcount++; valueForProgressBar = ( fileprocessedcount / filecount ) * 100; int leftToProcess = filecount - Convert.ToInt32( fileprocessedcount ); // Get the time it took to process one file TimeSpan span = agora.Subtract( previousTime ); // Average span in seconds acumulatedSpanInSec += span.Seconds; averageSpanInSec = acumulatedSpanInSec / fileprocessedcount; // Calculate the estimated time to complete estimated = System.DateTime.Now.AddSeconds( averageSpanInSec * leftToProcess ); if ( uioutput != null ) uioutput.UpdateProgressBar( valueForProgressBar, estimated, leftToProcess ); return; #endregion Generate Document // Processing for one file ends here } else { // If item imported is a FOLDER // This is the client destination folder (and name) // string clientDestinationFileLocation = documentTN.clientDocument.Location.Trim(); if ( !string.IsNullOrEmpty( clientDestinationFileLocation ) ) { string clientDestinationFileLocationName = Utils.getFilePathName( clientDestinationFileLocation, documentTN.clientDocument.FileName.Trim() ); // string PhysicalLocation = Utils.GetPathName(clientDestinationFileLocation); string PhysicalLocation = clientDestinationFileLocationName; if ( uioutput != null ) uioutput.AddOutputMessage( "Processing Folder: " + PhysicalLocation, processName, userID ); if ( !string.IsNullOrEmpty( PhysicalLocation ) ) { if ( !Directory.Exists( PhysicalLocation ) ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Folder Created: " + clientDestinationFileLocationName, processName, userID ); Directory.CreateDirectory( PhysicalLocation ); } else { if ( uioutput != null ) uioutput.AddOutputMessage( "Folder Already Exists: " + clientDestinationFileLocationName, processName, userID ); } } } else { if ( uioutput != null ) uioutput.AddOutputMessage( "Folder Ignored: " + documentTN.document.Name, processName, userID ); } // Process each document in folder // foreach ( TreeNode tn in documentsTreeNode.Nodes ) { scClientDocSetDocLink doco = (scClientDocSetDocLink) tn.Tag; GenerateDocumentsController( tn ); } } } /// <summary> /// Generate one document - Stop using this one ASAP, replace by GenerateSingleDocument /// </summary> /// <param name="doco"></param> public void GenerateDocumentTBD( scClientDocSetDocLink doco, string processName, string userID ) { // Deprecated - use GenerateSingleDocument if possible // // // Retrieve latest version // Model.ModelDocument.Document document = new Model.ModelDocument.Document(); document.UID = doco.clientDocument.FKDocumentUID; // document.Read(); RepDocument.Read( false, doco.clientDocument.FKDocumentUID ); string msg = ">>> Generating file: " + document.UID + " === " + document.SimpleFileName; if ( uioutput != null ) uioutput.AddOutputMessage( msg, processName, userID ); // if (iconMessage != null) iconMessage.Text = ">>> Generating file: " + document.UID; // Locate source file // string sourceFileLocationName = Utils.getFilePathName( doco.clientDocument.SourceLocation, doco.clientDocument.SourceFileName ); // Find the parent folder location // int parentUID = doco.clientDocument.ParentUID; var cdParent = new ClientDocument(); cdParent.UID = parentUID; // cdParent.Read(); cdParent = RepClientDocument.Read( parentUID ); // This is the client destination folder (and name) // //ResponseStatus destLocationDerivedClient = ClientDocument.GetDocumentPath(doco.clientDocument); //string destLocationDerived = destLocationDerivedClient.Contents.ToString(); string clientDestinationFileLocation = doco.clientDocument.Location.Trim(); string clientDestinationFileLocationName = Utils.getFilePathName( clientDestinationFileLocation, doco.clientDocument.FileName.Trim() ); // This is the source client file name // string clientSourceFileLocation = doco.clientDocument.Location.Trim(); string clientSourceFileLocationName = Utils.getFilePathName( clientSourceFileLocation, doco.clientDocument.FileName.Trim() ); // Source location and destination may be different. // The destination of the file must be the one where it lives on the actual tree // To determine where the file should be located, we need to get the parent folder // The only way to determine the parent folder is walking through the entire tree from the root. // The root is the only thing that can be trusted. Every other location is dependent on the root. // The determination of the file location occurs in 2 parts. The one here is the second part. // At this point we are not going to use the source location of the original document, instead // we are going to use the client document location // // Check if destination folder directory exists // string PhysicalLocation = Utils.GetPathName( clientDestinationFileLocation ); if ( string.IsNullOrEmpty( PhysicalLocation ) ) { string er = "Location is empty " + clientDestinationFileLocation + "\n" + "File Name: " + doco.document.Name; if ( uioutput != null ) uioutput.AddOutputMessage( er, processName, userID ); return; } // 02/04/2011 // This step should be done when the "FOLDER" record is created and not when the document // is generated // //if (!Directory.Exists( PhysicalLocation )) // Directory.CreateDirectory( PhysicalLocation ); // However the folder existence must be checked // if ( !Directory.Exists( PhysicalLocation ) ) { Directory.CreateDirectory( PhysicalLocation ); string er = "Destination folder has been created with File! " + PhysicalLocation + "\n" + "File Name: " + doco.document.Name; if ( uioutput != null ) uioutput.AddOutputMessage( er, processName, userID ); //return; } if ( File.Exists( clientDestinationFileLocationName ) ) { // Proceed but report in list // if ( overrideDocuments == "Yes" ) { // Delete file try { File.Delete( clientDestinationFileLocationName ); if ( uioutput != null ) uioutput.AddOutputMessage( "File deleted... " + document.SimpleFileName, processName, userID ); } catch ( Exception ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Error deleting file " + document.SimpleFileName, processName, userID ); if ( uioutput != null ) uioutput.AddErrorMessage( "Error deleting file " + document.SimpleFileName, processName, userID ); return; } } else { if ( uioutput != null ) uioutput.AddOutputMessage( "File already exists " + document.SimpleFileName, processName, userID ); return; } } // Copy and fix file // if ( uioutput != null ) uioutput.AddOutputMessage( "Replacing variables... ", processName, userID ); // Word Documents // if ( doco.clientDocument.RecordType.Trim() == FCMConstant.RecordType.FOLDER ) { // Update file - set as GENERATED. // // This is the moment where the folder destination has to be created // and the folder db record has to be updated with the location // if ( !Directory.Exists( PhysicalLocation ) ) Directory.CreateDirectory( PhysicalLocation ); if ( uioutput != null ) uioutput.AddOutputMessage( "FOLDER: " + doco.clientDocument.SourceFileName, processName, userID ); } else { // If is is not a folder, it must be a regular file. // Trying to copy it as well... // var currentDocumentPath = Path.GetExtension( doco.clientDocument.FileName ); if ( doco.clientDocument.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.WORD ) { #region Word // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ var results = WordDocumentTasks.CopyDocument( sourceFileLocationName, clientSourceFileLocationName, listOfWordsToReplace, vkWordApp, uioutput, processName, userID ); if ( results.ReturnCode < 0 ) { // Error has occurred // var er = (System.Exception) results.Contents; if ( uioutput != null ) uioutput.AddOutputMessage( "ERROR: " + er.ToString(), processName, userID ); if ( uioutput != null ) uioutput.AddErrorMessage( "ERROR: " + er.ToString(), processName, userID ); return; } #endregion Word } else if ( doco.clientDocument.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL ) { // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ ExcelSpreadsheetTasks.CopyDocument( sourceFileLocationName, clientSourceFileLocationName, listOfWordsToReplace, uioutput, processName, userID ); } else { File.Copy( sourceFileLocationName, clientSourceFileLocationName ); if ( uioutput != null ) uioutput.AddOutputMessage( "File copied but not modified: " + Path.GetExtension( doco.clientDocument.FileName ) + " == File: " + clientSourceFileLocationName, processName, userID ); } // // Instantiate client document ClientDocument cd = new ClientDocument(); cd.UID = doco.clientDocument.UID; // Update file - set as GENERATED. // RepClientDocument.SetGeneratedFlagVersion( cd, 'Y', document.IssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " - Generated successfully - " ); if ( uioutput != null ) uioutput.AddOutputMessage( "Document generated: " + clientDestinationFileLocationName, processName, userID ); } return; } /// <summary> /// Generate selected documents /// </summary> /// <param name="clientDocumentUIDList"></param> public void GenerateGroupOfDocuments( List<int> clientDocumentUIDList, bool isRestart ) { // Read Local config to check if it has to stop // string stopGeneration = XmlConfig.ReadLocal( MakConstant.ConfigXml.StopGeneration ); if ( stopGeneration == "Y" ) { if ( uioutput != null ) uioutput.AddOutputMessage( "!!! Generation has stopped before first document using config.", processName, userID ); return; } int i = 0; bool fixfolders = false; foreach (var docuid in clientDocumentUIDList) { i++; if (uioutput != null) uioutput.AddOutputMessage(".....", processName, userID); if (uioutput != null) uioutput.AddOutputMessage(".....", processName, userID); if (uioutput != null) uioutput.AddOutputMessage("Generating document # " + docuid.ToString(), processName, userID); if (uioutput != null) uioutput.AddOutputMessage(">>", processName, userID); fixfolders = false; if (i == 1) fixfolders = true; var response = GenerateSingleDocument(docuid, isRestart, fixfolders); // Read Local config to check if it has to stop // stopGeneration = XmlConfig.ReadLocal(MakConstant.ConfigXml.StopGeneration); if (stopGeneration == "Y") { if (uioutput != null) uioutput.AddOutputMessage("!!! Generation has stopped using config.", processName, userID); break; } } // Try to make parallel //Parallel.ForEach(clientDocumentUIDList, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (docuid) => //{ // processName = "Thread::" + Thread.CurrentThread.ManagedThreadId.ToString(); // i++; // if (uioutput != null) uioutput.AddOutputMessage(".....", processName, userID); // if (uioutput != null) uioutput.AddOutputMessage(".....", processName, userID); // if (uioutput != null) uioutput.AddOutputMessage("Generating document # " + docuid.ToString(), processName, userID); // if (uioutput != null) uioutput.AddOutputMessage(">>", processName, userID); // fixfolders = false; // if (i == 1) // fixfolders = true; // var response = GenerateSingleDocument(docuid, isRestart, fixfolders); //}); } /// <summary> /// Generate single document /// </summary> /// <param name="clientDocumentUID"></param> public ResponseStatus GenerateSingleDocument( int clientDocumentUID, bool isRestart, bool fixDestinationFolder ) { ResponseStatus response = new ResponseStatus(MessageType.Error); // Reporting activity to master // BUSFCMBackendStatus.ReportStatus( HeaderInfo.Instance, processName, "Generating document # " + clientDocumentUID.ToString() ); // Read client document // var clientDocument = RepClientDocument.Read( clientDocumentUID ); if ( clientDocument.UID == 0 ) { LogFile.WriteToTodaysLogFile( "Client Document not found ID = 0", "DocumentGeneration.cs", processName ); return new ResponseStatus( MessageType.Error ) {Message = "Client Document not found ID = 0", ReturnCode = -0040, ReasonCode = 0002}; } if ( clientDocument.IsLocked == 'Y' ) { LogFile.WriteToTodaysLogFile( "Document is locked. Client updates have been made.", processName ); // Update file - set as GENERATED. // RepClientDocument.SetGeneratedFlagVersion( clientDocument, 'E', clientDocument.SourceIssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " Document is locked." ); return new ResponseStatus(MessageType.Warning) { Message = "Document is locked. Client updates have been made.", ReturnCode = 0001, ReasonCode = 0004 }; } if (fixDestinationFolder) { // Fix path // uioutput.AddOutputMessage("Fixing destination folder...", "UI", Utils.UserID); //LogFile.WriteToTodaysLogFile("Fixing destination folder...", processName); var responseX = UpdateDestinationFolder(clientID, clientDocument.FKClientDocumentSetUID); } // // Update flag to FAILED... in case something happen before the end of the process // RepClientDocument.SetGeneratedFlagVersion( clientDocument, 'E', clientDocument.SourceIssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " - Start: " + " Generation has started." ); // Retrieve latest version // var document = new Model.ModelDocument.Document(); document.UID = clientDocument.FKDocumentUID; document = RepDocument.Read( false, clientDocument.FKDocumentUID ); if ( document.UID <= 0 ) { var responseerror = new ResponseStatus( MessageType.Error ); responseerror.Message = "Document not found."; if ( uioutput != null ) uioutput.AddOutputMessage( responseerror.Message, processName: processName, userID: userID ); return responseerror; } if ( document.Skip == "Y" ) { var responseerror = new ResponseStatus( MessageType.Warning ); responseerror.Message = "Skipping document "+ document.CUID + " - because of skip indicator. Contact support."; if ( uioutput != null ) uioutput.AddOutputMessage( responseerror.Message, processName: processName, userID: userID ); return responseerror; } // It can't be skipped, it has to be copied. // //if ( document.SourceCode == "CLIENT" ) //{ // var responseerror = new ResponseStatus( MessageType.Warning ); // responseerror.Message = "Skipping document " + document.CUID + " - because is is client specific."; // if ( uioutput != null ) uioutput.AddOutputMessage( responseerror.Message, processName: processName, userID: userID ); // return responseerror; //} string msg = ">>> Generating file: " + document.UID + " === " + document.FileName; if ( uioutput != null ) uioutput.AddOutputMessage( msg, processName: processName, userID: userID ); // Check if source version has changed // If the source version has changed we need to physically delete the current file if ( document.IssueNumber != clientDocument.SourceIssueNumber ) { // Delete client copy of document if ( uioutput != null ) uioutput.AddOutputMessage( "Version has changed " + document.SimpleFileName, processName: processName, userID: userID ); if ( uioutput != null ) uioutput.AddOutputMessage( "Trying to delete current file. " + document.SimpleFileName, processName: processName, userID: userID ); string currentClientFile = Utils.getFilePathName( clientDocument.Location, clientDocument.FileName ); // Delete file try { File.Delete( currentClientFile ); } catch ( Exception ) { string errormessage = "Error deleting old version file or file not found." + currentClientFile; if ( uioutput != null ) uioutput.AddOutputMessage( errormessage, processName: processName, userID: userID ); if ( uioutput != null ) uioutput.AddErrorMessage( errormessage, processName: processName, userID: userID ); if ( uioutput != null ) uioutput.AddOutputMessage( "Proceeding with generation...", processName: processName, userID: userID ); // Ok to proceed } } // ############################################################### if ( clientDocument.IsFolder == 'Y' || clientDocument.IsFolder == 'Y') { // Do not touch the name since it has been updated already. // Folders and Root shouldn't be touched } else { // Update client records with new file name // clientDocument.SourceFileName = document.FileName; // Set comboIssueNumber and File Name // RepClientDocument.SetClientDestinationFile( clientDocument: clientDocument, clientUID: clientDocument.FKClientUID, documentCUID: document.CUID, sourceVersionNumber: document.IssueNumber, simpleFileName: document.SimpleFileName ); //cd.UpdateSourceFileName(); RepClientDocument.UpdateSourceFileName( clientDocument ); } // ############################################################### // Locate source file // string sourceFileLocationName = Utils.getFilePathName( clientDocument.SourceLocation, clientDocument.SourceFileName ); // Find the parent folder location // int parentUID = clientDocument.ParentUID; var cdParent = new ClientDocument(); cdParent.UID = parentUID; // cdParent.Read(); cdParent = RepClientDocument.Read( parentUID ); // This is the client destination folder (and name) // //ResponseStatus destLocationDerivedClient = ClientDocument.GetDocumentPath(doco.clientDocument); //string destLocationDerived = destLocationDerivedClient.Contents.ToString(); string clientDestinationFileLocation = clientDocument.Location.Trim(); string clientDestinationFileLocationName = Utils.getFilePathName( clientDestinationFileLocation, clientDocument.FileName.Trim() ); // This is the source client file name // string clientSourceFileLocation = clientDocument.Location.Trim(); string clientSourceFileLocationName = Utils.getFilePathName( clientSourceFileLocation, clientDocument.FileName.Trim() ); // Source location and destination may be different. // The destination of the file must be the one where it lives on the actual tree // To determine where the file should be located, we need to get the parent folder // The only way to determine the parent folder is walking through the entire tree from the root. // The root is the only thing that can be trusted. Every other location is dependent on the root. // The determination of the file location occurs in 2 parts. The one here is the second part. // At this point we are not going to use the source location of the original document, instead // we are going to use the client document location // // Check if destination folder directory exists // string PhysicalLocation = Utils.GetPathName( clientDestinationFileLocation ); if ( string.IsNullOrEmpty( PhysicalLocation ) ) { string er = "Location is empty " + clientDestinationFileLocation + "\n" + "File Name: " + document.Name; if ( uioutput != null ) uioutput.AddOutputMessage( er, processName: processName, userID: userID ); RepClientDocument.SetGeneratedFlagVersion( clientDocument, 'E', 0, DateTime.Today.ToString( "yyyyMMdd" ) + " - Error: " + er ); var responseerror = new ResponseStatus( MessageType.Error ); responseerror.Message = er; return responseerror; } // 02/04/2011 // This step should be done when the "FOLDER" record is created and not when the document // is generated // //if (!Directory.Exists( PhysicalLocation )) // Directory.CreateDirectory( PhysicalLocation ); // However the folder existence must be checked // if ( !Directory.Exists( PhysicalLocation ) ) { Directory.CreateDirectory( PhysicalLocation ); string er = "Destination folder has been created with File! " + PhysicalLocation + "\n" + "File Name: " + document.Name; if ( uioutput != null ) uioutput.AddOutputMessage( er, processName: processName, userID: userID ); //return; } // In case of restart, do not override what has been generated. // if ( isRestart ) overrideDocuments = "No"; if ( File.Exists( clientDestinationFileLocationName ) ) { // Proceed but report in list // if ( overrideDocuments == "Yes" ) { // Delete file try { File.Delete( clientDestinationFileLocationName ); } catch ( Exception ) { if ( uioutput != null ) uioutput.AddOutputMessage( "Error deleting file " + document.SimpleFileName, processName: processName, userID: userID ); if ( uioutput != null ) uioutput.AddErrorMessage( "Error deleting file " + document.SimpleFileName, processName: processName, userID: userID ); var responseerror = new ResponseStatus( MessageType.Error ); responseerror.Message = "Error deleting file " + document.SimpleFileName; RepClientDocument.SetGeneratedFlagVersion( clientDocument, 'E', 0, DateTime.Today.ToString( "yyyyMMdd" ) + " - Error: " + responseerror.Message ); return responseerror; } if ( uioutput != null ) uioutput.AddOutputMessage( "File deleted... " + document.SimpleFileName, processName: processName, userID: userID ); } else { var responseerror = new ResponseStatus( MessageType.Error ) { Message = "File already exists and it won't be replaced. " + document.SimpleFileName }; if ( uioutput != null ) uioutput.AddOutputMessage( responseerror.Message, processName: processName, userID: userID ); // Do not update the source issue number in this case // RepClientDocument.SetGeneratedFlagVersion( clientDocument, 'Y', clientDocument.SourceIssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " - Warning: " + responseerror.Message ); return responseerror; } } // Copy and fix file // if ( uioutput != null ) uioutput.AddOutputMessage( "Replacing variables... ", processName: processName, userID: userID ); // Word Documents // if ( clientDocument.RecordType.Trim() == FCMConstant.RecordType.FOLDER ) { // Update file - set as GENERATED. // // This is the moment where the folder destination has to be created // and the folder db record has to be updated with the location // if ( !Directory.Exists( PhysicalLocation ) ) Directory.CreateDirectory( PhysicalLocation ); if ( uioutput != null ) uioutput.AddOutputMessage( "FOLDER: " + clientDocument.SourceFileName, processName: processName, userID: userID ); } else { // If is is not a folder, it must be a regular file. // Trying to copy it as well... // var currentDocumentPath = Path.GetExtension( clientDocument.FileName ); if ( document.SourceCode == "CLIENT" ) { // Copy only // File.Copy( sourceFileLocationName, clientSourceFileLocationName ); if ( uioutput != null ) uioutput.AddOutputMessage( "Client Specific - File copied but not modified: " + Path.GetExtension( clientDocument.FileName ) + " == File: " + clientSourceFileLocationName, processName, userID ); } else { if (clientDocument.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.WORD) { #region Word // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ var results = WordDocumentTasks.CopyDocument(sourceFileLocationName, clientSourceFileLocationName, listOfWordsToReplace, vkWordApp, uioutput, processName, userID); if (results.ReturnCode < 0) { // Error has occurred // var er = (System.Exception) results.Contents; if (uioutput != null) uioutput.AddOutputMessage("ERROR: " + er.ToString(), processName, userID); if (uioutput != null) uioutput.AddErrorMessage("ERROR: " + er.ToString(), processName, userID); var responseerror = new ResponseStatus(MessageType.Error) {Message = "ERROR: " + er.ToString()}; RepClientDocument.SetGeneratedFlagVersion(clientDocument, 'E', 0, DateTime.Today.ToString("yyyyMMdd") + " - Error: " + responseerror.Message); return responseerror; } #endregion Word // Generate Register of Systems Documents // if (document.CUID == "SRG-01") { WordReport wr = new WordReport(ClientID: clientDocument.FKClientUID, ClientDocSetID: clientDocument.FKClientDocumentSetUID, UIoutput: uioutput, OverrideDocuments: overrideDocuments); // List client document list // var documentSetList = new ClientDocument(); //documentSetList.List(Utils.ClientID, Utils.ClientSetID); var cdlr = new BUSClientDocument.ClientDocumentListRequest(); cdlr.clientUID = clientDocument.FKClientUID; cdlr.clientDocumentSetUID = clientDocument.FKClientDocumentSetUID; var response2 = BUSClientDocument.List(cdlr); documentSetList.clientDocSetDocLink = response2.clientList; TreeView tvFileList = new TreeView(); BUSClientDocument.ListInTree(documentSetList, tvFileList, "CLIENT"); var location = Utils.GetPathName(clientDocument.Location); var response3 = wr.RegisterOfSytemDocuments2(tvFileList, location, clientDocument.FileName, processName, userID); uioutput.AddOutputMessage(response.Message, processName: processName, userID: userID); } } else if (clientDocument.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL) { // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Generate Document and replace tag values in new document generated // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ ExcelSpreadsheetTasks.CopyDocument(sourceFileLocationName, clientSourceFileLocationName, listOfWordsToReplace, uioutput, processName, userID); } else { File.Copy(sourceFileLocationName, clientSourceFileLocationName); if (uioutput != null) uioutput.AddOutputMessage("File copied but not modified: " + Path.GetExtension(clientDocument.FileName) + " == File: " + clientSourceFileLocationName, processName, userID); } } // // Instantiate client document var cd = new ClientDocument(); cd.UID = clientDocument.UID; // Update file - set as GENERATED. // RepClientDocument.SetGeneratedFlagVersion( clientDocument, 'Y', document.IssueNumber, DateTime.Today.ToString( "yyyyMMdd" ) + " All good." ); if ( uioutput != null ) uioutput.AddOutputMessage( "Document generated: " + clientDestinationFileLocationName, processName, userID ); } ResponseStatus responseSuccessfull = new ResponseStatus(); responseSuccessfull.Message = "File generated successfully."; return responseSuccessfull; } /// <summary> /// Generate selected documents /// </summary> /// <param name="clientDocumentUIDList"></param> public void GenerateFullSetForClient( int clientID, int clientDocumentSetUID, bool isRestart ) { var listOfClientDocs = RepClientDocument.ListS(clientID, clientDocumentSetUID); List<int> listint = new List<int>(); foreach (var doc in listOfClientDocs) { listint.Add(doc.clientDocument.UID); } // Fix path // var response = UpdateDestinationFolder( clientID, clientDocumentSetUID ); GenerateGroupOfDocuments(listint, isRestart); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FCMMySQLBusinessLibrary.Model.ModelBackendStatus { public class BackendStatus { public int UID { get; set; } public string ProcessName { get; set; } public string Status { get; set; } public DateTime ReportDateTime { get; set; } public string Details { get; set; } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Model.ModelBackendStatus; using FCMMySQLBusinessLibrary.Repository; using MackkadoITFramework.Utils; using System.Data.Odbc; namespace FCModbcBusinessLibrary.Repository.RepositoryBackendStatus { public class RepBackendStatus : BackendStatus { // ----------------------------------------------------- // List clients // ----------------------------------------------------- public static BackendStatus ReadLast( HeaderInfo headerInfo, string processName ) { var retBackendStatus = new BackendStatus(); using (var connection = new OdbcConnection(ConnString.ConnectionStringODBC)) { var commandString = string.Format( " SELECT " + " UID, " + " ProcessName, " + " ReportDateTime, " + " Details, " + " Status " + " FROM backendstatus" + " WHERE ProcessName = @processName" + " ORDER BY UID DESC " ); using (var command = new OdbcCommand( commandString, connection ) ) { connection.Open(); command.Parameters.Add("@processName", OdbcType.VarChar).Value = processName; try { using ( OdbcDataReader reader = command.ExecuteReader() ) { while ( reader.Read() ) { try { retBackendStatus.UID = Convert.ToInt32( reader [FCMDBFieldName.BackendStatus.UID] ); } catch { retBackendStatus.UID = 0; } try { retBackendStatus.ReportDateTime = Convert.ToDateTime( reader [FCMDBFieldName.BackendStatus.ReportDateTime] ); } catch { retBackendStatus.ReportDateTime = DateTime.Today; } retBackendStatus.ProcessName = reader [FCMDBFieldName.BackendStatus.ProcessName] as string; retBackendStatus.Details = reader [FCMDBFieldName.BackendStatus.Details] as string; retBackendStatus.Status = reader [FCMDBFieldName.BackendStatus.Status] as string; break; } } } catch ( Exception ex ) { string error = ex.ToString(); LogFile.WriteToTodaysLogFile( ex.ToString(), headerInfo.UserID, "", "Client.cs" ); } } } return retBackendStatus; } // ----------------------------------------------------- // List clients // ----------------------------------------------------- public static List<BackendStatus> List(HeaderInfo headerInfo) { List<BackendStatus> retBackendStatusList = new List<BackendStatus>(); using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID, " + " ProcessName, " + " ReportDateTime, " + " Details, " + " Status " + " FROM backendstatus" + " WHERE ProcessName = @processName" + " ORDER BY UID DESC " ); using (var command = new OdbcCommand( commandString, connection ) ) { connection.Open(); try { using ( OdbcDataReader reader = command.ExecuteReader()) { while ( reader.Read() ) { BackendStatus backendStatus = new BackendStatus(); try { backendStatus.UID = Convert.ToInt32( reader [FCMDBFieldName.BackendStatus.UID] ); } catch { backendStatus.UID = 0; } backendStatus.ProcessName = reader [FCMDBFieldName.BackendStatus.ProcessName] as string; backendStatus.Details = reader [FCMDBFieldName.BackendStatus.Details] as string; backendStatus.Status = reader [FCMDBFieldName.BackendStatus.Status] as string; try { backendStatus.ReportDateTime = Convert.ToDateTime( reader [FCMDBFieldName.BackendStatus.UID] ); } catch { backendStatus.ReportDateTime = DateTime.Today; } retBackendStatusList.Add( backendStatus ); } } } catch ( Exception ex ) { string error = ex.ToString(); LogFile.WriteToTodaysLogFile( ex.ToString(), headerInfo.UserID, "", "Client.cs" ); } } } return retBackendStatusList; } /// <summary> /// Add new status line /// </summary> /// <returns></returns> public static void Insert(HeaderInfo headerInfo, BackendStatus backendStatus, OdbcConnection connection = null) { int uid = 0; int nextUID = GetLastUID() + 1; backendStatus.UID = uid; if ( connection == null ) { connection = new OdbcConnection(ConnString.ConnectionString); connection.Open(); } var commandString = ( "INSERT INTO backendstatus " + "(" + FCMDBFieldName.BackendStatus.UID + "," + FCMDBFieldName.BackendStatus.ProcessName + "," + FCMDBFieldName.BackendStatus.ReportDateTime + "," + FCMDBFieldName.BackendStatus.Details + "," + FCMDBFieldName.BackendStatus.Status + ")" + " VALUES " + "( @UID " + ", @ProcessName " + ", @ReportDateTime " + ", @Details " + ", @Status " + " )" ); using (var command = new OdbcCommand( commandString, connection ) ) { command.Parameters.Add( "@UID", OdbcType.BigInt ).Value = nextUID; command.Parameters.Add("@ProcessName", OdbcType.VarChar).Value = backendStatus.ProcessName; command.Parameters.Add("@Status", OdbcType.VarChar).Value = backendStatus.Status; command.Parameters.Add("@Details", OdbcType.VarChar).Value = backendStatus.Details; command.Parameters.Add("@ReportDateTime", OdbcType.DateTime, 8).Value = backendStatus.ReportDateTime; command.ExecuteNonQuery(); } backendStatus.UID = nextUID; return; } /// <summary> /// Retrieve last UID /// </summary> /// <returns></returns> private static int GetLastUID() { int lastUID = 0; // // EA SQL database // using ( var connection = new OdbcConnection( ConnString.ConnectionString ) ) { var commandString = "SELECT MAX(UID) LASTUID FROM backendstatus"; using ( var command = new OdbcCommand( commandString, connection ) ) { connection.Open(); OdbcDataReader reader = command.ExecuteReader(); if ( reader.Read() ) { try { lastUID = Convert.ToInt32( reader ["LASTUID"] ); } catch ( Exception ) { lastUID = 0; } } } } return lastUID; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Helper; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelMetadata { public class ReportMetadata { private MySqlConnection _MySqlConnection; private string _dbConnectionString; private string _userID; public int UID { get; set; } public string RecordType { get; set; } // DF = Default; CS = Company Specific public string FieldCode { get; set; } public string ClientType { get; set; } public int ClientUID { get; set; } public string Description { get; set; } public string InformationType { get; set; } public string TableName { get; set; } public string FieldName { get; set; } public string FilePath { get; set; } public string FileName { get; set; } public string Condition { get; set; } public string CompareWith { get; set; } public char UseAsLabel { get; set; } public IEnumerable<string> RecordTypeListValues { get { var list = new List<string> { "Default", "Client Specific" }; return list; } } public List<ReportMetadata> reportMetadataList; /// <summary> /// Indicates whether the metafield is used for the client. Only used for client specific field. /// </summary> public char Enabled; public bool FoundinDB; // ----------------------------------------------------- // Constructor using userId and connection string // ----------------------------------------------------- public ReportMetadata() { } /// <summary> /// Returns the value of the metafield /// </summary> /// <returns></returns> public string GetValue() { string ret = ""; string select = ""; if (this.InformationType == Utils.InformationType.IMAGE) { select = this.Condition; // return select; } if (this.InformationType == Utils.InformationType.VARIABLE) { select = DateTime.Today.ToString().Substring(0,10); return select; } if (this.InformationType == Utils.InformationType.FIELD) { select = this.Condition; } if (string.IsNullOrEmpty(select)) { return ""; } // -------------------------------- // Get Variable // -------------------------------- //if (this.CompareWith == "CLIENT.UID") //{ // // select += Utils.ClientID.ToString(); // select += this.ClientUID.ToString(); //} // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = select; using (var command = new MySqlCommand( commandString, connection)) { if (this.CompareWith == "CLIENT.UID") { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = this.ClientUID; } connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { ret = reader[0].ToString(); } } } // If it is an image, get the final folder // if (this.InformationType == Utils.InformationType.IMAGE) { // string logoPathName = Utils.GetPathName( ret ); string logoPathName = Utils.getFilePathName( ret ); ret = logoPathName; } return ret; } /// <summary> /// Retrieve last Report Metadata UID /// </summary> /// <returns></returns> public static int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ReportMetadata"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Retrieve last Report Metadata UID /// </summary> /// <returns></returns> public static int GetLastUIDSubTransaction( MySqlConnection connection, MySqlTransaction MySqlTransaction, HeaderInfo headerInfo) { int LastUID = 0; // // EA SQL database // var commandString = "SELECT MAX(UID) LASTUID FROM ReportMetadata"; // var command = new MySqlCommand(commandString, connection, MySqlTransaction); var command = connection.CreateCommand(); command.CommandText = commandString; command.Transaction = MySqlTransaction; MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } return LastUID; } /// <summary> /// Add or update record. /// </summary> public void Save() { // Check if code value exists. // If it exists, update // Else Add a new one this.Read(true); bool results = this.FoundinDB; if (results) { this.Update(); } else { this.Add(); } } /// <summary> /// Add or update record. Sub Transactional /// </summary> public void SaveSubTransaction( MySqlConnection connection, MySqlTransaction MySqlTransaction, HeaderInfo headerInfo) { // Check if code value exists. // If it exists, update // Else Add a new one this.Read(true); bool results = this.FoundinDB; if (results) { this.UpdateSubTransaction(connection, MySqlTransaction, headerInfo); } else { this.AddSubTransaction(connection, MySqlTransaction, headerInfo); } } /// <summary> /// Add new report metadata /// </summary> private void Add() { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; DateTime _now = DateTime.Today; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO ReportMetadata " + "( " + " UID " + " ,RecordType " + " ,Description " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ,UseAsLabel " + " ) " + " VALUES " + " ( " + " @UID " + " ,@RecordType " + " ,@Description " + " ,@FieldCode " + " ,@ClientType " + " ,@ClientUID " + " ,@InformationType " + " ,@Condition " + " ,@CompareWith " + " ,@Enabled " + " ,@UseAsLabel" + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add("@RecordType", MySqlDbType.VarChar).Value = RecordType; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@FieldCode", MySqlDbType.VarChar).Value = FieldCode; command.Parameters.Add("@ClientType", MySqlDbType.VarChar).Value = ClientType; command.Parameters.Add("@ClientUID", MySqlDbType.Int32).Value = ClientUID; command.Parameters.Add("@InformationType", MySqlDbType.VarChar).Value = InformationType; command.Parameters.Add("@Condition", MySqlDbType.VarChar).Value = Condition; command.Parameters.Add("@CompareWith", MySqlDbType.VarChar).Value = CompareWith; command.Parameters.Add("@Enabled", MySqlDbType.VarChar).Value = Enabled; command.Parameters.Add("@UseAsLabel", MySqlDbType.VarChar).Value = UseAsLabel; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Add new report metadata /// </summary> private void AddSubTransaction( MySqlConnection connection, MySqlTransaction MySqlTransaction, HeaderInfo headerInfo) { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUIDSubTransaction( connection, MySqlTransaction, headerInfo ) + 1; DateTime _now = DateTime.Today; var commandString = ( "INSERT INTO ReportMetadata " + "( " + " UID " + " ,RecordType " + " ,Description " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ) " + " VALUES " + " ( " + " @UID " + " ,@RecordType " + " ,@Description " + " ,@FieldCode " + " ,@ClientType " + " ,@ClientUID " + " ,@InformationType " + " ,@Condition " + " ,@CompareWith " + " ,@Enabled " + " )" ); var command = new MySqlCommand(commandString, connection, MySqlTransaction); command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add("@RecordType", MySqlDbType.VarChar).Value = RecordType; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@FieldCode", MySqlDbType.VarChar).Value = FieldCode; command.Parameters.Add("@ClientType", MySqlDbType.VarChar).Value = ClientType; command.Parameters.Add("@ClientUID", MySqlDbType.Int32).Value = ClientUID; command.Parameters.Add("@InformationType", MySqlDbType.VarChar).Value = InformationType; command.Parameters.Add("@Condition", MySqlDbType.VarChar).Value = Condition; command.Parameters.Add("@CompareWith", MySqlDbType.VarChar).Value = CompareWith; command.Parameters.Add("@Enabled", MySqlDbType.VarChar).Value = Enabled; try { command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), headerInfo.UserID); } return; } /// <summary> /// Update metadata table /// </summary> private void Update() { string ret = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ReportMetadata " + "SET " + " FieldCode = @FieldCode " + // not setting record type... " ,RecordType = @RecordType " + " ,Description = @Description " + " ,ClientType = @ClientType " + " ,ClientUID = @ClientUID " + " ,InformationType = @InformationType " + " ,ConditionX = @Condition " + " ,CompareWith = @CompareWith " + " ,Enabled = @Enabled" + " ,UseAsLabel = @UseAsLabel" + " WHERE UID = @UID "); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FieldCode", MySqlDbType.VarChar ).Value = FieldCode; command.Parameters.Add("@RecordType", MySqlDbType.VarChar ).Value = RecordType; command.Parameters.Add("@Description", MySqlDbType.VarChar ).Value = Description; command.Parameters.Add("@ClientType", MySqlDbType.VarChar ).Value = ClientType; command.Parameters.Add("@InformationType", MySqlDbType.VarChar ).Value = InformationType; command.Parameters.Add("@ClientUID", MySqlDbType.VarChar ).Value = ClientUID; command.Parameters.Add("@UID", MySqlDbType.VarChar ).Value = UID; command.Parameters.Add("@Condition", MySqlDbType.VarChar ).Value = Condition; command.Parameters.Add("@CompareWith", MySqlDbType.VarChar ).Value = CompareWith; command.Parameters.Add("@Enabled", MySqlDbType.VarChar).Value = Enabled; command.Parameters.Add("@UseAsLabel", MySqlDbType.VarChar).Value = UseAsLabel; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Update metadata table /// </summary> private void UpdateSubTransaction( MySqlConnection connection, MySqlTransaction MySqlTransaction, HeaderInfo headerInfo) { string ret = "Item updated successfully"; var commandString = ( "UPDATE ReportMetadata " + "SET " + " FieldCode = @FieldCode " + // not setting record type... " ,RecordType = @RecordType " + " ,Description = @Description " + " ,ClientType = @ClientType " + " ,ClientUID = @ClientUID " + " ,InformationType = @InformationType " + " ,ConditionX = @Condition " + " ,CompareWith = @CompareWith " + " ,Enabled = @Enabled" + " WHERE UID = @UID "); var command = new MySqlCommand(commandString, connection, MySqlTransaction); command.Parameters.Add("@FieldCode", MySqlDbType.VarChar).Value = FieldCode; command.Parameters.Add("@RecordType", MySqlDbType.VarChar).Value = RecordType; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@ClientType", MySqlDbType.VarChar).Value = ClientType; command.Parameters.Add("@InformationType", MySqlDbType.VarChar).Value = InformationType; command.Parameters.Add("@ClientUID", MySqlDbType.VarChar).Value = ClientUID; command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = UID; command.Parameters.Add("@Condition", MySqlDbType.VarChar).Value = Condition; command.Parameters.Add("@CompareWith", MySqlDbType.VarChar).Value = CompareWith; command.Parameters.Add("@Enabled", MySqlDbType.VarChar).Value = Enabled; try { command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), headerInfo.UserID); } return; } /// <summary> /// Read metadata /// </summary> /// <param name="CheckOnly"></param> private void Read(bool CheckOnly) { CodeValue ret = null; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT UID " + " ,RecordType " + " ,FieldCode " + " ,Description " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ,UseAsLabel " + " FROM ReportMetadata " + " WHERE UID = @UID "; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); command.Parameters.Add(new MySqlParameter("UID", this.UID)); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { if (!CheckOnly) { this.UID = Convert.ToInt32( reader["UID"].ToString() ); this.RecordType = reader["RecordType"].ToString(); this.FieldCode = reader["FieldCode"].ToString(); this.Description = reader["Description"].ToString(); this.ClientType = reader["ClientType"].ToString(); this.ClientUID = Convert.ToInt32( reader["ClientUID"]); this.InformationType = reader["InformationType"].ToString(); this.Condition = reader["Condition"].ToString(); this.CompareWith = reader["CompareWith"].ToString(); this.Enabled = Convert.ToChar(reader["CompareWith"]); this.UseAsLabel = Convert.ToChar(reader["UseAsLabel"]); } this.FoundinDB = true; } catch (Exception ex) { this.Description = ex.ToString(); } } else { this.FoundinDB = false; } } } } // --------------------------------------------- // Read // --------------------------------------------- public bool Read(int clientUID, string fieldCode) { bool ret = false; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT UID " + " ,RecordType " + " ,FieldCode " + " ,Description " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ,UseAsLabel " + " FROM ReportMetadata " + " WHERE ClientUID = @CLIENTUID " + " AND FieldCode = @FIELDCODE "; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); command.Parameters.Add(new MySqlParameter("@CLIENTUID", clientUID)); command.Parameters.Add(new MySqlParameter("@FIELDCODE", fieldCode)); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.RecordType = reader["RecordType"].ToString(); this.FieldCode = reader["FieldCode"].ToString(); this.Description = reader["Description"].ToString(); this.ClientType = reader["ClientType"].ToString(); this.ClientUID = Convert.ToInt32(reader["ClientUID"]); this.InformationType = reader["InformationType"].ToString(); this.Condition = reader["Condition"].ToString(); this.CompareWith = reader["CompareWith"].ToString(); this.Enabled = Convert.ToChar(reader["Enabled"]); this.UseAsLabel = Convert.ToChar(reader["UseAsLabel"]); ret = true; } catch (Exception ex) { this.Description = ex.ToString(); } } } return ret; } } // --------------------------------------------- // Read // --------------------------------------------- public bool ReadSubTransaction( int clientUID, string fieldCode, MySqlConnection connection, MySqlTransaction MySqlTransaction, HeaderInfo headerInfo) { bool ret = false; // // EA SQL database // var commandString = string.Format( " SELECT UID " + " ,RecordType " + " ,FieldCode " + " ,Description " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ,UseAsLabel " + " FROM ReportMetadata " + " WHERE ClientUID = {0} " + " AND FieldCode = '{1}' ", clientUID, fieldCode); var command = new MySqlCommand(commandString, connection, MySqlTransaction); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.RecordType = reader["RecordType"].ToString(); this.FieldCode = reader["FieldCode"].ToString(); this.Description = reader["Description"].ToString(); this.ClientType = reader["ClientType"].ToString(); this.ClientUID = Convert.ToInt32(reader["ClientUID"]); this.InformationType = reader["InformationType"].ToString(); this.Condition = reader["Condition"].ToString(); this.CompareWith = reader["CompareWith"].ToString(); this.Enabled = Convert.ToChar(reader["Enabled"]); this.UseAsLabel = Convert.ToChar(reader["UseAsLabel"]); ret = true; } catch (Exception ex) { this.Description = ex.ToString(); } } return ret; } // --------------------------------------------- // Read // --------------------------------------------- public void FindMatch(int clientUID, string rmdItem) { CodeValue ret = null; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,RecordType " + " ,FieldCode " + " ,Description " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " FROM ReportMetadata " + " WHERE " + " ClientUID = {0} " + " AND FieldCode = '{1}' ", clientUID, rmdItem); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.RecordType = reader["RecordType"].ToString(); this.FieldCode = reader["FieldCode"].ToString(); this.Description = reader["Description"].ToString(); this.ClientType = reader["ClientType"].ToString(); this.ClientUID = Convert.ToInt32(reader["ClientUID"]); this.InformationType = reader["InformationType"].ToString(); this.FoundinDB = true; } catch (Exception ex) { this.Description = ex.ToString(); } } else { this.FoundinDB = false; } } } } // --------------------------------------------- // Update metadata table // --------------------------------------------- public bool Delete() { if (UID <= 0) return false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "DELETE ReportMetadata " + " WHERE UID = @UID "); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = UID; connection.Open(); command.ExecuteNonQuery(); } } return true; } public struct MetadataFieldCode { public const string COMPANYLOGO = "COMPANYLOGO"; } // ----------------------------------------------------- // List Global Fields // ----------------------------------------------------- public void ListDefault() { this.reportMetadataList = new List<ReportMetadata>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,Description " + " ,RecordType " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " ,UseAsLabel " + " FROM ReportMetadata " + " WHERE RecordType = '{0}'", "DF"); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ReportMetadata _reportMetadata = new ReportMetadata(); _reportMetadata.UID = Convert.ToInt32(reader["UID"].ToString()); _reportMetadata.Description = reader["Description"].ToString(); _reportMetadata.RecordType = reader["RecordType"].ToString(); _reportMetadata.FieldCode = reader["FieldCode"].ToString(); _reportMetadata.ClientType = reader["ClientType"].ToString(); _reportMetadata.Condition = reader["ConditionX"].ToString(); _reportMetadata.CompareWith = reader["CompareWith"].ToString(); _reportMetadata.Enabled = Convert.ToChar(reader["Enabled"]); try { _reportMetadata.UseAsLabel = Convert.ToChar(reader["UseAsLabel"]); } catch (Exception ex) { _reportMetadata.UseAsLabel = 'N'; } try { _reportMetadata.ClientUID = Convert.ToInt32(reader["ClientUID"]); } catch (Exception ex) { _reportMetadata.ClientUID = 0; } _reportMetadata.InformationType = reader["InformationType"].ToString(); this.reportMetadataList.Add(_reportMetadata); } } } } } // ----------------------------------------------------- // List available report metadata // ----------------------------------------------------- public void ListAvailableForClient(int clientUID) { this.reportMetadataList = new List<ReportMetadata>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,Description " + " ,RecordType " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " FROM ReportMetadata " + " WHERE RecordType = 'DF' " + " AND FieldCode not in " + " ( select FieldCode from reportmetadata where ClientUID = {0}) ", clientUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ReportMetadata _reportMetadata = new ReportMetadata(); _reportMetadata.UID = Convert.ToInt32(reader["UID"].ToString()); _reportMetadata.Description = reader["Description"].ToString(); _reportMetadata.RecordType = reader["RecordType"].ToString(); _reportMetadata.FieldCode = reader["FieldCode"].ToString(); _reportMetadata.ClientType = reader["ClientType"].ToString(); try { _reportMetadata.ClientUID = Convert.ToInt32(reader["ClientUID"]); } catch (Exception ex) { _reportMetadata.ClientUID = 0; } _reportMetadata.InformationType = reader["InformationType"].ToString(); _reportMetadata.Condition = reader["ConditionX"].ToString(); _reportMetadata.CompareWith = reader["CompareWith"].ToString(); this.reportMetadataList.Add(_reportMetadata); } } } } } // ----------------------------------------------------- // List metadata for a given client // ----------------------------------------------------- public void ListMetadataForClient(int clientUID, bool onlyEnabled = false) { this.reportMetadataList = new List<ReportMetadata>(); var enabledOnlyCriteria = ""; if (onlyEnabled) { enabledOnlyCriteria = " AND Enabled = 'Y' "; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + " UID " + " ,Description " + " ,RecordType " + " ,FieldCode " + " ,ClientType " + " ,ClientUID " + " ,InformationType " + " ,ConditionX " + " ,CompareWith " + " ,Enabled " + " FROM ReportMetadata " + " WHERE RecordType = 'CL' " + enabledOnlyCriteria + " AND ClientUID = {0} ", clientUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ReportMetadata _reportMetadata = new ReportMetadata(); _reportMetadata.UID = Convert.ToInt32(reader["UID"].ToString()); _reportMetadata.Description = reader["Description"].ToString(); _reportMetadata.RecordType = reader["RecordType"].ToString(); _reportMetadata.FieldCode = reader["FieldCode"].ToString(); _reportMetadata.ClientType = reader["ClientType"].ToString(); _reportMetadata.InformationType = reader["InformationType"].ToString(); _reportMetadata.Enabled = Convert.ToChar(reader["Enabled"]); try { _reportMetadata.ClientUID = Convert.ToInt32(reader["ClientUID"]); } catch (Exception ex) { _reportMetadata.ClientUID = 0; } _reportMetadata.InformationType = reader["InformationType"].ToString(); _reportMetadata.Condition = reader["ConditionX"].ToString(); _reportMetadata.CompareWith = reader["CompareWith"].ToString(); this.reportMetadataList.Add(_reportMetadata); } } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelBackendStatus; using FCMMySQLBusinessLibrary.Repository.RepositoryBackendStatus; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCFCMBackendStatus.Service { public class BUSFCMBackendStatus { /// <summary> /// Get last status update for a process /// </summary> public static BackendStatus ReadLast(HeaderInfo headerInfo, string processName) { var resp = RepBackendStatus.ReadLast( headerInfo, processName ); return resp; } /// <summary> /// Report current process status /// </summary> public static BackendStatus ReportStatus( HeaderInfo headerInfo, string processName, string details, string status = "ACTIVE" ) { BackendStatus backendStatus = new BackendStatus(); backendStatus.Status = status; backendStatus.ProcessName = processName; backendStatus.Details = details; backendStatus.ReportDateTime = DateTime.Now; RepBackendStatus.Insert( headerInfo, backendStatus ); return backendStatus; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.Utils; using MackkadoITFramework.ReferenceData; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; namespace fcm.Windows { public partial class UIDocumentList : Form { public DataTable elementSourceDataTable; private DocumentList documentList; public string ScreenCode; ImageList imageList16; ImageList imageList32; float tvClientDocumentListFontSize; int tvClientDocumentListIconSize; private string defaultActionDoubleClick; /// <summary> /// Constructor /// </summary> public UIDocumentList() { InitializeComponent(); ScreenCode = FCMConstant.ScreenCode.DocumentList; GetValuesFromCache(); btnSelect.Visible = false; } public UIDocumentList( DocumentList _documentList ) : this() { documentList = _documentList; documentList.documentList = new List<Document>(); // If the intention is to select from the list, do not enable actions // btnSelect.Visible = true; // Delete cms2miDelete.Enabled = false; miDelete.Enabled = false; tbbtnDelete.Enabled = false; // New cms2miNewDocument.Enabled = false; // Links tsbtnLinks.Enabled = false; miLinkDocuments.Enabled = false; // Edit/ Open tbbtnOpen.Enabled = false; cms2miEdit.Enabled = false; miEdit.Enabled = false; // Image with delete btnDelete.AllowDrop = false; defaultActionDoubleClick = "Select"; } private void UITemplateFiles_Load(object sender, EventArgs e) { // Get client list from background and load into the list // foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // Get selected client from the background // if (cbxClient.Items.Count > 0) { cbxClient.SelectedIndex = Utils.ClientIndex; } cbxClient.Enabled = false; cbxType.Text = "FCM"; cbxType.SelectedIndex = 0; miEdit.Enabled = false; miDelete.Enabled = false; // loadDocumentList(); } private void treeView_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void treeView_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) { e.Effect = DragDropEffects.Move; } override public void Refresh() { loadDocumentList(HeaderInfo.Instance); } // ------------------------------------------ // List Documents // ------------------------------------------ public void loadDocumentList(HeaderInfo headerInfo) { // Image list // imageList16 = ControllerUtils.GetImageList(); imageList16.ImageSize = new Size(16, 16); imageList32 = ControllerUtils.GetImageList(); imageList32.ImageSize = new Size(32, 32); // Binding tvFileList.ImageList = imageList16; // Clear nodes tvFileList.Nodes.Clear(); var docoList = new DocumentList(); if (cbxType.Text == "FCM") { docoList.List(); } else { docoList.ListClient(Utils.ClientID); } // Load document in the treeview // // docoList.ListInTree(tvFileList); Document root = new Document(); // root.GetRoot(headerInfo); //root = RepDocument.GetRoot(HeaderInfo.Instance); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvFileList, docoList, root); tvFileList.Nodes[0].Expand(); GetValuesFromCache(); tvFileList.Refresh(); } private void GetValuesFromCache() { // Get screen values from cache // // ---------------------------------------- // Get font size for client document list // ---------------------------------------- var userSettingsCache = new UserSettings(); userSettingsCache.FKUserID = Utils.UserID; userSettingsCache.FKScreenCode = ScreenCode; userSettingsCache.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentList; userSettingsCache.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; var stringValue = Utils.UserSettingGetCacheValue(userSettingsCache); if (string.IsNullOrEmpty(stringValue)) stringValue = "8.25"; // Convert to float tvClientDocumentListFontSize = float.Parse(stringValue); tvFileList.Font = new System.Drawing.Font("Microsoft Sans Serif", tvClientDocumentListFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // ---------------------------------------- // ---------------------------------------- // Get icon size for client document list // ---------------------------------------- userSettingsCache.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; var stringIconSize = Utils.UserSettingGetCacheValue(userSettingsCache); if (string.IsNullOrEmpty(stringIconSize)) stringIconSize = "16"; if (stringIconSize == "16") tvFileList.ImageList = imageList16; if (stringIconSize == "32") tvFileList.ImageList = imageList32; } private void loadDocumentList(object sender, EventArgs e) { indexChanged(); } private void btnDocumentDetails_Click(object sender, EventArgs e) { //EditMetadata(false); } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { indexChanged(); } // When client is changed or the client document set is changed // private void indexChanged() { // Get selected client // // Find selected item // Utils.ClientIndex = cbxClient.SelectedIndex; // Extract client id if (cbxClient.SelectedIndex >= 0) { Utils.ClientID = Utils.ClientList[cbxClient.SelectedIndex].UID; if (cbxType.Text == "CLIENT") { cbxClient.Enabled = true; } else { cbxClient.Enabled = false; } } loadDocumentList(HeaderInfo.Instance); } private void loadDirectoryToolStripMenuItem_Click(object sender, EventArgs e) { if (tvFileList.Nodes.Count <= 0) { MessageBox.Show("Root node is missing. Please contact technical support."); return; } // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; Document treeSelectedDoco = new Document(); if (tndocSelected == null) { tvFileList.SelectedNode = tvFileList.Nodes[0]; tndocSelected = tvFileList.SelectedNode; } treeSelectedDoco = (Document)tndocSelected.Tag; // Cast var templateFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.TEMPLATEFOLDER); folderBrowserDialog1.ShowNewFolderButton = false; folderBrowserDialog1.SelectedPath = templateFolder; folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop; folderBrowserDialog1.ShowDialog(); if (string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath)) return; string folderSelected = folderBrowserDialog1.SelectedPath; var resp = MessageBox.Show("Load Directory", "Are you sure? ", MessageBoxButtons.YesNo); if (resp == DialogResult.Yes) { var uioutput = new Windows.UIOutputMessage(); uioutput.Show(); var response = Utils.LoadFolder(folderSelected, uioutput, treeSelectedDoco.UID, 0, HeaderInfo.Instance); MessageBox.Show(response.Message, "Load Folder", MessageBoxButtons.OK, response.Icon); } loadDocumentList(HeaderInfo.Instance); } // ----------------------------------------------------------- // Delete Document (Logical delete) // ----------------------------------------------------------- private void deleteDocument(HeaderInfo headerInfo) { Document rm = new Document(); // rm.SetToVoid(rm.UID); // RepDocument.SetToVoid(rm.UID); BUSDocument.SetToVoid(rm.UID); loadDocumentList(headerInfo); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Dispose(); } // ------------------------------------------------ // Edit Document from Tree. Allow only Documents // ------------------------------------------------ private void EditDocument(object sender, EventArgs e) { if (! string.IsNullOrEmpty(defaultActionDoubleClick )) if (defaultActionDoubleClick == "Select") { this.btnSelect_Click(sender, e); return; } // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new Document(); if (docSelected == null) return; rm = (Document)docSelected.Tag; // Cast // Show Document Screen // UIDocumentEdit uide = new UIDocumentEdit(this, rm, docSelected); uide.ShowDialog(); docSelected.Text = rm.FileName; } private void NewDocument_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; if (docSelected == null) return; Document treeSelectedDoco = new Document(); treeSelectedDoco = (Document)docSelected.Tag; // Cast // If current tree selected item is a document // issue an error saying that only folder can hold // an item if (treeSelectedDoco.RecordType.Trim() != FCMConstant.RecordType.FOLDER) { MessageBox.Show("Only folders allow items inside."); return; } // New Document or Folder being added // var document = new Document(); // Set the parent uid as current tree selected // folder // document.ParentUID = treeSelectedDoco.UID; UIDocumentEdit uide = new UIDocumentEdit(this, document, docSelected); uide.ShowDialog(); if (uide.documentSavedSuccessfully) { int im = FCMConstant.Image.Document; if (document.RecordType == FCMConstant.RecordType.FOLDER) im = FCMConstant.Image.Folder; var treeNode = new TreeNode(document.Name, im, im); treeNode.Tag = document; treeNode.Name = document.UID.ToString(); docSelected.Nodes.Add(treeNode); } Refresh(); } private void ShowChangeImpact(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; Document treeSelectedDoco = new Document(); treeSelectedDoco = (Document)docSelected.Tag; // Cast // If current tree selected item is a document // issue an error saying that only folder can hold // an item if (treeSelectedDoco.RecordType != FCMConstant.RecordType.DOCUMENT) { MessageBox.Show("Only documents have issues/ versions."); return; } UIImpactedDocuments uid = new UIImpactedDocuments(treeSelectedDoco); uid.ShowDialog(); } private void ShowDocumentIssues(object sender, EventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; Document treeSelectedDoco = new Document(); treeSelectedDoco = (Document)docSelected.Tag; // Cast // If current tree selected item is a document // issue an error saying that only folder can hold // an item if (treeSelectedDoco.RecordType != FCMConstant.RecordType.DOCUMENT) { MessageBox.Show("Only documents have issues/ versions."); return; } UIDocumentVersion uidi = new UIDocumentVersion(treeSelectedDoco); uidi.ShowDialog(); } private void tvFileList_AfterSelect(object sender, TreeViewEventArgs e) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; Document treeSelectedDoco = new Document(); try { treeSelectedDoco = (Document)docSelected.Tag; // Cast } catch (Exception ex) { return; } txtCUID.Text = treeSelectedDoco.CUID; txtUID.Text = treeSelectedDoco.UID.ToString(); txtFileName.Text = treeSelectedDoco.FileName; txtIssueNumber.Text = treeSelectedDoco.IssueNumber.ToString(); txtLocation.Text = treeSelectedDoco.Location; txtParentUID.Text = treeSelectedDoco.ParentUID.ToString(); cbxSourceCode.Text = treeSelectedDoco.SourceCode; cbxRecordType.Text = treeSelectedDoco.RecordType; txtName.Text = treeSelectedDoco.Name; txtProjectPlan.Text = treeSelectedDoco.IsProjectPlan.ToString(); txtIndex.Text = docSelected.Index.ToString(); txtSeqNum.Text = treeSelectedDoco.SequenceNumber.ToString(); miEdit.Enabled = true; miDelete.Enabled = true; } private void tvFileList_DragDrop(object sender, DragEventArgs e) { // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; Document treeSelectedDoco = new Document(); treeSelectedDoco = (Document)tndocSelected.Tag; // Cast // Clone selected document // TreeNode tndocSelectedMoved = (TreeNode)tndocSelected.Clone(); Document moveToFolderLocation = new Document(); if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvFileList.PointToClient(new Point(e.X, e.Y)); destinationNode = tvFileList.GetNodeAt(pt); // If the destination folder is the same, just move the order of // elements if (tndocSelected.Parent == destinationNode.Parent) { if (!destinationNode.Equals(tndocSelectedMoved)) { //Insert original node to new location tvFileList.Nodes.Insert(destinationNode.Index, tndocSelectedMoved); //Remove original node tndocSelected.Remove(); } } else { // Check if destination is a folder // moveToFolderLocation = (Document)destinationNode.Tag; if (moveToFolderLocation.RecordType != FCMConstant.RecordType.FOLDER) return; if (!destinationNode.Equals(tndocSelectedMoved)) { destinationNode.Nodes.Add(tndocSelectedMoved); destinationNode.Expand(); //Remove original node tndocSelected.Remove(); } } } } // // Drag'n'Drop // private void tree_DragDrop(object sender, DragEventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { Point pt; TreeNode destinationNode; pt = tvFileList.PointToClient(new Point(e.X, e.Y)); destinationNode = tvFileList.GetNodeAt(pt); // Get parent // if (destinationNode == null) return; Document parent = new Document(); parent = (Document)destinationNode.Tag; // Get current document // if (tndocSelected == null) return; Document documentSelected = new Document(); documentSelected = (Document)tndocSelected.Tag; // If destination is a document, only allow APPENDIX // If destination is a folder, allow DOCUMENT and FOLDER // if (parent.RecordType.Trim() == FCMConstant.RecordType.FOLDER) { if (documentSelected.RecordType == FCMConstant.RecordType.DOCUMENT || documentSelected.RecordType == FCMConstant.RecordType.FOLDER) { // allow document or folder // } else return; } if (parent.RecordType.Trim() == FCMConstant.RecordType.DOCUMENT) { if (documentSelected.RecordType == FCMConstant.RecordType.APPENDIX) { // allow appendix // } else return; } //if (parent.RecordType.Trim() != Utils.RecordType.FOLDER) // return; // Remove node from source // tndocSelected.Remove(); destinationNode.Nodes.Add(tndocSelected); // Save document details // // Get current Document document = new Document(); document = (Document)tndocSelected.Tag; document.ParentUID = parent.UID; document.SequenceNumber = tndocSelected.Index; txtParentUID.Text = document.ParentUID.ToString(); txtSeqNum.Text = document.SequenceNumber.ToString(); tvFileList.SelectedNode = tndocSelected; SaveSequenceParent(HeaderInfo.Instance, document); } } // --------------------------------------- // Move document or folder down // --------------------------------------- private void picDown_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; int i = tndocSelected.Index + 1; tndocSelected.Remove(); parent.Nodes.Insert(i, tndocSelected); tvFileList.SelectedNode = tndocSelected; Document document = new Document(); document = (Document)tndocSelected.Tag; document.SequenceNumber = tndocSelected.Index; txtSeqNum.Text = document.SequenceNumber.ToString(); // Save document details // SaveSequenceParent(document); UpdateSequence(parent); } // --------------------------------------- // Move document or folder up // --------------------------------------- private void picUp_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; if (tndocSelected.Index > 0) { int i = tndocSelected.Index - 1; tndocSelected.Remove(); parent.Nodes.Insert(i, tndocSelected); tvFileList.SelectedNode = tndocSelected; // Save document details Document document = new Document(); document = (Document)tndocSelected.Tag; document.SequenceNumber = tndocSelected.Index; txtSeqNum.Text = document.SequenceNumber.ToString(); UpdateSequence(parent); } } // --------------------------------------- // Save sequence number and parent // --------------------------------------- private void SaveSequenceParent(HeaderInfo headerInfo, Document document) { // document.Save(headerInfo, FCMConstant.SaveType.UPDATE); //RepDocument.Save(headerInfo, document, FCMConstant.SaveType.UPDATE); var documentSaveRequest = new DocumentSaveRequest(); documentSaveRequest.inDocument = document; documentSaveRequest.headerInfo = HeaderInfo.Instance; documentSaveRequest.saveType = FCMConstant.SaveType.UPDATE; var resp = BUSDocument.DocumentSave(documentSaveRequest); document.UID = resp.document.UID; } private void UIDocumentList_DragDrop(object sender, DragEventArgs e) { } private void tvFileList_DragLeave(object sender, EventArgs e) { } private void btnDelete_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } // ---------------------------------------------- // Removing an element from the tree // ---------------------------------------------- private void btnDelete_DragDrop(object sender, DragEventArgs e) { TreeNode tndocSelected = tvFileList.SelectedNode; TreeNode parent = tndocSelected.Parent; tndocSelected.Remove(); // Update database with new sequence numbers // UpdateSequence(parent); // Delete element Document document = new Document(); document = (Document)tndocSelected.Tag; // document.SetToVoid(document.UID); // RepDocument.SetToVoid(document.UID); BUSDocument.SetToVoid(document.UID); tvFileList.SelectedNode = parent; } // ---------------------------------------------- // After an element has been draged away, update // remaining sequence numbers // ---------------------------------------------- private void UpdateSequence(TreeNode parent) { foreach (TreeNode node in parent.Nodes) { TreeNode parentNode = node.Parent; // Cast current document Document document = new Document(); document = (Document)node.Tag; // Get parent Document parentDoco = new Document(); parentDoco = (Document)parentNode.Tag; document.SequenceNumber = node.Index; document.ParentUID = parentDoco.UID; SaveSequenceParent(HeaderInfo.Instance, document); } } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void tvFileList_MouseHover(object sender, EventArgs e) { } private void tvFileList_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e) { //Document document = (Document)e.Node.Tag; //string info = "Document \n" + // document.CUID + "\n" + // document.UID + "\n" + // document.Name + "\n"; //toolTip1.Show(info, tvFileList, 10, 10, 20000); } private void btnSelect_Click(object sender, EventArgs e) { TreeNode tndocSelected = tvFileList.SelectedNode; if (tndocSelected != null) { if (tndocSelected.Tag.GetType().Name == "Document") { Document document = (Document)tndocSelected.Tag; documentList.documentList.Add(document); this.Dispose(); } } } /// <summary> /// Delete document selected. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DeleteDocument_Click(object sender, EventArgs e) { var resp = MessageBox.Show("Are you sure?", "Delete Document", MessageBoxButtons.YesNo); if (resp != DialogResult.Yes) { return; } // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; if (docSelected == null) return; if (docSelected.Tag.GetType().Name == "scClientDocSetDocLink") { var rm = new scClientDocSetDocLink(); rm = (scClientDocSetDocLink)docSelected.Tag; // Cast try { // rm.document.Delete( rm.document.UID ); // RepDocument.Delete(rm.document.UID); BUSDocument.DeleteDocument(rm.document.UID); } catch { // Using Logical Deletion // rm.document.SetToVoid( rm.document.UID ); // RepDocument.SetToVoid(rm.document.UID); BUSDocument.SetToVoid(rm.document.UID); } } if (docSelected.Tag.GetType().Name == "Document") { var rm = new Document(); rm = (Document)docSelected.Tag; // Cast try { // rm.Delete( rm.UID ); // RepDocument.Delete(rm.UID); BUSDocument.DeleteDocument(rm.UID); } catch { // rm.SetToVoid( rm.UID ); // RepDocument.SetToVoid(rm.UID); BUSDocument.SetToVoid(rm.UID); } } // Physically delete items // Remove item docSelected.Remove(); } private void linkToolStripMenuItem_Click(object sender, EventArgs e) { UIDocumentLink uidl = new UIDocumentLink(); uidl.Show(); } private void tvFileList_Leave(object sender, EventArgs e) { miEdit.Enabled = false; miDelete.Enabled = false; } private void tvFileList_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvFileList.SelectedNode = tvFileList.GetNodeAt( e.X, e.Y ); } } private void tsmFontSize825_Click(object sender, EventArgs e) { tvFileList.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // Save setting (Font Size to 8.25) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; userSetting.Value = "8.25"; BUSUserSetting.Save(userSetting); } private void tsmFontSize12_Click(object sender, EventArgs e) { tvFileList.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // Save setting (Font Size to 8.25) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; userSetting.Value = "12"; BUSUserSetting.Save(userSetting); } private void tsmFontSize14_Click(object sender, EventArgs e) { tvFileList.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); // Save setting (Font Size to 8.25) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.FontSize; userSetting.Value = "14"; BUSUserSetting.Save(userSetting); } private void tsmIconSize16_Click(object sender, EventArgs e) { tvFileList.ImageList = imageList16; tvFileList.Refresh(); // Save setting (Icon Size to 16) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; userSetting.Value = "16"; BUSUserSetting.Save(userSetting); } private void tsmIconSize32_Click(object sender, EventArgs e) { tvFileList.ImageList = imageList32; tvFileList.Refresh(); // Save setting (Icon Size to 32) // var userSetting = new UserSettings(); userSetting.FKUserID = Utils.UserID; userSetting.FKScreenCode = this.ScreenCode; userSetting.FKControlCode = FCMConstant.ScreenControl.TreeViewClientDocumentList; userSetting.FKPropertyCode = FCMConstant.ScreenProperty.IconSize; userSetting.Value = "32"; BUSUserSetting.Save(userSetting); } private void btnFixLocation_Click( object sender, EventArgs e ) { int documentUID = Convert.ToInt32(txtUID.Text); var drr = new DocumentReadRequest(); drr.UID = documentUID; var docread = BUSDocument.DocumentRead( drr ); if ( docread.document.RecordType == "FOLDER" ) return; var documentSaveRequest = new DocumentSaveRequest(); documentSaveRequest.inDocument = docread.document; documentSaveRequest.inDocument.Name = UIHelper.ClientDocumentUIHelper.SetDocumentName( documentSaveRequest.inDocument.SimpleFileName, documentSaveRequest.inDocument.IssueNumber.ToString(), documentSaveRequest.inDocument.CUID, documentSaveRequest.inDocument.RecordType, documentSaveRequest.inDocument.FileName); documentSaveRequest.headerInfo = HeaderInfo.Instance; documentSaveRequest.saveType = FCMConstant.SaveType.UPDATE; var resp = BUSDocument.DocumentSave( documentSaveRequest ); txtLocation.Text = resp.document.Location; txtName.Text = resp.document.Name; TreeNode tndocSelected = tvFileList.SelectedNode; if ( tndocSelected != null ) { if ( tndocSelected.Tag.GetType().Name == "Document" ) { tndocSelected.Tag = resp.document; } } } private void fixLocationToolStripMenuItem_Click( object sender, EventArgs e ) { TreeNode tndocSelected = tvFileList.SelectedNode; if ( tndocSelected != null ) { fixDocumentLocation( tndocSelected ); } } private void fixDocumentLocation(TreeNode tn) { if (tn.Tag == null) return; Document document = (Document) tn.Tag; if (document.RecordType == "FOLDER") { foreach ( TreeNode node in tn.Nodes ) { fixDocumentLocation(node); } } var drr = new DocumentReadRequest(); drr.UID = document.UID; var docread = BUSDocument.DocumentRead( drr ); var documentSaveRequest = new DocumentSaveRequest(); documentSaveRequest.inDocument = docread.document; documentSaveRequest.inDocument.Name = UIHelper.ClientDocumentUIHelper.SetDocumentName( documentSaveRequest.inDocument.SimpleFileName, documentSaveRequest.inDocument.IssueNumber.ToString(), documentSaveRequest.inDocument.CUID, documentSaveRequest.inDocument.RecordType, documentSaveRequest.inDocument.FileName); documentSaveRequest.headerInfo = HeaderInfo.Instance; documentSaveRequest.saveType = FCMConstant.SaveType.UPDATE; var resp = BUSDocument.DocumentSave( documentSaveRequest ); tn.Tag = resp.document; } private void locateInExplorerToolStripMenuItem_Click( object sender, EventArgs e ) { // // Get selected document from tree // TreeNode docSelected = tvFileList.SelectedNode; var rm = new Document(); if ( docSelected == null ) return; rm = (Document) docSelected.Tag; // Cast // Show file dialog string filePathName = Utils.getFilePathName( rm.Location, rm.FileName ); string filePath = Utils.GetPathName( rm.Location ); openFileDialog1.FileName = rm.FileName; openFileDialog1.InitialDirectory = filePath; var file = openFileDialog1.ShowDialog(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract { public class DocumentListRequest { public HeaderInfo headerInfo; public string inCondition; } public class DocumentListResponse { public List<Document> documentList; public ResponseStatus response; } public class DocumentReadRequest { public HeaderInfo headerInfo; public int UID; public string CUID; public bool retrieveVoidedDocuments; } public class DocumentReadResponse { public Document document; public ResponseStatus response; } public class DocumentSaveRequest { public HeaderInfo headerInfo; public Document inDocument; public string saveType; } public class DocumentSaveResponse { public Document document; public ResponseStatus response; } public class DocumentNewVersionRequest { public HeaderInfo headerInfo; public Document inDocument; } public class DocumentNewVersionResponse { public Document outDocument; public ResponseStatus response; } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using MackkadoITFramework.ReferenceData; using fcm.Windows; using FCMMySQLBusinessLibrary; using Utils = MackkadoITFramework.Helper.Utils; namespace fcm.Components { public partial class UCReportMetadata : UserControl { UIReportMetadata uiReportMetadata; private Form _callingFrom; public UCReportMetadata(Form callingFrom) { InitializeComponent(); _callingFrom = callingFrom; } public UCReportMetadata() { InitializeComponent(); _callingFrom = null; } public void SetUIReportInst(UIReportMetadata inst) { uiReportMetadata = inst; } private void btnNew_Click(object sender, EventArgs e) { NewEntry(0); } public void NewEntry(int clientID) { ClearFields(); // Generate new Unique ID txtUID.Text = (ReportMetadata.GetLastUID() + 1).ToString(); txtClientUID.Text = clientID.ToString(); txtRecordType.Text = "DF"; } private void ClearFields() { txtRecordType.Text = "DF"; txtFieldCode.Text = ""; txtClientUID.Text = ""; txtDescription.Text = ""; cbxType.Text = ""; txtCondition.Text = ""; txtCompareWith.Text = ""; } public void SetValues(ReportMetadata input) { txtUID.Text = input.UID.ToString(); txtRecordType.Text = input.RecordType; txtFieldCode.Text = input.FieldCode; txtClientUID.Text = input.ClientUID.ToString(); txtDescription.Text = input.Description; cbxType.Text = input.InformationType; txtCondition.Text = input.Condition; txtCompareWith.Text = input.CompareWith; checkEnabled.Checked = input.Enabled == 'Y' ? true : false; checkUseLabel.Checked = input.UseAsLabel == 'Y' ? true : false; } private void textBox2_TextChanged(object sender, EventArgs e) { } private void btnSave_Click(object sender, EventArgs e) { ReportMetadata rmd = new ReportMetadata(); rmd.UID = Convert.ToInt32( txtUID.Text ); rmd.RecordType = txtRecordType.Text; if (string.IsNullOrEmpty(txtClientUID.Text)) { rmd.ClientUID = 0; } else rmd.ClientUID = Convert.ToInt32(txtClientUID.Text); rmd.ClientType = txtClientType.Text; rmd.Description = txtDescription.Text; rmd.InformationType = cbxType.Text; rmd.FieldCode = txtFieldCode.Text; rmd.Condition = txtCondition.Text; rmd.Condition = txtCondition.Text; rmd.CompareWith = txtCompareWith.Text; rmd.Enabled = checkEnabled.Checked ? 'Y' : 'N'; rmd.UseAsLabel = checkUseLabel.Checked ? 'Y' : 'N'; rmd.Save(); MessageBox.Show("Code Type Save Successfully."); if (uiReportMetadata != null) { uiReportMetadata.Show(); } this.Visible = false; if (_callingFrom != null && _callingFrom.GetType().Name == "UIReportMetadata") { UIReportMetadata uirmd = (UIReportMetadata)_callingFrom; uirmd.refreshList(); } } private void UCReportMetadata_Load(object sender, EventArgs e) { } private void btnDelete_Click(object sender, EventArgs e) { var conf = MessageBox.Show("Are you sure?", "Delete Item", MessageBoxButtons.YesNo); if (conf != DialogResult.Yes) return; ReportMetadata rmd = new ReportMetadata(); rmd.UID = Convert.ToInt32(txtUID.Text); bool ret = rmd.Delete(); if (ret) { MessageBox.Show("Item Deleted Successfully."); } else { MessageBox.Show("Deletion was unsuccessful."); } if (uiReportMetadata != null) { uiReportMetadata.loadMetadataList(rmd.UID); } this.Visible = false; } private void cbxType_SelectedIndexChanged(object sender, EventArgs e) { if (cbxType.Text == Utils.InformationType.IMAGE) btnLocation.Enabled = true; else btnLocation.Enabled = false; } private void btnLocation_Click(object sender, EventArgs e) { // Separate the file name from the path // Store both in separate fields // // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Show file dialog var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; txtCondition.Text = fullPathFileName; } } } } <file_sep>namespace FCMMySQLBusinessLibrary.FCMUtils { public class ConnStringX { private static string connectionString; private static string connectionStringServer; private static string connectionStringLocal; private static string connectionStringMySql; public static string ConnectionStringMySql { get { if (string.IsNullOrEmpty(connectionStringMySql)) { connectionStringMySql = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.ConnectionStringMySql); } return connectionStringMySql; } set { connectionStringMySql = value; } } public static string ConnectionString { get { if (string.IsNullOrEmpty(connectionString)) { //connectionString = //"Data Source=LAPTOPHP;" + //"Initial Catalog=management;" + //"Persist Security info=false;" + //"integrated security=sspi;"; //connectionString = //"Data Source=LAPTOPHP;" + //"Initial Catalog=management;" + //"User ID=servicefcm;Password=<PASSWORD>;"; //connectionString = //"Data Source=DESKTOPHP\\SQLEXPRESS;" + //"Initial Catalog=management;" + //"User ID=service_fcm;Password=<PASSWORD>;"; // 1) Connection String // connectionString = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.ConnectionStringMySql); //"Persist Security info=false;" + //"integrated security=sspi;"; } return connectionString; } set { connectionString = value; } } public static string ConnectionStringServer { get { if (string.IsNullOrEmpty(connectionStringServer)) { connectionStringServer = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.ConnectionStringServer); } return connectionStringServer; } set { connectionStringServer = value; } } public static string ConnectionStringLocal { get { if (string.IsNullOrEmpty(connectionStringLocal)) { connectionStringLocal = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.ConnectionStringLocal); } return connectionStringLocal; } set { connectionStringLocal = value; } } private static string Toshiba { get { return "Data Source=TOSHIBAPC\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string DeanPC { get { return "Data Source=DEAN-PC\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string HPLaptop { get { return "Data Source=HPLAPTOP\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string Desktop { get { return "Data Source=DESKTOHP\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } private static string HPMINI { get { return "Data Source=HPMINI\\SQLEXPRESS;" + "Initial Catalog=management;" + "Persist Security info=false;" + "integrated security=sspi;"; } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace FCMMySQLBusinessLibrary.Model.ModelClient { public class ClientEmail { public int UID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string Type { get; set; } public string Attachment { get; set; } public string CertificateType { get; set; } } } <file_sep>using System.Configuration; using System.Web.Configuration; using System.Xml; namespace MackkadoITFramework.Utils { public class XmlConfig { public static string Read( string attribute ) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load( "C:\\Program Files\\FCM\\FCMConfig.xml" ); XmlTextReader textReader = new XmlTextReader( "C:\\Program Files\\FCM\\FCMConfig.xml" ); string constring = ""; string pickNext = "N"; while ( textReader.Read() ) { // Move to first element textReader.MoveToNextAttribute(); if ( pickNext == "Y" ) { constring = textReader.Value; constring = constring.Replace( System.Environment.NewLine, string.Empty ); constring = constring.TrimStart(); constring = constring.TrimEnd(); break; } if ( textReader.Name == attribute ) { pickNext = "Y"; } } return constring; } public static string ReadLocal( string attribute ) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load( "FCMLocalConfig.xml" ); XmlTextReader textReader = new XmlTextReader( "FCMLocalConfig.xml" ); string constring = ""; string pickNext = "N"; while ( textReader.Read() ) { // Move to first element textReader.MoveToNextAttribute(); if ( pickNext == "Y" ) { constring = textReader.Value; constring = constring.Replace( System.Environment.NewLine, string.Empty ); constring = constring.TrimStart(); constring = constring.TrimEnd(); break; } if ( textReader.Name == attribute ) { pickNext = "Y"; } } return constring; } public static string GUFCRead(string attribute) { string filelocation = "C:\\Program Files\\GUFC\\GUFCConfig.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filelocation); XmlTextReader textReader = new XmlTextReader(filelocation); string constring = ""; string pickNext = "N"; while (textReader.Read()) { // Move to first element textReader.MoveToNextAttribute(); if (pickNext == "Y") { constring = textReader.Value; constring = constring.Replace(System.Environment.NewLine, string.Empty); constring = constring.TrimStart(); constring = constring.TrimEnd(); break; } if (textReader.Name == attribute) { pickNext = "Y"; } } return constring; } } } <file_sep>namespace FCMMySQLBusinessLibrary.Model.ModelMetadata { class GlobalMetadata { // public Int32 UID; public string InformationType; public string FieldCode; public string TableName; public string FieldName; public string FilePath; private string _userID; private string _dbConnectionString; // ----------------------------------------------------- // Constructor using userId and connection string // ----------------------------------------------------- public GlobalMetadata(string UserID, string DBConnectionString) { _userID = UserID; _dbConnectionString = DBConnectionString; } } } <file_sep>delete from clientdocument where fkclientuid = 201300070; delete from clientextrainformation where fkclientuid = 201300070; delete from clientcontract where fkcompanyuid = 201300070; delete from clientdocumentset where fkclientuid = 201300070; delete from employee where fkcompanyuid = 201300070; delete from client where uid = 201300070; <file_sep>using System; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.Security; using MackkadoITFramework.Utils; using fcm.Windows.Cache; using ConnString = MackkadoITFramework.Utils.ConnString; using HeaderInfo = MackkadoITFramework.Utils.HeaderInfo; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; namespace fcm.Windows { public partial class UILogon : Form { public string connectedTo; public UILogon() { InitializeComponent(); } private void Logon_Leave(object sender, EventArgs e) { Application.Exit(); } private void Logon_Load(object sender, EventArgs e) { // Retrieve inital config information // // 1) Connection String // // ConnString.ConnectionString = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.ConnectionString); txtConnection.Text = ConnString.ConnectionStringLocal; txtServerConnection.Text = ConnString.ConnectionStringServer; int st = 0; st = ConnString.ConnectionStringLocal.IndexOf("Data Source"); if (st >= 0) { int en = ConnString.ConnectionStringLocal.IndexOf(";"); txtConnection.Text = ConnString.ConnectionStringLocal.Substring(st, en - st); int st1 = ConnString.ConnectionStringServer.IndexOf("Data Source"); int en1 = ConnString.ConnectionStringServer.IndexOf(";"); txtServerConnection.Text = ConnString.ConnectionStringServer.Substring(st1, en1 - st1); } else { st = ConnString.ConnectionStringLocal.IndexOf("Server"); if (st >= 0) { int en = ConnString.ConnectionStringLocal.IndexOf(";"); txtConnection.Text = ConnString.ConnectionStringLocal.Substring(st, en - st); int st1 = ConnString.ConnectionStringServer.IndexOf("Server"); int en1 = ConnString.ConnectionStringServer.IndexOf(";"); txtServerConnection.Text = ConnString.ConnectionStringServer.Substring(st1, en1 - st1); } } // ConnString.ConnectionString = ConnString.ConnectionStringLocal; // Get last user id //ProcessRequestCodeValues cv = new ProcessRequestCodeValues(); //cv.FKCodeType = "LASTINFO"; //cv.ID = "USERID"; //cv.Read(false); //txtUserID.Text = cv.ValueExtended; // Enable/ Disable dbs using xml // string enableLocalDB = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.EnableLocalDB); string enableServerDB = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.EnableServerDB); string defaultDB = FCMXmlConfig.Read(FCMConstant.fcmConfigXml.DefaultDB); rbLocal.Enabled = false; rbServer.Enabled = false; if (enableLocalDB == "Y") rbLocal.Enabled = true; if (enableServerDB == "Y") rbServer.Enabled = true; if (defaultDB == "Server") { if (enableServerDB == "Y") rbServer.Checked = true; } else if (enableLocalDB == "Y") rbLocal.Checked = true; // txtUserID.Focus(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Logon_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void btnLogon_Click(object sender, EventArgs e) { connectedTo = "not connected"; if (rbLocal.Checked || rbServer.Checked) {//ok } else { MessageBox.Show("Please select database."); return; } if (rbLocal.Checked) { ConnString.ConnectionString = ConnString.ConnectionStringLocal; connectedTo = "Local"; } if (rbServer.Checked) { ConnString.ConnectionString = ConnString.ConnectionStringServer; connectedTo = "Server"; } // Set framework db as the same at this stage ConnString.ConnectionStringFramework = ConnString.ConnectionString; if (string.IsNullOrEmpty(ConnString.ConnectionString)) return; try { Utils.UserID = txtUserID.Text; } catch (Exception ex) { MessageBox.Show("Error loading database. Contact system administrator. " + ex.ToString()); Application.Exit(); } // Check if user is valid var uacnew = new UserAccess(); var readuser = uacnew.Read(txtUserID.Text); if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0001) { // cool } if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0002) { MessageBox.Show("User not found."); return; } if (readuser.ReturnCode <= 000) { MessageBox.Show(readuser.Message); return; } if (string.IsNullOrWhiteSpace( uacnew.Password )) { MessageBox.Show( "User not found. Contact System Support." ); return; } var response = uacnew.AuthenticateUser(txtUserID.Text, txtPassword.Text); if (response.ReturnCode == 0001 && response.ReasonCode == 0001) { // Cool } else { // Invalid Password // ControllerUtils.ShowFCMMessage(response.UniqueCode, txtUserID.Text, response.Message, "UILogon.cs"); return; } var responseClientList = new BUSClient().ClientList(HeaderInfo.Instance); Utils.ClientList = responseClientList.clientList; string ret = LogFile.WriteToTodaysLogFile("User has logged on", Utils.UserID); if (ret != "" && ret.Length > 3 && ret.Substring(0, 5) == "Error") { MessageBox.Show(ret); Application.Exit(); } // Retrieve User Settings - Load in memory // Utils.LoadUserSettingsInCache(); LogFile.WriteToTodaysLogFile("User Settings loaded in cache", Utils.UserID); // Load reference data in cache // CachedInfo.LoadReferenceDataInCache(HeaderInfo.Instance); LogFile.WriteToTodaysLogFile("Reference Data loaded in cache", Utils.UserID); CachedInfo.LoadRelatedCodeInCache(); LogFile.WriteToTodaysLogFile("Related code loaded in cache", Utils.UserID); // Set Header Info // HeaderInfo.Instance.CurrentDateTime = System.DateTime.Today; HeaderInfo.Instance.UserID = txtUserID.Text; this.Hide(); } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); } private void txtPassword_TextChanged(object sender, EventArgs e) { } private void txtUserID_TextChanged(object sender, EventArgs e) { } } } <file_sep>DELETE FROM DocumentSetDocumentLink WHERE UID > 0; DELETE FROM ClientDocumentLink WHERE UID > 0; DELETE FROM ClientDocumentVersion WHERE UID > 0; DELETE FROM ClientDocumentIssue WHERE UID > 0; DELETE FROM ClientDocument WHERE UID > 0; DELETE FROM ClientDocumentSet WHERE UID > 0; DELETE FROM DocumentSetLink WHERE UID > 0; DELETE FROM DocumentSetDocumentLink WHERE UID > 0; DELETE FROM DocumentSetDocument WHERE UID > 0; DELETE FROM DocumentSet WHERE UID > 0; DELETE FROM DocumentLink WHERE UID > 0; DELETE FROM DocumentVersion WHERE UID > 0; DELETE FROM Document WHERE UID > 0; commit<file_sep>SET FOREIGN_KEY_CHECKS=0; CREATE TABLE Client ( UID bigint NOT NULL, Name varchar(50) NOT NULL, Address varchar(50), Phone varchar(30), Fax varchar(30), MainContactPersonName varchar(50), EmailAddress varchar(50), CreationDateTime datetime NOT NULL, UpdateDateTime datetime NOT NULL, UserIdCreatedBy char(10) NOT NULL, UserIdUpdatedBy char(10) NOT NULL, ABN varchar(20), IsVoid char(1), FK_UserID varchar(50), PRIMARY KEY (UID), INDEX Client_idx (IsVoid ASC), KEY (FK_UserID) ) ; CREATE TABLE ClientContract ( FKCompanyUID bigint, UID bigint NOT NULL, ExternalID varchar(50), StartDate datetime, EndDate datetime, UserIdCreatedBy char(10), UserIdUpdatedBy char(10), CreationDateTime datetime, UpdateDateTime datetime, Status varchar(10), Type varchar(10), PRIMARY KEY (UID), KEY (FKCompanyUID) ) ; CREATE TABLE ClientDocument ( UID bigint NOT NULL, DocumentCUID varchar(100), FKClientUID bigint, FKClientDocumentSetUID bigint, FKDocumentUID bigint, ComboIssueNumber varchar(100), ClientIssueNumber int, SourceIssueNumber int, Location varchar(200), EndDate datetime, StartDate datetime, IsVoid char(1) NOT NULL, FileName varchar(100), SequenceNumber int, SourceLocation varchar(200), SourceFileName varchar(100), Generated char(1), ParentUID bigint, RecordType char(10), IsProjectPlan char(1), DocumentType varchar(10), Status varchar(10), PRIMARY KEY (UID), INDEX ClientDocument_idx (FKClientUID ASC, FKClientDocumentSetUID ASC), INDEX ClientDocument_idx2 (FKClientUID ASC, FKDocumentUID ASC, FKClientDocumentSetUID ASC, IsVoid ASC), KEY (FKClientUID), KEY (FKClientDocumentSetUID), KEY (FKDocumentUID) ) ; CREATE TABLE ClientDocumentIssue ( UID bigint NOT NULL, FKClientDocumentUID bigint NOT NULL, ClientIssueNumber int NOT NULL, Location varchar(200), FileName varchar(100), IssueNumberText varchar(4), SourceIssueNumber int, ComboIssueNumber varchar(100) NOT NULL, DocumentCUID varchar(20), FKClientUID bigint, PRIMARY KEY (UID), KEY (FKClientDocumentUID) ) ; CREATE TABLE ClientDocumentLink ( UID bigint NOT NULL, FKParentDocumentUID bigint NOT NULL, FKChildDocumentUID bigint NOT NULL, LinkType varchar(10) NOT NULL, IsVoid char(1) NOT NULL, FKClientDocumentSetUID bigint NOT NULL, FKClientUID bigint NOT NULL, PRIMARY KEY (UID), KEY (FKParentDocumentUID), KEY (FKChildDocumentUID) ) ; CREATE TABLE ClientDocumentSet ( UID bigint NOT NULL, FKClientUID bigint, Description varchar(50), Folder varchar(200), StartDate datetime, EndDate datetime, IsVoid char(1), ClientSetID bigint, SourceFolder varchar(200), Status varchar(10), CreationDateTime datetime, UpdateDateTime date, UserIdCreatedBy char(10), UserIdUpdatedBy char(10), PRIMARY KEY (UID), KEY (FKClientUID) ) ; CREATE TABLE CodeRelated ( FKCodeTypeFrom varchar(20) NOT NULL, FKCodeValueFrom varchar(20) NOT NULL, FKCodeTypeTo varchar(20) NOT NULL, FKCodeValueTo varchar(20) NOT NULL, PRIMARY KEY (FKCodeTypeFrom, FKCodeValueFrom, FKCodeTypeTo, FKCodeValueTo), KEY (FKCodeTypeFrom, FKCodeValueFrom), KEY (FKCodeTypeTo, FKCodeValueTo) ) ; CREATE TABLE CodeType ( CodeType varchar(20) NOT NULL, Description varchar(50), ShortCodeType char(3), PRIMARY KEY (CodeType) ) ; CREATE TABLE CodeValue ( FKCodeType varchar(20) NOT NULL, ID varchar(20) NOT NULL, Description varchar(50), Abbreviation varchar(10), ValueExtended varchar(200), PRIMARY KEY (FKCodeType, ID), KEY (FKCodeType) ) ; CREATE TABLE Document ( UID bigint NOT NULL, SimpleFileName varchar(100), CUID varchar(100) NOT NULL, Name varchar(100), SequenceNumber bigint NOT NULL, IssueNumber int, Location varchar(200), Comments varchar(100), FileName varchar(100), SourceCode varchar(10), FKClientUID bigint, IsVoid char(1), ParentUID bigint NOT NULL, RecordType char(10), FileExtension varchar(10), IsProjectPlan varchar(1), DocumentType varchar(10), IssueNumberText varchar(4), Status varchar(10), CreationDateTime datetime, UpdateDateTime datetime, UserIdCreatedBy varchar(50), UserIdUpdatedBy varchar(50), PRIMARY KEY (UID), INDEX Document_idx2 (SourceCode ASC, FKClientUID ASC), INDEX IX_ClientUID_UID (FKClientUID ASC, UID ASC), INDEX IX_SourceCode_ClientID_IsVoid (SourceCode ASC, FKClientUID ASC, IsVoid ASC), INDEX IX_SourceCode_IsVoid (SourceCode ASC, IsVoid ASC) ) ; CREATE TABLE DocumentLink ( UID bigint NOT NULL, FKParentDocumentUID bigint NOT NULL, FKChildDocumentUID bigint NOT NULL, LinkType varchar(10) NOT NULL, IsVoid char(1) NOT NULL, PRIMARY KEY (UID), KEY (FKParentDocumentUID), KEY (FKChildDocumentUID) ) ; CREATE TABLE DocumentSet ( UID bigint NOT NULL, TemplateType varchar(20), TemplateFolder varchar(50), IsVoid char(1), PRIMARY KEY (UID) ) ; CREATE TABLE DocumentSetDocument ( UID bigint NOT NULL, FKDocumentUID bigint, FKDocumentSetUID bigint, Location varchar(200), IsVoid char(1), StartDate datetime, EndDate datetime, FKParentDocumentUID bigint, SequenceNumber bigint, FKParentDocumentSetUID bigint, DocumentType varchar(100), PRIMARY KEY (UID), UNIQUE INDEX IX_DocumentSetDocument (FKDocumentSetUID ASC, FKDocumentUID ASC), KEY (FKDocumentUID), KEY (FKDocumentSetUID) ) ; CREATE TABLE DocumentSetDocumentLink ( UID bigint NOT NULL, FKDocumentSetUID bigint NOT NULL, FKParentDocumentUID bigint NOT NULL, FKChildDocumentUID bigint NOT NULL, LinkType varchar(10) NOT NULL, IsVoid char(1) NOT NULL, PRIMARY KEY (UID), KEY (FKParentDocumentUID), KEY (FKChildDocumentUID) ) ; CREATE TABLE DocumentSetLink ( UID bigint NOT NULL, FKDocumentUID bigint, FKDocumentSetUID bigint, DocumentIdentifier varchar(50), Location varchar(200), IsVoid char(1), StartDate datetime, EndDate datetime, PRIMARY KEY (UID), KEY (FKDocumentUID), KEY (FKDocumentSetUID) ) ; CREATE TABLE DocumentVersion ( UID bigint, FKDocumentUID bigint NOT NULL, FKDocumentCUID varchar(20) NOT NULL, IssueNumber int NOT NULL, Location varchar(200), FileName varchar(100), CreationDateTime datetime, UpdateDateTime datetime, UserIdCreatedBy varchar(10), UserIdUpdatedBy varchar(10), IsVoid char(1), KEY (FKDocumentUID) ) ; CREATE TABLE Employee ( FKCompanyUID bigint, UID bigint NOT NULL, Name varchar(50), RoleType varchar(20), SequenceNumber int, Address varchar(100), Phone varchar(20), Fax varchar(20), EmailAddress varchar(100), IsAContact char(1), UserIdCreatedBy varchar(10), UserIdUpdatedBy varchar(10), CreationDateTime datetime, UpdateDateTime datetime, PRIMARY KEY (UID), KEY (FKCompanyUID) ) ; CREATE TABLE FCMRole ( Role varchar(50) NOT NULL, Description varchar(50) NOT NULL, PRIMARY KEY (Role) ) ; CREATE TABLE FCMUser ( UserID varchar(50) NOT NULL, Password varchar(50) NOT NULL, Salt varchar(50) NOT NULL, UserName varchar(50), LogonAttempts int, PRIMARY KEY (UserID) ) ; CREATE TABLE FCMUserRole ( UniqueID int NOT NULL, FK_UserID varchar(50) NOT NULL, FK_Role varchar(50) NOT NULL, StartDate date NOT NULL, EndDate date, IsActive char(1), IsVoid char(1), PRIMARY KEY (UniqueID), KEY (FK_Role), KEY (FK_UserID) ) ; CREATE TABLE Metadata ( UID , FieldCode , CompanyType , CompanyUID , InformationType , TableName , FieldName , FilePath , FileName ) ; CREATE TABLE RegisterofSystemDocuments ( DocumentNumber varchar(50) NOT NULL, Directory varchar(50), SubDirectory varchar(50), IssueNumber decimal(10,2), DocumentName varchar(50), Comments varchar(150), PRIMARY KEY (DocumentNumber) ) ; CREATE TABLE ReportMetadata ( UID bigint NOT NULL, RecordType varchar(2) NOT NULL, FieldCode varchar(50), Description ntext, ClientType varchar(10), ClientUID bigint, InformationType varchar(10) NOT NULL, TableNameX varchar(50), FieldNameX varchar(50), FilePathX varchar(50), FileNameX varchar(50), Condition ntext, CompareWith varchar(100), Enabled char(1), PRIMARY KEY (UID) ) ; CREATE TABLE Security ( UserID varchar(50) NOT NULL, UserName varchar(50) NOT NULL, Password varchar(50) NOT NULL, PRIMARY KEY (UserID) ) ; SET FOREIGN_KEY_CHECKS=1; ALTER TABLE Client ADD CONSTRAINT FK_Client_FCMUser FOREIGN KEY (FK_UserID) REFERENCES FCMUser (UserID) ; ALTER TABLE ClientContract ADD CONSTRAINT FK_ClientContract_Client FOREIGN KEY (FKCompanyUID) REFERENCES Client (UID) ; ALTER TABLE ClientDocument ADD CONSTRAINT FK_ClientDocument_Client FOREIGN KEY (FKClientUID) REFERENCES Client (UID) ; ALTER TABLE ClientDocument ADD CONSTRAINT FK_ClientDocument_ClientDocumentSetLink FOREIGN KEY (FKClientDocumentSetUID) REFERENCES ClientDocumentSet (UID) ; ALTER TABLE ClientDocument ADD CONSTRAINT FK_Document_1_ClientDocument_n FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ; ALTER TABLE ClientDocumentIssue ADD CONSTRAINT FK_ClientDocumentIssue_ClientDocument FOREIGN KEY (FKClientDocumentUID) REFERENCES ClientDocument (UID) ; ALTER TABLE ClientDocumentLink ADD CONSTRAINT FK_ClientDocumentLink_ClientDocument_Parent FOREIGN KEY (FKParentDocumentUID) REFERENCES ClientDocument (UID) ; ALTER TABLE ClientDocumentLink ADD CONSTRAINT FK_ClientDocumentLink_ClientDocument_child FOREIGN KEY (FKChildDocumentUID) REFERENCES ClientDocument (UID) ; ALTER TABLE ClientDocumentSet ADD CONSTRAINT FK_ClientDocumentSetLink_Client FOREIGN KEY (FKClientUID) REFERENCES Client (UID) ; ALTER TABLE CodeRelated ADD CONSTRAINT FK_Source FOREIGN KEY (FKCodeTypeFrom, FKCodeValueFrom) REFERENCES CodeValue (FKCodeType, ID) ; ALTER TABLE CodeRelated ADD CONSTRAINT FK_Destination FOREIGN KEY (FKCodeTypeTo, FKCodeValueTo) REFERENCES CodeValue (FKCodeType, ID) ; ALTER TABLE CodeValue ADD CONSTRAINT FK_CodeValue_CodeType FOREIGN KEY (FKCodeType) REFERENCES CodeType (CodeType) ; ALTER TABLE DocumentLink ADD CONSTRAINT FK_DocumentLink_Document_from FOREIGN KEY (FKParentDocumentUID) REFERENCES Document (UID) ; ALTER TABLE DocumentLink ADD CONSTRAINT FK_DocumentLink_Document_to FOREIGN KEY (FKChildDocumentUID) REFERENCES Document (UID) ; ALTER TABLE DocumentSetDocument ADD CONSTRAINT FK_Document_1_DocumentSetDocument_n FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ; ALTER TABLE DocumentSetDocument ADD CONSTRAINT FK_TemplateDocumentInstance_DocumentTemplateType FOREIGN KEY (FKDocumentSetUID) REFERENCES DocumentSet (UID) ; ALTER TABLE DocumentSetDocumentLink ADD CONSTRAINT FK_Parent_DSDL_DSD FOREIGN KEY (FKParentDocumentUID) REFERENCES DocumentSetDocument (UID) ; ALTER TABLE DocumentSetDocumentLink ADD CONSTRAINT FK_Child_DSDL_DSD FOREIGN KEY (FKChildDocumentUID) REFERENCES DocumentSetDocument (UID) ; ALTER TABLE DocumentSetLink ADD CONSTRAINT FK_DocumentSetLink_Document FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ; ALTER TABLE DocumentSetLink ADD CONSTRAINT FK_TemplateDocumentInstance_DocumentTemplateType FOREIGN KEY (FKDocumentSetUID) REFERENCES DocumentSet (UID) ; ALTER TABLE DocumentVersion ADD CONSTRAINT FK_DocumentIssue_Document FOREIGN KEY (FKDocumentUID) REFERENCES Document (UID) ; ALTER TABLE Employee ADD CONSTRAINT FK_Employee_Client FOREIGN KEY (FKCompanyUID) REFERENCES Client (UID) ; ALTER TABLE FCMUserRole ADD CONSTRAINT FK_FCMUserRole_FCMRole FOREIGN KEY (FK_Role) REFERENCES FCMRole (Role) ; ALTER TABLE FCMUserRole ADD CONSTRAINT FK_FCMUserRole_FCMUser FOREIGN KEY (FK_UserID) REFERENCES FCMUser (UserID) ; <file_sep>using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public class BUSClientDocumentGeneration { public static ResponseStatus UpdateLocation(int clientID, int clientDocumentSetUID) { var response = new ResponseStatus(); response = DocumentGeneration.UpdateDestinationFolder(clientID, clientDocumentSetUID); return response; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; namespace fcm.Windows { public partial class UIDocumentLink : Form { DocumentList docoList; int SelectedParentDocumentUID; public UIDocumentLink() { InitializeComponent(); } private void UIDocumentLink_Load(object sender, EventArgs e) { PopulateDocumentCombo('N'); cbxLinkType.Items.Add(FCMConstant.DocumentLinkType.PROJECTPLAN); cbxLinkType.Items.Add(FCMConstant.DocumentLinkType.APPENDIX); removeDocumentToolStripMenuItem.Enabled = false; selectDocumentToolStripMenuItem.Enabled = false; } private void PopulateDocumentCombo(char ProjectPlan) { docoList = new DocumentList(); if (ProjectPlan == 'Y') docoList.ListProjectPlans(); else docoList.List(); cbxDocument.Items.Clear(); cbxDocument.SelectedText = ""; int i = 0; foreach (Document doco in docoList.documentList) { string item = doco.UID + ";" + doco.CUID + ";" + doco.Name; cbxDocument.Items.Add(item); if (i == 0) { cbxDocument.ResetText(); cbxDocument.SelectedText = item; } i++; } cbxLinkType.Text = FCMConstant.DocumentLinkType.PROJECTPLAN; ParentHasChanged(); loadDocumentList(); } private void cbxDocument_SelectedIndexChanged(object sender, EventArgs e) { ParentHasChanged(); } private void ParentHasChanged() { // Get selected document // List documents connected to selected document // ... for selected link type var x = cbxDocument.Text; string[] doco = x.Split(';'); Document document = new Document(); document.UID = Convert.ToInt32(doco[0]); SelectedParentDocumentUID = document.UID; DocumentLinkList list = DocumentLinkList.ListRelatedDocuments(document.UID, cbxLinkType.Text); loadLinkedDocuments(document); } // ------------------------------------------ // List Documents // ------------------------------------------ public void loadDocumentList() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvListOfDocuments.ImageList = imageList; // Clear nodes tvListOfDocuments.Nodes.Clear(); var docoList = new DocumentList(); docoList.List(); // Load document in the treeview // // docoList.ListInTree(tvListOfDocuments); Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false, 0, "ROOT"); // Using Business Layer root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvListOfDocuments, docoList, root); tvListOfDocuments.ExpandAll(); } // ------------------------------------------ // List Documents // ------------------------------------------ public void loadLinkedDocuments(Document document) { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvLinkedDocuments.ImageList = imageList; // Clear nodes tvLinkedDocuments.Nodes.Clear(); var docoList = DocumentLinkList.ListRelatedDocuments(document.UID, cbxLinkType.Text); // Load document in the treeview // // docoList.ListInTree(tvLinkedDocuments); Document root = new Document(); root.CUID = document.CUID; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = document.UID; // root.Read(); // root = RepDocument.Read(false, document.UID, document.CUID); // Using Business Layer var documentReadRequest = new DocumentReadRequest(); documentReadRequest.UID = document.UID; documentReadRequest.CUID = document.CUID; documentReadRequest.retrieveVoidedDocuments = false; var docreadresp = BUSDocument.DocumentRead(documentReadRequest); if (docreadresp.response.ReturnCode == 0001) { // all good } else { MessageBox.Show(docreadresp.response.Message); return; } root = docreadresp.document; // DocumentLinkList.ListInTree(tvLinkedDocuments, docoList, root); tvLinkedDocuments.ExpandAll(); } private void checkProjectPlans_CheckedChanged(object sender, EventArgs e) { char projectplan = 'N'; if (checkProjectPlans.Checked) projectplan = 'Y'; PopulateDocumentCombo(projectplan); } private void tvListOfDocuments_DoubleClick(object sender, EventArgs e) { AddSelectedDocument(); } private void AddSelectedDocument() { TreeNode tn = new TreeNode(); tn = tvListOfDocuments.SelectedNode; TreeNode clone = new TreeNode(); clone = (TreeNode)tn.Clone(); tvLinkedDocuments.Nodes[0].Nodes.Add(clone); } // ------------------------------------------------ // Save details // ------------------------------------------------ private void tsbSave_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; foreach (TreeNode tn in tvLinkedDocuments.Nodes[0].Nodes) { var nodeType = tn.Tag.GetType().Name; if (nodeType == "DocumentLink") { DocumentLink doc = new DocumentLink(); doc = (DocumentLink)tn.Tag; DocumentLink.LinkDocuments( SelectedParentDocumentUID, doc.documentTo.UID, cbxLinkType.Text); } if (nodeType == "Document") { Document doc = new Document(); doc = (Document)tn.Tag; DocumentLink.LinkDocuments( SelectedParentDocumentUID, doc.UID, cbxLinkType.Text); } } Cursor.Current = Cursors.Arrow; MessageBox.Show("Saved successfully."); } private void tvLinkedDocuments_DoubleClick(object sender, EventArgs e) { RemoveDocument(); } // Remove document from selected list // private void RemoveDocument() { TreeNode tn = new TreeNode(); tn = tvLinkedDocuments.SelectedNode; var nodeType = tn.Tag.GetType().Name; if (nodeType == "Document") { Document doc = new Document(); doc = (Document)tn.Tag; DocumentLink dl = new DocumentLink(); // Logically delete the record if the record is commited. if (dl.Read(SelectedParentDocumentUID, doc.UID, cbxLinkType.Text)) dl.Delete(dl.UID); tn.Remove(); } if (nodeType == "DocumentLink") { DocumentLink doc = new DocumentLink(); doc = (DocumentLink)tn.Tag; DocumentLink dl = new DocumentLink(); // Logically delete the record if the record is commited. if (dl.Read(SelectedParentDocumentUID, doc.documentTo.UID, cbxLinkType.Text)) dl.Delete(dl.UID); tn.Remove(); } } private void tsbExit_Click(object sender, EventArgs e) { this.Close(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void cbxLinkType_SelectedIndexChanged(object sender, EventArgs e) { ParentHasChanged(); } private void selectDocumentToolStripMenuItem_Click(object sender, EventArgs e) { AddSelectedDocument(); } private void tvLinkedDocuments_AfterSelect(object sender, TreeViewEventArgs e) { removeDocumentToolStripMenuItem.Enabled = true; } private void tvListOfDocuments_AfterSelect(object sender, TreeViewEventArgs e) { selectDocumentToolStripMenuItem.Enabled = true; } private void tvLinkedDocuments_Leave(object sender, EventArgs e) { removeDocumentToolStripMenuItem.Enabled = false; } private void tvListOfDocuments_Leave(object sender, EventArgs e) { selectDocumentToolStripMenuItem.Enabled = false; } private void removeDocumentToolStripMenuItem_Click(object sender, EventArgs e) { RemoveDocument(); } private void tvLinkedDocuments_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvLinkedDocuments.SelectedNode = tvLinkedDocuments.GetNodeAt( e.X, e.Y ); } } private void tvListOfDocuments_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvListOfDocuments.SelectedNode = tvListOfDocuments.GetNodeAt( e.X, e.Y ); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Model.ModelClient; using System.IO; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using MackkadoITFramework.Utils; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Repository; using MackkadoITFramework.ErrorHandling; namespace fcm.Windows { public partial class UIImpactedDocuments : Form { public DataTable elementSourceDataTable; public DataTable clientMetadataTable; Document document; Client clientDocument; ImageList imageList; ImageList imageList32; public UIImpactedDocuments() { InitializeComponent(); document = new Document(); // Image list // imageList = new ImageList(); imageList = ControllerUtils.GetImageList(); imageList.ImageSize = new Size(16, 16); // Binding tvDocumentList.ImageList = imageList; // Image list 32 // imageList32 = new ImageList(); imageList32 = ControllerUtils.GetImageList(); imageList32.ImageSize = new Size(32, 32); // Binding // tvDocumentList.ImageList = imageList32; } public UIImpactedDocuments(Document iDocument) : this() { document = new Document(); document = iDocument; txtDocumentID.Text = document.CUID; txtDocumentName.Text = document.Name; ListImpact(iDocument); btnDocument.Enabled = false; btnImpact.Enabled = false; } // -------------------------------------------- // Document Click // -------------------------------------------- private void btnDocument_Click(object sender, EventArgs e) { loadDocumentList(); } /// <summary> /// Load documents for a Client Document Set /// </summary> private void loadDocumentList(int w=16, int h=16) { if (elementSourceDataTable != null) { elementSourceDataTable.Clear(); } DocumentList dl = new DocumentList(); UIDocumentList uidl = new UIDocumentList(dl); uidl.ShowDialog(); if (dl == null) return; if (dl.documentList == null) return; if (dl.documentList.Count > 0) { document = dl.documentList[0]; txtDocumentID.Text = document.CUID; txtDocumentName.Text = document.Name; } ListImpact(document,w,h); } private void ListImpact(Document document, int h=16, int w=16) { // Clear nodes tvDocumentList.Nodes.Clear(); var impacted = new ClientDocument(); // impacted.ListImpacted(document); BUSClientDocument.ListImpacted( impacted, document ); TreeNode rootNode = new TreeNode("Impacted List", FCMConstant.Image.Folder, FCMConstant.Image.Folder); rootNode.Name = "Impacted List"; tvDocumentList.Nodes.Add(rootNode); foreach (var doco in impacted.clientDocSetDocLink) { // string clientName = Client.ReadFieldClient(DBFieldName.Client.Name, doco.clientDocument.FKClientUID); var clientField = new Client(HeaderInfo.Instance); // string clientName = clientField.ReadFieldClient(DBFieldName.Client.Name, doco.clientDocument.FKClientUID); var readFieldClientResponse = new BUSClient().ReadFieldClient( new ReadFieldRequest() {clientUID = doco.clientDocument.FKClientUID, field = FCMDBFieldName.Client.Name, headerInfo = HeaderInfo.Instance }); string clientName = readFieldClientResponse.fieldContents; // 1) Add client to tree // // 1.1) Find out current contract information // 1.2) Display document version // 1.3) Check if document has been further updated var response = BUSClientContract.GetValidContractOnDate(doco.clientDocument.FKClientUID, System.DateTime.Today); // Successful ClientContract clientContractValid = new ClientContract(); string validContract = @";Contract=N/A"; if (response.ReturnCode == 0001 && response.ReasonCode == 0001) { clientContractValid = (ClientContract)response.Contents; validContract = ";Contract=Valid"; } int imageClient = Utils.GetClientLogoImageSeqNum(doco.clientDocument.FKClientUID); string NameToDisplay = clientName + " ==> " + validContract + "; Version: " + doco.clientDocument.ClientIssueNumber.ToString(); TreeNode clientNode = new TreeNode(NameToDisplay, imageClient, imageClient); clientNode.Name = doco.clientDocument.FKClientUID.ToString(); clientNode.Tag = doco; rootNode.Nodes.Add(clientNode); // Add Client Document Set to tree // TreeNode clientDocumentSetNode = new TreeNode("Set "+doco.clientDocument.FKClientDocumentSetUID.ToString(), FCMConstant.Image.Folder, FCMConstant.Image.Folder); clientDocumentSetNode.Name = "Set " + doco.clientDocument.FKClientDocumentSetUID.ToString("0000"); clientDocumentSetNode.Tag = doco; clientNode.Nodes.Add(clientDocumentSetNode); // Add document to tree // int image = Utils.GetFileImage(doco.clientDocument.SourceFilePresent, doco.clientDocument.DestinationFilePresent, doco.clientDocument.DocumentType); TreeNode documentNode = new TreeNode(txtDocumentName.Text, image, image); documentNode.Name = txtDocumentName.Text; documentNode.Tag = doco; clientDocumentSetNode.Nodes.Add(documentNode); } if (tvDocumentList.Nodes.Count > 0) tvDocumentList.Nodes[0].Expand(); } private void btnEdit_Click(object sender, EventArgs e) { // // Get selected document from tree // TreeNode tndocSelected = tvDocumentList.SelectedNode; if (tndocSelected == null) return; var cds = new scClientDocSetDocLink(); cds = (scClientDocSetDocLink)tndocSelected.Tag; var Location = cds.clientDocument.Location; var FileName = cds.clientDocument.FileName; var FileType = cds.clientDocument.DocumentType; //string filePathName = // Utils.getFilePathName(Location, // FileName); //if (!string.IsNullOrEmpty(filePathName)) //{ // WordDocumentTasks.OpenDocument(filePathName); //} //else //{ // MessageBox.Show("Document is empty."); //} Utils.OpenDocument(Location, FileName, FileType, vkReadOnly: false); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void UIImpactedDocuments_Load(object sender, EventArgs e) { } private void btnImpact_Click(object sender, EventArgs e) { txtDocumentID.Text = document.CUID; txtDocumentName.Text = document.Name; ListImpact(document); btnDocument.Enabled = false; btnImpact.Enabled = false; } private void tvDocumentList_MouseDown( object sender, MouseEventArgs e ) { if (e.Button == MouseButtons.Right) { tvDocumentList.SelectedNode = tvDocumentList.GetNodeAt( e.X, e.Y ); } } private void tvDocumentList_AfterSelect(object sender, TreeViewEventArgs e) { } private void tsmIconSize16_Click(object sender, EventArgs e) { tvDocumentList.ImageList = imageList; tvDocumentList.Refresh(); } private void tsmIconSize32_Click(object sender, EventArgs e) { tvDocumentList.ImageList = imageList32; tvDocumentList.Refresh(); } private void tsmIcon16_Click(object sender, EventArgs e) { tvDocumentList.ImageList = imageList; tvDocumentList.Refresh(); } private void tsmIconSize32x_Click(object sender, EventArgs e) { tvDocumentList.ImageList = imageList32; tvDocumentList.Refresh(); } private void tsmFontSize825_Click(object sender, EventArgs e) { tvDocumentList.Font = new System.Drawing.Font("Microsoft Sans Serif", 825F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); } private void tsmFontSize12_Click(object sender, EventArgs e) { tvDocumentList.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); } private void sendEmailToolStripMenuItem_Click(object sender, EventArgs e) { var answer = MessageBox.Show("Would you like to send emails to impacted clients?", "Send email", MessageBoxButtons.YesNo); if (answer != DialogResult.Yes) { return; } Cursor.Current = Cursors.WaitCursor; List<Client> listOfClients = new List<Client>(); // Get file name // string filePathName = Utils.getFilePathName( document.Location, document.FileName); if (!File.Exists(filePathName)) { MessageBox.Show("File not found. " + filePathName); return; } // Select client to send email and show before send // var impacted = new ClientDocument(); // impacted.ListImpacted(document); BUSClientDocument.ListImpacted(impacted, document); foreach (var doco in impacted.clientDocSetDocLink) { var response = BUSClientContract.GetValidContractOnDate(doco.clientDocument.FKClientUID, System.DateTime.Today); if (response.ReturnCode == 0001 && response.ReasonCode == 0001) { //Client client = new Client(HeaderInfo.Instance); //client.UID = doco.clientDocument.FKClientUID; ClientReadRequest crr = new ClientReadRequest(); crr.clientUID = doco.clientDocument.FKClientUID; crr.headerInfo = HeaderInfo.Instance; var busClientResponse = BUSClient.ClientRead( crr ); //var busClientResponse = client.Read(); listOfClients.Add(busClientResponse.client); } } if (listOfClients.Count <= 0) return; string subject = "Document updated"; string body = "The document "+document.Name+" has been updated."; var resp = SendEmailToGroup( clientList: listOfClients, iSubject: subject, iBody: body, Attachment: filePathName); MessageBox.Show(resp.Message); Cursor.Current = Cursors.Arrow; } /// <summary> /// Send email to group /// </summary> /// <param name="clientList"></param> public static ResponseStatus SendEmailToGroup( List<Client> clientList, string iSubject, string iBody, string Attachment) { ResponseStatus resp = new ResponseStatus(); // FCM Dropbox // <EMAIL> string from = "<EMAIL>"; string password = "<PASSWORD>"; foreach (var client in clientList) { resp = FCMEmail.SendEmail( iPassword: <PASSWORD>, iFrom: from, iRecipient: client.EmailAddress, iSubject: iSubject, iBody: iBody, iAttachmentLocation: Attachment); if (resp.ReturnCode < 0001) { break; } } return resp; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FCMMySQLBusinessLibrary.Repository { public static class FCMDBFieldName { /// <summary> /// Database fields /// </summary> public struct Client { public const string UID = "UID"; public const string ABN = "ABN"; public const string Name = "Name"; public const string LegalName = "LegalName"; public const string Address = "Address"; public const string Phone = "Phone"; public const string Fax = "Fax"; public const string Mobile = "Mobile"; public const string Logo1Location = "Logo1Location"; public const string Logo2Location = "Logo2Location"; public const string Logo3Location = "Logo3Location"; public const string EmailAddress = "EmailAddress"; public const string MainContactPersonName = "MainContactPersonName"; public const string IsVoid = "IsVoid"; public const string FKUserID = "FKUserID"; public const string FKDocumentSetUID = "FKDocumentSetUID"; public const string DocSetUIDDisplay = "DocSetUIDDisplay"; public const string DisplayLogo = "DisplayLogo"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; public const string RecordVersion = "recordVersion"; } /// <summary> /// Database fields /// </summary> public struct ClientContract { public const string FKCompanyUID = "FKCompanyUID"; public const string UID = "UID"; public const string ExternalID = "ExternalID"; public const string Status = "Status"; public const string Type = "Type"; public const string StartDate = "StartDate"; public const string EndDate = "EndDate"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; } /// <summary> /// Database fields /// </summary> public struct ClientExtraInformation { public const string UID = "UID"; public const string FKClientUID = "FKClientUID"; public const string DateToEnterOnPolicies = "DateToEnterOnPolicies"; public const string ScopeOfServices = "ScopeOfServices"; public const string ActionPlanDate = "ActionPlanDate"; public const string CertificationTargetDate = "CertificationTargetDate"; public const string TimeTrading = "TimeTrading"; public const string RegionsOfOperation = "RegionsOfOperation"; public const string OperationalMeetingsFrequency = "OperationalMeetingsFrequency"; public const string ProjectMeetingsFrequency = "ProjectMeetingsFrequency"; // public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; public const string RecordVersion = "RecordVersion"; public const string IsVoid = "IsVoid"; } /// <summary> /// Database fields /// </summary> public struct Document { public const string UID = "UID"; public const string SimpleFileName = "SimpleFileName"; public const string CUID = "CUID"; public const string Name = "Name"; public const string DisplayName = "DisplayName"; public const string SequenceNumber = "SequenceNumber"; public const string IssueNumber = "IssueNumber"; public const string Location = "Location"; public const string Comments = "Comments"; public const string FileName = "FileName"; public const string SourceCode = "SourceCode"; public const string FKClientUID = "FKClientUID"; public const string IsVoid = "IsVoid"; public const string ParentUID = "ParentUID"; public const string RecordType = "RecordType"; public const string FileExtension = "FileExtension"; public const string IsProjectPlan = "IsProjectPlan"; public const string DocumentType = "DocumentType"; public const string Status = "Status"; public const string RecordVersion = "RecordVersion"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; } /// <summary> /// Database fields /// </summary> public struct ClientDocument { public const string UID = "UID"; public const string DocumentCUID = "DocumentCUID"; public const string FKClientUID = "FKClientUID"; public const string FKClientDocumentSetUID = "FKClientDocumentSetUID"; public const string FKDocumentUID = "FKDocumentUID"; public const string SourceLocation = "SourceLocation"; public const string SourceFileName = "SourceFileName"; public const string Location = "Location"; public const string FileName = "FileName"; public const string SourceIssueNumber = "SourceIssueNumber"; public const string ClientIssueNumber = "ClientIssueNumber"; public const string SequenceNumber = "SequenceNumber"; public const string Generated = "xGenerated"; public const string StartDate = "StartDate"; public const string EndDate = "EndDate"; public const string RecordType = "RecordType"; public const string ParentUID = "ParentUID"; public const string IsProjectPlan = "IsProjectPlan"; public const string DocumentType = "DocumentType"; public const string ComboIssueNumber = "ComboIssueNumber"; public const string IsVoid = "IsVoid"; public const string IsLocked = "IsLocked"; public const string IsRoot = "IsRoot"; public const string IsFolder = "IsFolder"; public const string GenerationMessage = "GenerationMessage"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; } /// <summary> /// Database fields /// </summary> public struct BackendStatus { public const string UID = "UID"; public const string ProcessName = "ProcessName"; public const string Status = "Status"; public const string ReportDateTime = "ReportDateTime"; public const string Details = "Details"; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelDocument; using MackkadoITFramework.APIDocument; using FCMMySQLBusinessLibrary.FCMUtils; namespace fcm.Windows { public partial class UIDocumentVersion : Form { public DataTable elementSourceDataTable; private Document _document; public UIDocumentVersion(Document document) { InitializeComponent(); _document = document; var UID = new DataColumn("UID", typeof(String)); var FKDocumentUID = new DataColumn("FKDocumentUID", typeof(String)); var FKDocumentCUID = new DataColumn("FKDocumentCUID", typeof(String)); var IssueNumber = new DataColumn("IssueNumber", typeof(String)); var Location = new DataColumn("Location", typeof(String)); var FileName = new DataColumn("FileName", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(IssueNumber); elementSourceDataTable.Columns.Add(FileName); elementSourceDataTable.Columns.Add(Location); elementSourceDataTable.Columns.Add(UID); elementSourceDataTable.Columns.Add(FKDocumentUID); elementSourceDataTable.Columns.Add(FKDocumentCUID); dgvIssueList.DataSource = elementSourceDataTable; txtDocumentID.Text = document.CUID; txtDocumentName.Text = document.Name; } private void UIDocumentIssue_Load(object sender, EventArgs e) { loadDocumentList(); } // // List of issues // public void loadDocumentList() { elementSourceDataTable.Clear(); var docoList = DocumentVersion.List(_document); foreach (DocumentVersion doco in docoList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["UID"] = doco.UID; elementRow["FileName"] = doco.FileName; elementRow["FKDocumentCUID"] = doco.FKDocumentCUID; elementRow["FKDocumentUID"] = doco.FKDocumentUID; elementRow["IssueNumber"] = doco.IssueNumber; elementRow["Location"] = doco.Location; elementSourceDataTable.Rows.Add(elementRow); } } private void btnOk_Click(object sender, EventArgs e) { this.Close(); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void btnView_Click(object sender, EventArgs e) { if (dgvIssueList.SelectedRows.Count <= 0) return; var selectedRow = dgvIssueList.SelectedRows; var Location = selectedRow[0].Cells["Location"].Value.ToString(); var FileName = selectedRow[0].Cells["FileName"].Value.ToString(); string filePathName = Utils.getFilePathName(Location, FileName); if (!string.IsNullOrEmpty(filePathName)) { WordDocumentTasks.OpenDocument(filePathName, vkReadOnly: true); } else { MessageBox.Show(@"Document is empty."); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void dgvIssueList_CellMouseDown( object sender, DataGridViewCellMouseEventArgs e ) { if (e.ColumnIndex >= 0 && e.RowIndex >= 0) { dgvIssueList.CurrentCell = dgvIssueList.Rows[e.RowIndex].Cells[e.ColumnIndex]; } } private void tsmCompare_Click(object sender, EventArgs e) { // get current document // var currentLocation = _document.Location; var currentFileName = _document.FileName; var currentFileType = _document.DocumentType; // Get selected document from tree // //if (dgvDocumentList.SelectedRows.Count <= 0) // return; if (dgvIssueList.SelectedRows.Count <= 0) return; var selectedRow = dgvIssueList.SelectedRows; var selectedLocation = ""; var selectedFileName = ""; var selectedFileType = ""; foreach (var row in selectedRow) { DataGridViewRow dgvr = (DataGridViewRow)row; selectedLocation = dgvr.Cells["Location"].Value.ToString(); selectedFileName = dgvr.Cells["FileName"].Value.ToString(); selectedFileType = MackkadoITFramework.Helper.Utils.DocumentType.WORD; // dgvr.Cells["Location"].Value.ToString(); break; } string source = Utils.getFilePathName(currentLocation, currentFileName); string destination = Utils.getFilePathName(selectedLocation, selectedFileName); if (string.IsNullOrEmpty(source)) { MessageBox.Show("Source file is empty."); return; } if (string.IsNullOrEmpty(destination)) { MessageBox.Show("Destination file is empty."); return; } Utils.CompareDocuments(source, destination, MackkadoITFramework.Helper.Utils.DocumentType.WORD); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIClientDocumentSet : Form { public DataTable elementSourceDataTable; private int documentSetID; public UIClientDocumentSet() { InitializeComponent(); CreateDataTable(); } public UIClientDocumentSet(string ClientID) { InitializeComponent(); CreateDataTable(); cbxClient.Enabled = false; } public void CreateDataTable() { // // Create datatable // var CUID = new DataColumn("CUID", typeof(String)); var Name = new DataColumn("Name", typeof(String)); var Directory = new DataColumn("Directory", typeof(String)); var Subdirectory = new DataColumn("Subdirectory", typeof(String)); var SequenceNumber = new DataColumn("SequenceNumber", typeof(Int32)); var LatestIssueNumber = new DataColumn("LatestIssueNumber", typeof(String)); var LatestIssueLocation = new DataColumn("LatestIssueLocation", typeof(String)); var Comments = new DataColumn("Comments", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(CUID); elementSourceDataTable.Columns.Add(Name); elementSourceDataTable.Columns.Add(Directory); elementSourceDataTable.Columns.Add(Subdirectory); elementSourceDataTable.Columns.Add(SequenceNumber); elementSourceDataTable.Columns.Add(LatestIssueNumber); elementSourceDataTable.Columns.Add(LatestIssueLocation); dgvDocumentList.DataSource = elementSourceDataTable; } private void UIClientDocumentSet_Load(object sender, EventArgs e) { foreach (Client c in Utils.ClientList.clientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } // Retrieve current client from background // cbxClient.SelectedIndex = Utils.ClientIndex; // List document sets for a client // ClientDocumentSetList cdsl = new ClientDocumentSetList(); cdsl.List(Utils.ClientID); foreach (ClientDocumentSet cds in cdsl.documentSetList) { cbxDocumentSet.Items.Add(cds.UID + "; "+ cds.Description); } // Retrieve document set for a client // ClientDocumentSet clientDocSet = new ClientDocumentSet(); documentSetID = 1; clientDocSet.Get(Utils.ClientID, documentSetID); cbxDocumentSet.SelectedIndex = 0; // If this is the first time the client is selected, this program // will copy all documents to a client before displaying the list. // The list will always come from the client // The intention is to use the client type to get the correct // Document set before copying the documents to the client // loadDocumentList(); } // // List companies // private void loadDocumentList() { elementSourceDataTable.Clear(); // Check if the client has a list of documents for the template // ClientDocumentSet cds = new ClientDocumentSet(); if (cds.Get(Utils.ClientID, documentSetID)) { // Just proceed to list } else { // Copy the recors to the client first } var docoList = new DocumentList(); docoList.List(); foreach (Document doco in docoList.documentList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["CUID"] = doco.CUID; elementRow["Name"] = doco.Name; elementRow["Directory"] = doco.Directory; elementRow["Subdirectory"] = doco.Subdirectory; elementRow["SequenceNumber"] = doco.SequenceNumber; elementRow["LatestIssueNumber"] = doco.LatestIssueNumber; elementRow["LatestIssueLocation"] = doco.LatestIssueLocation; elementSourceDataTable.Rows.Add(elementRow); } } private void removeToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var selRows in dgvDocumentList.SelectedRows) { dgvDocumentList.Rows.Remove((DataGridViewRow)selRows); } } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { Utils.ClientID = Utils.ClientList.clientList[cbxClient.SelectedIndex].UID; Utils.ClientIndex = cbxClient.SelectedIndex; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { Utils.ClientIndex = cbxClient.SelectedIndex; Utils.ClientID = Utils.ClientList.clientList[Utils.ClientIndex].UID; string [] part = cbxDocumentSet.SelectedItem.ToString().Split(';'); documentSetID = Convert.ToInt32( part[0] ); } private void groupBox1_Enter(object sender, EventArgs e) { } private void btnGenerateProjectFiles_Click(object sender, EventArgs e) { UIClientMetadata ucm = new UIClientMetadata(); ucm.Show(); } // ----------------------------------------------------- // This method replicates folders and files for a given // folder structure (source and destination) // ----------------------------------------------------- private void ReplicateFolderFilesReplace() { Cursor.Current = Cursors.WaitCursor; Word.ApplicationClass vkWordApp = new Word.ApplicationClass(); // The source comes from the document set // The destination is selected and stored also // string sourceFolder = txtSourceFolder.Text; string destinationFolder = txtDestinationFolder.Text; if (sourceFolder == "" || destinationFolder == "") { return; } var ts = new List<WordDocumentTasks.TagStructure>(); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<XX>>", TagValue = "VV1" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<YY>>", TagValue = "VV2" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<VV>>", TagValue = "VV3" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientNAME>>", TagValue = "Client 2" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientADDRESS>>", TagValue = "St Street" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientEMAILADDRESS>>", TagValue = "Email@com" }); ts.Add(new WordDocumentTasks.TagStructure() { Tag = "<<ClientPHONE>>", TagValue = "09393893" }); WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder); WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp); Cursor.Current = Cursors.Arrow; MessageBox.Show("Project Successfully Created."); } private void btnSelectDestination_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } } } <file_sep>using System; using System.Collections; using System.IO; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows.Forms; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Interfaces; using MackkadoITFramework.Utils; //using Microsoft.Office.Core; namespace MackkadoITFramework.APIDocument { public class WordDocumentTasks { private int row; // --------------------------------------------- // Open Document // --------------------------------------------- public static ResponseStatus OpenDocument(object fromFileName, object vkReadOnly, bool isFromWeb=false) { if ( !isFromWeb ) if ( !File.Exists( (string) fromFileName ) ) { ResponseStatus rserror = new ResponseStatus( MessageType.Error ); rserror.Message = "File not found. " + fromFileName; MessageBox.Show( rserror.Message ); return rserror; } Word.Application vkWordApp = new Word.Application(); // object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application visible vkWordApp.Visible = true; vkWordApp.Activate(); // Let's open the document Word.Document vkMyDoc = vkWordApp.Documents.Open( ref fromFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); return new ResponseStatus(); } // --------------------------------------------- // Copy Documents // --------------------------------------------- public static object CopyDocumentReplaceContents( object fromFileName, object destinationFileName, List<WordDocumentTasks.TagStructure> tag ) { Word.Application vkWordApp = new Word.Application(); object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application visible vkWordApp.Visible = true; vkWordApp.Activate(); // Let's open the document Word.Document vkMyDoc = vkWordApp.Documents.Open( ref fromFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); // Let's create a new document Word.Document vkNewDoc = vkWordApp.Documents.Add( ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); // Select and Copy from the original document vkMyDoc.Select(); vkWordApp.Selection.Copy(); // Paste into new document as unformatted text vkNewDoc.Select(); vkWordApp.Selection.PasteSpecial(ref vkMissing, ref vkFalse, ref vkMissing, ref vkFalse, ref vkDynamic, ref vkMissing, ref vkMissing); // Save the new document vkNewDoc.SaveAs(ref saveFile, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing); // Copy elements // FromString => toString // // underdevelopment // vkNewDoc.Select(); foreach (var t in tag) { FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); } vkNewDoc.Save(); // close the new document vkNewDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing); // close the original document vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing); // close word application vkWordApp.Quit(ref vkFalse, ref vkMissing, ref vkMissing); return saveFile; } // --------------------------------------------- // // --------------------------------------------- /// <summary> /// Create client document and replace document tags /// </summary> /// <param name="fromFileName"></param> /// <param name="destinationFileName"></param> /// <param name="tag"></param> /// <param name="vkWordApp"></param> /// <returns></returns> public static ResponseStatus CopyDocument( object fromFileName, object destinationFileName, List<WordDocumentTasks.TagStructure> tag, Word.Application vkWordApp, IOutputMessage uioutput, string processName, string userID ) { ResponseStatus ret = new ResponseStatus(); object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application not visible // vkWordApp.Visible = false; // vkWordApp.Activate(); // Let's copy the document if ( uioutput != null ) uioutput.AddOutputMessage( "Copying file from: " + fromFileName + " to: " + destinationFileName, processName, userID ); File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true); // Let's open the DESTINATION document Word.Document vkMyDoc; try { //vkMyDoc = vkWordApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); //vkMyDoc = vkWordApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); if ( uioutput != null ) uioutput.AddOutputMessage( "Opening file: " + destinationFileName, processName, userID ); vkMyDoc = vkWordApp.Documents.Open( FileName: destinationFileName, ConfirmConversions: vkFalse, ReadOnly: vkFalse, AddToRecentFiles: vkMissing, PasswordDocument: vkMissing, PasswordTemplate: vkMissing, Revert: vkMissing, WritePasswordDocument: vkMissing, WritePasswordTemplate: vkMissing, Format: vkMissing, Encoding: vkMissing, Visible: vkFalse ); } catch (Exception ex) { ret.ReturnCode = -1; ret.ReasonCode = 1000; ret.Message = "Error opening file." + destinationFileName; ret.Contents = ex; return ret; } // // In case the file is still read-only... // if ( uioutput != null ) uioutput.AddOutputMessage( "Checking if file is read-only: " + destinationFileName, processName, userID ); if ( vkMyDoc.ReadOnly ) { uioutput.AddOutputMessage( "(Word) File is Read-only contact support: " + fromFileName, processName, userID ); vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject( vkMyDoc ); return ret; } if ( uioutput != null ) uioutput.AddOutputMessage( "File is NOT read-only!! " + destinationFileName, processName, userID ); if ( uioutput != null ) uioutput.AddOutputMessage( "Starting find and replace loop", processName, userID ); // 18/04/2013 // vkMyDoc.Activate(); foreach (var t in tag) { if ( t.TagType == Helper.Utils.InformationType.FIELD || t.TagType == Helper.Utils.InformationType.VARIABLE ) { FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); // ReplaceProperty(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); } else { insertPicture( vkMyDoc, t.TagValue, t.Tag ); } } // 15/03/2013 // Force field update if ( uioutput != null ) uioutput.AddOutputMessage( "Force field updates.", processName, userID ); foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges) { myStoryRange.Fields.Update(); } // 24/10/2010 - Modificado quando troquei a referencia do Word // //vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update(); //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Fields.Update(); try { if ( vkMyDoc.ReadOnly ) { if (uioutput != null) uioutput.AddOutputMessage( "(Word) File is Read-only contact support: " + fromFileName, processName, userID ); } else { if ( uioutput != null ) uioutput.AddOutputMessage( "Saving file, it is no read-only.", processName, userID ); vkMyDoc.Save(); } } catch (Exception ex) { if (uioutput != null) uioutput.AddOutputMessage( "(Word) ERROR Saving in file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID ); } // close the new document try { if ( uioutput != null ) uioutput.AddOutputMessage( "Closing file", processName, userID ); vkMyDoc.Close(SaveChanges:vkTrue); } catch ( Exception ex ) { if (uioutput != null) uioutput.AddOutputMessage( "(Word) ERROR Closing file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID ); } // Trying to release COM object if ( uioutput != null ) uioutput.AddOutputMessage( "Releasing COM object", processName, userID ); System.Runtime.InteropServices.Marshal.ReleaseComObject( vkMyDoc ); return ret; } // --------------------------------------------- // Copy Documents // --------------------------------------------- public static object CopyDocument( object fromFileName, object destinationFileName, List<WordDocumentTasks.TagStructure> tag ) { Word.Application vkWordApp = new Word.Application(); object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application visible vkWordApp.Visible = true; vkWordApp.Activate(); // Let's copy the document File.Copy(fromFileName.ToString(), destinationFileName.ToString(), true); // Let's open the DESTINATION document Word.Document vkMyDoc = vkWordApp.Documents.Open( ref destinationFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); foreach (var t in tag) { FindAndReplace(t.Tag, t.TagValue, 1, vkWordApp, vkMyDoc); } vkMyDoc.Save(); // close the new document vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing); // close word application vkWordApp.Quit(ref vkFalse, ref vkMissing, ref vkMissing); return saveFile; } //// ---------------------------------------------------- //// Find and replace words in MS Word //// ---------------------------------------------------- //public static void FindAndReplaceFIRST( // object vkFind, // object vkReplace, // object vkNum, // Word.Application vkWordApp, // Word.Document vkMyDoc // ) //{ // object vkReadOnly = false; // object vkVisible = true; // object vkFalse = false; // object missing = false; // object vkTrue = true; // object vkDynamic = 2; // object replaceAll = Word.WdReplace.wdReplaceAll; // if (vkMyDoc == null) // { // return; // } // if (vkWordApp == null) // { // return; // } // if (vkReplace.ToString().Trim().Length == 0) // { // return; // } // if (vkFind.ToString().Trim().Length == 0) // { // return; // } // // Replace Word Document body // // // // 05/09/2010 - Testando a passagem de paramentros com nome do parametro... nao remover codigo abaixo. // // Working... Forward = false; // //vkWordApp.Selection.Find.Execute( // // ref vkFind, ref vkFalse, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse, // // ref vkTrue, ref vkNum, ref vkFalse, // // ref vkReplace, ref vkDynamic, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse ); // //vkWordApp.Selection.Find.Execute( // // FindText: vkFind, // // ReplaceWith: vkReplace, // // MatchCase: vkFalse, // // MatchWholeWord: vkTrue, // // MatchAllWordForms: vkTrue, // // Replace: vkDynamic); // vkWordApp.Selection.Find.Execute( // MatchCase: vkFalse, // MatchWholeWord: vkTrue, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // FindText: vkFind, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // // Replace in the primary header/ footer // // // //vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute( // // ref vkFind, ref vkFalse, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse, // // ref vkTrue, ref vkNum, ref vkFalse, // // ref vkReplace, ref vkDynamic, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse); // vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // // Replace in the first page footer // // // //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute( // // ref vkFind, ref vkFalse, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse, // // ref vkTrue, ref vkNum, ref vkFalse, // // ref vkReplace, ref vkDynamic, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse ); // vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage ).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages ).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); //} /// <summary> /// Replace inside the range /// </summary> /// <param name="range"></param> /// <param name="wordDocument"></param> /// <param name="wordApp"></param> /// <param name="findText"></param> /// <param name="replaceText"></param> private static void ReplaceRange(Word.Range range, Word.Document wordDocument, Word.Application wordApp, object findText, object replaceText) { object missing = System.Reflection.Missing.Value; wordDocument.Activate(); //object item = Word.WdGoToItem.wdGoToPage; //object whichItem = Word.WdGoToDirection.wdGoToFirst; //wordDocument.GoTo(ref item, ref whichItem, ref missing, ref missing); //object forward = true; //object replaceAll = Word.WdReplace.wdReplaceAll; //object matchAllWord = true; //range.Find.Execute(ref findText, ref missing, ref matchAllWord, // ref missing, ref missing, ref missing, ref forward, // ref missing, ref missing, ref replaceText, ref replaceAll, // ref missing, ref missing, ref missing, ref missing); range.Find.ClearFormatting(); range.Find.Replacement.ClearFormatting(); object vkTrue = true; object vkFalse = false; range.Find.Execute( FindText: findText, MatchCase: vkFalse, MatchWholeWord: vkTrue, MatchWildcards: vkFalse, MatchSoundsLike: vkFalse, MatchAllWordForms: vkFalse, Forward: vkFalse, Wrap: 1, Format: vkFalse, ReplaceWith: replaceText, Replace: 2, MatchKashida: vkFalse, MatchDiacritics: vkFalse, MatchAlefHamza: vkFalse, MatchControl: vkFalse); } /// <summary> /// Find and replace words in document /// </summary> /// <param name="vkFind"></param> /// <param name="vkReplace"></param> /// <param name="vkNum"></param> /// <param name="vkWordApp"></param> /// <param name="vkMyDoc"></param> public static void FindAndReplace( object vkFind, object vkReplace, object vkNum, Word.Application vkWordApp, Word.Document vkMyDoc ) { object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object missing = false; object vkTrue = true; object vkDynamic = 2; object replaceAll = Word.WdReplace.wdReplaceAll; if (vkMyDoc == null) { return; } if (vkWordApp == null) { return; } // 12.01.2013 // Allow spaces in replace variable - it will cause the system to clean-up unwanted variables. // //if (vkReplace.ToString().Trim().Length == 0) //{ // return; //} if (vkFind.ToString().Trim().Length == 0) { return; } string findText = vkFind.ToString().Trim(); string replaceText = vkReplace.ToString().Trim(); // In theory not needed... // //foreach (Word.Comment comment in vkMyDoc.Comments) //{ // ReplaceRange(comment.Range, vkMyDoc, vkWordApp, findText, replaceText); //} //foreach (Word.HeaderFooter header in vkMyDoc.Sections.Last.Headers) //{ // ReplaceRange(header.Range, vkMyDoc, vkWordApp, findText, replaceText); //} //foreach (Word.HeaderFooter footer in vkMyDoc.Sections.Last.Footers) //{ // ReplaceRange(footer.Range, vkMyDoc, vkWordApp, findText, replaceText); //} // End of changes on 07/01/2013 // I have enabled the code above to see if it work for the IMS document // foreach (Word.Shape shp in vkMyDoc.Shapes) { if (shp.TextFrame.HasText < 0) { ReplaceRange(shp.TextFrame.TextRange, vkMyDoc, vkWordApp, findText, replaceText); } } foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges) { ReplaceRange(myStoryRange, vkMyDoc, vkWordApp, findText, replaceText); foreach (Word.InlineShape shp in myStoryRange.InlineShapes) { ReplaceRange(shp.Range, vkMyDoc, vkWordApp, findText, replaceText); } // 23.02.2013 // This is to try to address header in different sections // It works! // foreach ( Word.HeaderFooter header in myStoryRange.Sections.Last.Headers ) { ReplaceRange( header.Range, vkMyDoc, vkWordApp, findText, replaceText ); } foreach ( Word.HeaderFooter footer in myStoryRange.Sections.Last.Footers ) { ReplaceRange( footer.Range, vkMyDoc, vkWordApp, findText, replaceText ); } } } /// <summary> /// Replace the property name /// </summary> /// <param name="vkFind"></param> /// <param name="vkReplace"></param> /// <param name="vkNum"></param> /// <param name="vkWordApp"></param> /// <param name="vkMyDoc"></param> public static void ReplaceProperty( object vkFind, object vkReplace, object vkNum, Word.Application vkWordApp, Word.Document vkMyDoc ) { if ( vkMyDoc == null ) { return; } if ( vkWordApp == null ) { return; } if ( vkFind.ToString().Trim().Length == 0 ) { return; } object oDocCustomProps; string propertyName = vkFind.ToString().Trim(); string propertyValue = vkReplace.ToString().Trim(); // -- change code from here -- // // It works however the propertyName must be defined in the document first otherwise it won't work. // var properties = vkMyDoc.CustomDocumentProperties; properties [propertyName].Value = propertyValue; } /// <summary> /// Not in use - Find Replace /// </summary> /// <param name="vkFind"></param> /// <param name="vkReplace"></param> /// <param name="vkNum"></param> /// <param name="vkWordApp"></param> /// <param name="vkMyDoc"></param> [Obsolete("There is another version of FindReplace", true)] public static void FindAndReplaceY( object vkFind, object vkReplace, object vkNum, Word.Application vkWordApp, Word.Document vkMyDoc ) { object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object missing = false; object vkTrue = true; object vkDynamic = 2; object replaceAll = Word.WdReplace.wdReplaceAll; // Replace Word Document body // foreach (Word.Range myStoryRange in vkMyDoc.StoryRanges) { ReplaceRange(myStoryRange, vkMyDoc, vkWordApp, vkFind, vkReplace); } } /// <summary> /// Find Replace option /// </summary> /// <param name="vkFind"></param> /// <param name="vkReplace"></param> /// <param name="vkNum"></param> /// <param name="vkWordApp"></param> /// <param name="vkMyDoc"></param> [Obsolete("There is another version of FindReplace", true)] public static void FindAndReplaceYS( object vkFind, object vkReplace, object vkNum, Word.Application vkWordApp, Word.Document vkMyDoc ) { object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object missing = false; object vkTrue = true; object vkDynamic = 2; object replaceAll = Word.WdReplace.wdReplaceAll; // Replace Word Document body // vkWordApp.Selection.Find.ClearFormatting(); vkWordApp.Selection.Find.Text = vkFind.ToString(); vkWordApp.Selection.Find.Replacement.ClearFormatting(); vkWordApp.Selection.Find.Replacement.Text = vkFind.ToString(); vkWordApp.Selection.Find.Execute( ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing); } // ---------------------------------------------------- // Insert picture // ---------------------------------------------------- public static void insertPicture(Word.Document oDoc, string pictureFile, object bookMarkName ) { // 02.03.2013 // Inserting pictures is on hold // PICTUREHOLD LogFile.WriteToTodaysLogFile( "Error: Pictures and logos are not being replace at this time. Issues are being investigated.","","","WordDocumentTasks.cs"); return; object oMissing = System.Reflection.Missing.Value; if ( pictureFile == "\\" || pictureFile == "\\\\" || string.IsNullOrEmpty( pictureFile ) ) return; // oDoc.ActiveWindow.Selection.Range.InlineShapes.AddPicture( // pictureFile, ref oMissing, ref oMissing, ref oMissing); // Object bookMarkName = "COMPANY_LOGO"; if (oDoc.Bookmarks.Exists(bookMarkName.ToString())) { //oDoc.Bookmarks.Item(ref bookMarkName).Range.InlineShapes.AddPicture( // pictureFile, ref oMissing, ref oMissing, ref oMissing); try { //oDoc.Bookmarks.Item(ref bookMarkName).Range.InlineShapes.AddPicture( // FileName: pictureFile, // LinkToFile: oMissing, // SaveWithDocument: oMissing, // Range: oMissing); oDoc.Bookmarks.Item( ref bookMarkName ).Range.InlineShapes.AddPicture( FileName: pictureFile, LinkToFile: oMissing, SaveWithDocument: oMissing, Range: oMissing ); } catch( Exception ex) { LogFile.WriteToTodaysLogFile( "insertPicture " + ex, "", "", "WordDocumentTasks.cs" ); } } // Object oMissed = doc.Paragraphs[2].Range; //the position you want to insert // doc.InlineShapes.AddPicture( } // ---------------------------------------------------- // Copy folder structure including files // ---------------------------------------------------- static public void CopyFolder( string sourceFolder, string destFolder ) { if (!Directory.Exists( destFolder )) Directory.CreateDirectory( destFolder ); string[] files = Directory.GetFiles( sourceFolder ); foreach (string file in files) { string name = Path.GetFileName( file ); string fileName = Path.GetFileNameWithoutExtension(file); string fileExtension = Path.GetExtension(file); string dest = Path.Combine( destFolder, fileName + "v01" + fileExtension ); File.Copy( file, dest ); } string[] folders = Directory.GetDirectories( sourceFolder ); foreach (string folder in folders) { string name = Path.GetFileName( folder ); string dest = Path.Combine( destFolder, name ); CopyFolder( folder, dest ); } } // ---------------------------------------------------- // Copy folder structure // ---------------------------------------------------- static public void ReplicateFolderStructure(string sourceFolder, string destFolder) { if (!Directory.Exists(destFolder)) Directory.CreateDirectory(destFolder); string[] folders = Directory.GetDirectories(sourceFolder); foreach (string folder in folders) { string name = Path.GetFileName(folder); string dest = Path.Combine(destFolder, name); ReplicateFolderStructure(folder, dest); } } // ---------------------------------------------------- // Replace strings in structure // ---------------------------------------------------- static public void ReplaceStringInAllFiles( string originalFolder, List<TagStructure> tagList, Word.Application vkWordApp) { object vkMissing = System.Reflection.Missing.Value; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; if (Directory.Exists(originalFolder)) { string[] files = Directory.GetFiles(originalFolder); foreach (string file in files) { string name = Path.GetFileName(file); object xFile = file; // Let's open the document Word.Document vkMyDoc = vkWordApp.Documents.Open( ref xFile, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); vkMyDoc.Select(); if (tagList.Count > 0) { for (int i = 0; i < tagList.Count; i++) { FindAndReplace( tagList[i].Tag, tagList[i].TagValue, 1, vkWordApp, vkMyDoc); } } WordDocumentTasks.insertPicture( vkMyDoc, "C:\\Research\\fcm\\Resources\\FCMLogo.jpg",""); vkMyDoc.Save(); vkMyDoc.Close(ref vkFalse, ref vkMissing, ref vkMissing); } // // Replace in all folders // string[] folders = Directory.GetDirectories(originalFolder); foreach (string folder in folders) { ReplaceStringInAllFiles(folder, tagList, vkWordApp); } } } public struct TagStructure : IEnumerable { public string TagType; public string Tag; public string TagValue; public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } // --------------------------------------------- // Print Document // --------------------------------------------- public static void PrintDocument( object fromFileName ) { if (!File.Exists( (string)fromFileName )) { MessageBox.Show( "File not found. " + fromFileName ); return; } Word.Application vkWordApp = new Word.Application(); object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application visible vkWordApp.Visible = true; vkWordApp.Activate(); // Let's open the document Word.Document vkMyDoc = vkWordApp.Documents.Open( ref fromFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible ); vkMyDoc.PrintOut(); vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject( vkMyDoc ); vkWordApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject( vkWordApp ); return; } /* http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx * 9.1 Embedding Pictures in Document Header: //EMBEDDING LOGOS IN THE DOCUMENT //SETTING FOCUES ON THE PAGE HEADER TO EMBED THE WATERMARK oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader; //THE LOGO IS ASSIGNED TO A SHAPE OBJECT SO THAT WE CAN USE ALL THE //SHAPE FORMATTING OPTIONS PRESENT FOR THE SHAPE OBJECT Word.Shape logoCustom = null; //THE PATH OF THE LOGO FILE TO BE EMBEDDED IN THE HEADER String logoPath = "C:\\Document and Settings\\MyLogo.jpg"; logoCustom = oWord.Selection.HeaderFooter.Shapes.AddPicture(logoPath, ref oFalse, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); logoCustom.Select(ref oMissing); logoCustom.Name = "CustomLogo"; logoCustom.Left = (float)Word.WdShapePosition.wdShapeLeft; //SETTING FOCUES BACK TO DOCUMENT oWord.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument; */ public static void CompareDocuments(object fromFileName, string toFileName) { if (!File.Exists((string)fromFileName)) { MessageBox.Show("File not found. " + fromFileName); return; } Word.Application vkWordApp = new Word.Application(); object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the word application visible vkWordApp.Visible = true; vkWordApp.Activate(); // Let's open the document Word.Document vkMyDoc = vkWordApp.Documents.Open( ref fromFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); vkMyDoc.Compare(toFileName); vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(vkMyDoc); vkWordApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(vkWordApp); return; } /// <summary> /// Generate master of system documents /// </summary> /// <param name="tv"></param> private ResponseStatus GenerateMasterOfSystemDocuments(TreeView tv) { ResponseStatus ret = new ResponseStatus(); object destinationFileName = "temp01.doc"; object saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; Word.Application vkWordApp = new Word.Application(); Word.Document vkMyDoc; try { vkMyDoc = vkWordApp.Documents.Open( ref destinationFileName, ref vkMissing, ref vkReadOnly, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkMissing, ref vkVisible); } catch (Exception ex) { ret.ReturnCode = -1; ret.ReasonCode = 1000; ret.Message = "Error creating file."; ret.Contents = ex; return ret; } return ret; } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using System.Windows.Forms; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentSet { public int UID { get; set; } public string Name { get; set; } public string TemplateType { get; set; } public string TemplateFolder { get; set; } public char IsVoid { get; set; } public DocumentList documentList { get; set; } public List<Document> listOfDocumentsInSet { get; set; } public List<DocumentSet> documentSetList { get; set; } public string UIDNameDisplay { get; set; } /// <summary> /// Load document into document set /// </summary> public void LoadAllDocuments() { // Retrieve all documents // For each document (order by parent uid) // check if it is already connected to current Document Set // If it is not, connect document // Link with parent document in the set // Replicate Document Links // 21/08/2013 // Stop using DocumentList // //DocumentList dl = new DocumentList(); //dl.List(); List<Document> docl = RepDocument.List(HeaderInfo.Instance); foreach (Document document in docl) { var found = DocumentSet.FindDocumentInSet(this.UID, document.UID); if (found.document.UID > 0) continue; else { DocumentSetDocument dsl = new DocumentSetDocument(); // Generate new UID dsl.UID = this.GetLastUID() + 1; // Add document to set // dsl.FKDocumentSetUID = this.UID; dsl.FKDocumentUID = document.UID; dsl.Location = document.Location; dsl.IsVoid = 'N'; dsl.StartDate = System.DateTime.Today; dsl.EndDate = System.DateTime.MaxValue; dsl.FKParentDocumentUID = document.ParentUID; // Uses the Document UID as the source (Has to be combined with Doc Set) dsl.FKParentDocumentSetUID = dsl.FKDocumentSetUID; dsl.SequenceNumber = document.SequenceNumber; dsl.Add(); } } // Replicate document links // foreach (Document document in docl) { var children = DocumentLinkList.ListRelatedDocuments(document.UID); foreach (var child in children.documentLinkList) { // DocumentSetDocumentLink dsdl = new DocumentSetDocumentLink(); dsdl.FKParentDocumentUID = 0; dsdl.FKChildDocumentUID = 0; dsdl.IsVoid = 'N'; dsdl.LinkType = child.LinkType; dsdl.UID = GetLastUID() + 1; // Find parent var parent1 = DocumentSet.FindDocumentInSet(this.UID, child.FKParentDocumentUID); // Find child var child1 = DocumentSet.FindDocumentInSet(this.UID, child.FKChildDocumentUID); dsdl.FKParentDocumentUID = parent1.DocumentSetDocument.UID; dsdl.FKChildDocumentUID = child1.DocumentSetDocument.UID; dsdl.Add(); } } } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM DocumentSet"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Get Document Details // ----------------------------------------------------- public static scDocoSetDocumentLink FindDocumentInSet(int documentSetUID, int documentUID) { // // EA SQL database // scDocoSetDocumentLink ret = new scDocoSetDocumentLink(); ret.document = new Model.ModelDocument.Document(); ret.documentSet = new DocumentSet(); ret.DocumentSetDocument = new DocumentSetDocument(); string commandString = ""; commandString = string.Format( " SELECT " + " Document.UID DocumentUID" + " ,Document.CUID DocumentCUID " + " ,Document.Name DocumentName " + " ,Document.SequenceNumber DocumentSequenceNumber " + " ,Document.IssueNumber DocumentIssueNumber " + " ,Document.Location DocumentLocation "+ " ,Document.Comments DocumentComments" + " ,Document.UID DocumentUID" + " ,Document.FileName DocumentFileName" + " ,Document.SourceCode DocumentSourceCode" + " ,Document.FKClientUID DocumentFKClientUID" + " ,Document.ParentUID DocumentParentUID" + " ,Document.RecordType DocumentRecordType" + " ,Document.IsProjectPlan DocumentIsProjectPlan" + " ,Document.DocumentType DocumentDocumentType" + " ,DocSetDoc.UID DocSetDocUID" + " ,DocSetDoc.FKDocumentUID DocSetDocFKDocumentUID" + " ,DocSetDoc.FKDocumentSetUID DocSetDocFKDocumentSetUID" + " ,DocSetDoc.Location DocSetDocLocation" + " ,DocSetDoc.IsVoid DocSetDocIsVoid" + " ,DocSetDoc.StartDate DocSetDocStartDate" + " ,DocSetDoc.EndDate DocSetDocEndDate" + " ,DocSetDoc.FKParentDocumentUID DocSetDocFKParentDocumentUID" + " ,DocSetDoc.FKParentDocumentSetUID DocSetDocFKParentDocumentSetUID" + " ,DocSet.UID SetUID" + " ,DocSet.TemplateType SetTemplateType" + " ,DocSet.TemplateFolder SetTemplateFolder" + " FROM Document Document" + " ,DocumentSetDocument DocSetDoc " + " ,DocumentSet DocSet " + " WHERE " + " Document.UID = DocSetDoc.FKDocumentUID "+ " AND DocSetDoc.FKDocumentSetUID = DocSet.UID " + " AND Document.UID = {0} " + " AND DocSetDoc.FKDocumentSetUID = {1}", documentUID, documentSetUID); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { // Document // RepDocument.LoadDocumentFromReader(ret.document, "", reader); //ret.document.UID = Convert.ToInt32(reader["DocumentUID"].ToString()); //ret.document.CUID = reader["DocumentCUID"].ToString(); //ret.document.Name = reader["DocumentName"].ToString(); //ret.document.SequenceNumber = Convert.ToInt32(reader["DocumentSequenceNumber"].ToString()); //ret.document.IssueNumber = Convert.ToInt32(reader["DocumentIssueNumber"].ToString()); //ret.document.Location = reader["DocumentLocation"].ToString(); //ret.document.Comments = reader["DocumentComments"].ToString(); //ret.document.FileName = reader["DocumentFileName"].ToString(); //ret.document.SourceCode = reader["DocumentSourceCode"].ToString(); //ret.document.FKClientUID = Convert.ToInt32(reader["DocumentFKClientUID"].ToString()); //ret.document.ParentUID = Convert.ToInt32(reader["DocumentParentUID"].ToString()); //ret.document.RecordType = reader["DocumentRecordType"].ToString(); //ret.document.IsProjectPlan = Convert.ToChar(reader["DocumentIsProjectPlan"]); //ret.document.DocumentType = reader["DocumentDocumentType"].ToString(); // Document Set // ret.documentSet.UID = Convert.ToInt32(reader["SetUID"].ToString()); ret.documentSet.TemplateType = reader["SetTemplateType"].ToString(); ret.documentSet.TemplateFolder = reader["SetTemplateFolder"].ToString(); ret.documentSet.UIDNameDisplay = ret.documentSet.UID.ToString() + "; " + ret.documentSet.TemplateType; // DocumentSetDocument // ret.DocumentSetDocument.UID = Convert.ToInt32(reader["DocSetDocUID"].ToString()); ret.DocumentSetDocument.FKDocumentUID = Convert.ToInt32(reader["DocSetDocFKDocumentUID"].ToString()); ret.DocumentSetDocument.FKDocumentSetUID = Convert.ToInt32(reader["DocSetDocFKDocumentSetUID"].ToString()); ret.DocumentSetDocument.Location = reader["DocSetDocLocation"].ToString(); ret.DocumentSetDocument.IsVoid = Convert.ToChar(reader["DocSetDocIsVoid"].ToString()); ret.DocumentSetDocument.StartDate = Convert.ToDateTime(reader["DocSetDocStartDate"].ToString()); ret.DocumentSetDocument.EndDate = Convert.ToDateTime(reader["DocSetDocEndDate"].ToString()); ret.DocumentSetDocument.FKParentDocumentUID = Convert.ToInt32(reader["DocSetDocFKParentDocumentUID"].ToString()); ret.DocumentSetDocument.FKParentDocumentSetUID = Convert.ToInt32(reader["DocSetDocFKParentDocumentSetUID"].ToString()); } catch { } } } } return ret; } // ----------------------------------------------------- // Get Document Set Details // ----------------------------------------------------- public bool Read(char IncludeDocuments) { // // EA SQL database // bool ret = false; string commandString = ""; commandString = string.Format( " SELECT UID " + " ,TemplateType " + " ,TemplateFolder " + " ,IsVoid " + " FROM DocumentSet " + " WHERE UID = {0} ", UID); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32(reader["UID"].ToString()); this.TemplateType = reader["TemplateType"].ToString(); this.TemplateFolder = reader["TemplateFolder"].ToString(); this.UIDNameDisplay = this.UID + "; " + this.TemplateType; this.IsVoid = Convert.ToChar(reader["IsVoid"].ToString()); ret = true; } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString()); } } } if (IncludeDocuments == 'Y') { this.documentList = new DocumentList(); this.documentList.ListDocSet(this.UID); this.ListDocumentsInSet( this.UID ); } } return ret; } public List<Document> ListDocumentsNotInSet(HeaderInfo headerInfo, int documentSetUID) { List<Document> documentsNotInSet = new List<Document>(); List<Document> documentsInSet = new List<Document>(); List<Document> fullListOfDocuments = new List<Document>(); fullListOfDocuments = RepDocument.ListDocuments(headerInfo); ListDocumentsInSet(documentSetUID); documentsInSet = this.listOfDocumentsInSet; bool found = false; foreach (var document in fullListOfDocuments) { found = false; foreach (var documentInSet in listOfDocumentsInSet) { // Document already in set if ( document.CUID == documentInSet.CUID ) { found = true; break; } } if (found) continue; // if gets to this point, document is not in set documentsNotInSet.Add(document); } return documentsNotInSet; } // ----------------------------------------------------- // Delete Document/ Folder node // ----------------------------------------------------- public static void DeleteDocumentTreeNode(int documentSetUID, TreeNode documentSetNode) { if (documentSetNode == null) return; if (documentSetUID <= 0) return; foreach (TreeNode documentAsNode in documentSetNode.Nodes) { Model.ModelDocument.Document doc = (Model.ModelDocument.Document)documentAsNode.Tag; DocumentSetDocument.Delete(DocumentSetUID: documentSetUID, DocumentUID: doc.UID); if (documentAsNode.Nodes.Count > 0) { foreach (TreeNode tn in documentAsNode.Nodes) { DeleteDocumentTreeNode(documentSetUID: documentSetUID, documentSetNode: tn); } } } Model.ModelDocument.Document doc2 = (Model.ModelDocument.Document)documentSetNode.Tag; DocumentSetDocument.Delete(DocumentSetUID: documentSetUID, DocumentUID: doc2.UID); return; } // ----------------------------------------------------- // Add new Document Set // ----------------------------------------------------- public int Add() { int _uid = 0; _uid = GetLastUID() + 1; this.UID = _uid; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO DocumentSet" + "( " + " UID " + ",TemplateType " + ",TemplateFolder" + ",IsVoid" + ")" + " VALUES " + "( " + " @UID " + ", @TemplateType " + ", @TemplateFolder " + ", @IsVoid " + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@TemplateType", MySqlDbType.VarChar).Value = TemplateType; command.Parameters.Add("@TemplateFolder", MySqlDbType.VarChar).Value = TemplateFolder; command.Parameters.Add("@IsVoid", MySqlDbType.VarChar).Value = 'N'; connection.Open(); command.ExecuteNonQuery(); } } return _uid; } // ----------------------------------------------------- // Add new Document Set // ----------------------------------------------------- public void Update() { using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE DocumentSet " + " SET " + " TemplateType = @TemplateType " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = this.UID; command.Parameters.Add("@TemplateType", MySqlDbType.VarChar).Value = this.TemplateType; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// List Document Set /// </summary> public void List() { this.documentSetList = new List<DocumentSet>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,TemplateType " + " ,TemplateFolder " + " ,IsVoid " + " FROM DocumentSet " + " WHERE IsVoid = 'N' " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { DocumentSet documentSet = new DocumentSet(); documentSet.UID = Convert.ToInt32(reader["UID"].ToString()); documentSet.TemplateType = reader["TemplateType"].ToString(); documentSet.TemplateFolder = reader["TemplateFolder"].ToString(); documentSet.IsVoid = Convert.ToChar(reader["IsVoid"].ToString()); documentSet.UIDNameDisplay = documentSet.UID.ToString() + "; " + documentSet.TemplateType; this.documentSetList.Add(documentSet); } } } } } /// <summary> /// List Document Set /// </summary> public static List<DocumentSet> ListS() { var documentSetList = new List<DocumentSet>(); using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { var commandString = string.Format( " SELECT UID " + " ,TemplateType " + " ,TemplateFolder " + " ,IsVoid " + " FROM DocumentSet " + " WHERE IsVoid = 'N' " ); using ( var command = new MySqlCommand( commandString, connection ) ) { connection.Open(); using ( MySqlDataReader reader = command.ExecuteReader() ) { while ( reader.Read() ) { DocumentSet documentSet = new DocumentSet(); documentSet.UID = Convert.ToInt32( reader ["UID"].ToString() ); documentSet.TemplateType = reader ["TemplateType"].ToString(); documentSet.TemplateFolder = reader ["TemplateFolder"].ToString(); documentSet.IsVoid = Convert.ToChar( reader ["IsVoid"].ToString() ); documentSet.UIDNameDisplay = documentSet.UID.ToString() + "; " + documentSet.TemplateType; documentSetList.Add( documentSet ); } } } } return documentSetList; } public void ListInComboBox(ComboBox cbxList) { this.List(); foreach (DocumentSet docSet in documentSetList) { cbxList.Items.Add(docSet.UID + "; " + docSet.TemplateType); } } // ----------------------------------------------------- // List Documents for a Document Set // ----------------------------------------------------- public void ListDocumentsInSet( int documentSetUID ) { this.listOfDocumentsInSet = new List<Document>(); using ( var connection = new MySqlConnection( ConnString.ConnectionString ) ) { var commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat( "DOC" ) + " ,LNK.FKParentDocumentUID " + " ,LNK.FKParentDocumentSetUID " + " ,LNK.SequenceNumber " + " FROM Document DOC " + " ,DocumentSetDocument LNK" + " WHERE " + " LNK.FKDocumentUID = DOC.UID " + " AND DOC.SourceCode = 'FCM' " + " AND LNK.IsVoid = 'N' " + " AND DOC.IsVoid = 'N' " + " AND LNK.FKDocumentSetUID = {0} " + " ORDER BY LNK.FKParentDocumentUID ASC, LNK.SequenceNumber ", documentSetUID ); using ( var command = new MySqlCommand( commandString, connection ) ) { connection.Open(); using ( MySqlDataReader reader = command.ExecuteReader() ) { while ( reader.Read() ) { Model.ModelDocument.Document _Document = new Model.ModelDocument.Document(); RepDocument.LoadDocumentFromReader( _Document, "DOC", reader ); // This is necessary because when the list comes from DocumentSet, the parent may change // _Document.ParentUID = Convert.ToInt32( reader ["FKParentDocumentUID"].ToString() ); this.listOfDocumentsInSet.Add( _Document ); } } } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Model.ModelClient { public class Client : EventArgs { public int UID { get; set; } public int LogoImageSeqNum { get; set; } [Required( ErrorMessage = "ABN is mandatory." )] [Display( Name = "ABN" )] public string ABN { get; set; } [Required(ErrorMessage = "Client name is mandatory.")] [Display(Name = "Name")] public string Name { get; set; } [Required(ErrorMessage = "Legal name is mandatory.")] [Display(Name = "Legal Name")] public string LegalName { get; set; } [Required( ErrorMessage = "Address is mandatory." )] [Display( Name = "Address" )] public string Address { get; set; } [Required( ErrorMessage = "Phone is mandatory." )] [Display( Name = "Phone Number" )] public string Phone { get; set; } public string Fax { get; set; } public string Mobile { get; set; } [Display(Name = "Logo - Small")] public string Logo1Location { get; set; } [Display(Name = "Logo - Medium")] public string Logo2Location { get; set; } [Display(Name = "Logo - Large")] public string Logo3Location { get; set; } [Display(Name = "Email Address")] public string EmailAddress { get; set; } [Display(Name = "Contact Person - Name")] public string MainContactPersonName { get; set; } [Display(Name = "Display Logo where applicable")] public char? DisplayLogo { get; set; } [Display(Name = "Client logs on to the system with user")] public string FKUserID { get; set; } [Display( Name = "Contractor Size" )] public int FKDocumentSetUID { get; set; } [Display( Name = "Contractor Size Description" )] public string DocSetUIDDisplay { get; set; } public string UserIdCreatedBy { get; set; } public string UserIdUpdatedBy { get; set; } public DateTime CreationDateTime { get; set; } public DateTime UpdateDateTime { get; set; } public int RecordVersion { get; set; } public string IsVoid { get; set; } public ClientExtraInformation clientExtraInformation { get; set; } public ClientEmployee clientEmployee { get; set; } public FCMConstant.DataBaseType databasetype; public HeaderInfo _headerInfo { get; set; } public List<Client> clientList { get; set; } public Client() { } public Client(HeaderInfo headerInfo) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MackkadoITFramework.Interfaces; using MackkadoITFramework.Utils; namespace fcm.Windows { public partial class UIOutputMessage : Form, IOutputMessage { public DataTable elementSourceDataTable; public DataTable errorDataTable; public UIOutputMessage() { InitializeComponent(); // Create datatable var outputMessage = new DataColumn("outputMessage", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(outputMessage); dgvOutputMessage.DataSource = elementSourceDataTable; // Create datatable var errorMessage = new DataColumn( "errorMessage", typeof( String ) ); errorDataTable = new DataTable( "ElementSourceDataTable" ); errorDataTable.Columns.Add( errorMessage ); dgvErrorList.DataSource = errorDataTable; } private void UIOutputMessage_Load(object sender, EventArgs e) { txtStartTime.Text = System.DateTime.Now.ToString(); } public void AddOutputMessage( string outputMessage, string processName, string userID ) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["outputMessage"] = outputMessage; elementSourceDataTable.Rows.Add(elementRow); txtEndTime.Text = System.DateTime.Now.ToString(); dgvOutputMessage.FirstDisplayedCell = dgvOutputMessage[0, dgvOutputMessage.Rows.Count - 1]; LogFile.WriteToTodaysLogFile( what: outputMessage,userID:userID,messageCode:"",programName:"UIOutputMessage.cs", processname: processName ); this.Refresh(); } public void AddErrorMessage( string errorMessage, string processName, string userID ) { DataRow elementRow = errorDataTable.NewRow(); elementRow["errorMessage"] = errorMessage; errorDataTable.Rows.Add( elementRow ); txtEndTime.Text = System.DateTime.Now.ToString(); dgvOutputMessage.FirstDisplayedCell = dgvOutputMessage[0, dgvOutputMessage.Rows.Count - 1]; LogFile.WriteToTodaysLogFile( what: errorMessage, userID: userID, messageCode: "", programName: "UIOutputMessage.cs", processname: processName ); this.Refresh(); } public void UpdateProgressBar( double value, DateTime estimatedTime, int documentsToBeGenerated = 0 ) { if (value > 100) return; progressBar1.Value = Convert.ToInt32( value ); txtEstimatedTime.Text = estimatedTime.ToString(); txtDocsToBeGenerated.Text = documentsToBeGenerated.ToString(); this.Refresh(); } private void btnOk_Click(object sender, EventArgs e) { this.Close(); } } } <file_sep>using System; using System.Data; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; namespace fcm.Windows { public partial class UIProposal : Form { public DataTable elementSourceDataTable; public UIProposal() { InitializeComponent(); // _connectionString = connectionString; // // Create datatable // var CUID = new DataColumn("CUID", typeof(String)); var Name = new DataColumn("Name", typeof(String)); var Directory = new DataColumn("Directory", typeof(String)); var Subdirectory = new DataColumn("Subdirectory", typeof(String)); var SequenceNumber = new DataColumn("SequenceNumber", typeof(Int32)); var IssueNumber = new DataColumn("IssueNumber", typeof(String)); var Location = new DataColumn("Location", typeof(String)); var Comments = new DataColumn("Comments", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(CUID); elementSourceDataTable.Columns.Add(Name); elementSourceDataTable.Columns.Add(Directory); elementSourceDataTable.Columns.Add(Subdirectory); elementSourceDataTable.Columns.Add(SequenceNumber); elementSourceDataTable.Columns.Add(IssueNumber); elementSourceDataTable.Columns.Add(Location); dgvDocumentList.DataSource = elementSourceDataTable; } private void UIProposal_Load(object sender, EventArgs e) { loadDocumentList(); foreach (Client c in Utils.ClientList) { cbxClient.Items.Add(c.UID + "; " + c.Name); } cbxClient.SelectedIndex = Utils.ClientIndex; // Proposal Type var propTypeList = new CodeValue(); propTypeList.ListInCombo(CodeType.CodeTypeValue.ProposalType, cbxProposalType); // Status var propStatusList = new CodeValue(); propStatusList.ListInCombo(CodeType.CodeTypeValue.ProposalStatus, cbxStatus); } // // List companies // private void loadDocumentList() { elementSourceDataTable.Clear(); var docoList = new DocumentList(); docoList.List(); foreach (Document doco in docoList.documentList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["CUID"] = doco.CUID; elementRow["Name"] = doco.Name; //elementRow["Directory"] = doco.Directory; //elementRow["Subdirectory"] = doco.Subdirectory; elementRow["SequenceNumber"] = doco.SequenceNumber; elementRow["IssueNumber"] = doco.IssueNumber; elementRow["Location"] = doco.Location; elementSourceDataTable.Rows.Add(elementRow); } } private void cbxClient_SelectedIndexChanged(object sender, EventArgs e) { Utils.ClientID = Utils.ClientList[cbxClient.SelectedIndex].UID; // Utils.ClientIndex = cbxClient.SelectedIndex; } private void removeToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var selRows in dgvDocumentList.SelectedRows) { dgvDocumentList.Rows.Remove((DataGridViewRow)selRows); } } } } <file_sep>using System; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using MKITHelper = MackkadoITFramework.Helper; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; namespace fcm.Windows { public partial class UIDocumentEdit : Form { private UIDocumentList uidl; private Document docSave; public bool documentSavedSuccessfully; TreeNode treeNode; private string _fileName; private string _fullPathFileName; private int _clientUID; private Form _previousForm; public UIDocumentEdit(Form previousForm) { InitializeComponent(); docSave = new Document(); // Load record type // cbxRecordType.Items.Add(FCMConstant.RecordType.DOCUMENT); cbxRecordType.Items.Add(FCMConstant.RecordType.APPENDIX); cbxRecordType.Items.Add(FCMConstant.RecordType.FOLDER); cbxRecordType.Text = FCMConstant.RecordType.DOCUMENT; // Load document type // cbxDocumentType.Items.Add(MackkadoITFramework.Helper.Utils.DocumentType.WORD); cbxDocumentType.Items.Add(MackkadoITFramework.Helper.Utils.DocumentType.EXCEL); cbxDocumentType.Items.Add(MackkadoITFramework.Helper.Utils.DocumentType.PDF); cbxDocumentType.Items.Add(MackkadoITFramework.Helper.Utils.DocumentType.FOLDER); cbxDocumentType.Items.Add(MackkadoITFramework.Helper.Utils.DocumentType.UNDEFINED); cbxDocumentType.Text = MackkadoITFramework.Helper.Utils.DocumentType.UNDEFINED; cbxSourceCode.Enabled = false; } /// <summary> /// Constructor to allow document to be saved to client. /// </summary> /// <param name="fileName"></param> /// <param name="fullPathFileName"></param> public UIDocumentEdit( Form previousForm, string fileName, string fullPathFileName, int clientUID ) : this(previousForm) { _fileName = fileName; _fullPathFileName = fullPathFileName; _clientUID = clientUID; } public UIDocumentEdit( Form previousForm, UIDocumentList _uidl ) : this(previousForm) { InitializeComponent(); uidl = new UIDocumentList(); uidl = _uidl; txtCUID.Enabled = false; txtCUID.ReadOnly = true; // txtDirectory.Focus(); } public UIDocumentEdit( Form previousForm, Document document, TreeNode tn ) : this(previousForm) { docSave = document; SetValues(document); if (document.UID == 0) { // New document New(); } documentSavedSuccessfully = false; treeNode = new TreeNode(); treeNode = tn; docSave = document; } public UIDocumentEdit(Form previousForm, int clientUID) : this(previousForm) { cbxSourceCode.Text = FCMConstant.SourceCode.CLIENT; cbxSourceCode.Enabled = false; txtClientUID.Text = clientUID.ToString(); btnClient.Enabled = false; btnNewIssue.Enabled = false; txtIssueNumber.Text = "001"; txtSeqNum.Text = "001"; // int nextClientDocument = ClientDocument.GetLastClientCUID( clientUID ) + 1; int nextClientDocument = BUSClientDocument.GetLastClientCUID( clientUID ) + 1; // The full name can only be added when the document is assigned to the client. // // txtCUID.Text = "CLI-" + nextClientDocument.ToString( "00" ) +"-00-" + clientUID.ToString( "0000" ) + "-01"; txtCUID.Text = "CLI-" + nextClientDocument.ToString( "00" ); // +"-00-" + clientUID.ToString( "0000" ) + "-01"; } private void UIDocumentEdit_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(_fileName)) { txtClientUID.Text = _clientUID.ToString(); } // // Enable or disable fields accordingly // if (string.IsNullOrEmpty(txtClientUID.Text)) { btnNewIssue.Enabled = false; txtIssueNumber.Enabled = true; txtCUID.Enabled = true; txtCUID.ReadOnly = false; cbxSourceCode.SelectedIndex = 0; cbxSourceCode.Text = FCMConstant.SourceCode.FCM; txtSeqNum.Text = "1"; tsSave.Enabled = false; } else { btnNewIssue.Enabled = true; txtIssueNumber.Enabled = false; txtCUID.Enabled = true; } if (!string.IsNullOrEmpty(_fileName)) { FileSelected(_fileName, _fullPathFileName); enableSave(null, null); } } // Set directory and description // public void SetDirectory(string _directory, string _directoryDescription) { //txtDirectory.Text = _directory; //txtDirectoryDescription.Text = _directoryDescription; return; } // Set sub directory and description // public void SetSubDirectory(string _subdirectory, string _subdirectoryDescription) { //txtSubDirectory.Text = _subdirectory; //txtSubDirectoryDescription.Text = _subdirectoryDescription; return; } private void btnDelete_Click(object sender, EventArgs e) { } private void btnNew_Click(object sender, EventArgs e) { New(); } // // Clear fields // private void New() { txtUID.Text = ""; txtSimpleFileName.Text = ""; txtCUID.Text = ""; txtLocation.Text = ""; txtIssueNumber.Text = ""; txtName.Text = ""; txtSeqNum.Text = ""; //txtDirectory.Text = ""; //txtSubDirectory.Text = ""; txtComments.Text = ""; //txtDirectoryDescription.Text = ""; //txtSubDirectoryDescription.Text = ""; txtFileName.Text = ""; // txtClientUID.Text = ""; //cbxSourceCode.SelectedText = FCMConstant.SourceCode.FCM; //cbxSourceCode.SelectedIndex = 0; cbxRecordType.Text = FCMConstant.RecordType.DOCUMENT; cbxDocumentType.Text = MackkadoITFramework.Helper.Utils.DocumentType.UNDEFINED; txtIssueNumber.Enabled = true; txtIssueNumber.ReadOnly = false; txtCUID.Enabled = true; txtCUID.ReadOnly = false; txtCUID.Focus(); } public void SetValues(Document inDoco) { txtUID.Text = inDoco.UID.ToString(); txtCUID.Text = inDoco.CUID; txtLocation.Text = inDoco.Location; txtIssueNumber.Text = inDoco.IssueNumber.ToString(); txtName.Text = inDoco.Name; txtDisplayName.Text = inDoco.DisplayName; txtSeqNum.Text = inDoco.SequenceNumber.ToString(); txtComments.Text = inDoco.Comments; txtFileName.Text = inDoco.FileName; txtSimpleFileName.Text = inDoco.SimpleFileName; cbxSourceCode.Text = inDoco.SourceCode; txtClientUID.Text = inDoco.FKClientUID.ToString(); txtParentUID.Text = inDoco.ParentUID.ToString(); cbxRecordType.Text = inDoco.RecordType; cbxDocumentType.Text = inDoco.DocumentType; checkProjectPlan.Checked = false; if (inDoco.IsProjectPlan == "Y") checkProjectPlan.Checked = true; } private void btnSave_Click( object sender, EventArgs e ) { //Document docSave = new Document(); if (string.IsNullOrEmpty( cbxSourceCode.Text )) { MessageBox.Show( "Source code must be set." ); return; } if (string.IsNullOrEmpty( cbxDocumentType.Text )) { MessageBox.Show( "Document Type must be set." ); return; } if (string.IsNullOrEmpty( txtUID.Text )) docSave.UID = 0; else docSave.UID = Convert.ToInt32( txtUID.Text ); if (checkProjectPlan.Checked) docSave.IsProjectPlan = "N"; else docSave.IsProjectPlan = "N"; docSave.CUID = txtCUID.Text; docSave.Comments = txtComments.Text; docSave.Location = txtLocation.Text; docSave.Status = "ACTIVE"; if (string.IsNullOrEmpty(txtIssueNumber.Text)) docSave.IssueNumber = 0; else docSave.IssueNumber = Convert.ToInt32(txtIssueNumber.Text); docSave.Name = txtName.Text; docSave.DisplayName = txtDisplayName.Text; docSave.RecordType = cbxRecordType.Text; docSave.SimpleFileName = txtSimpleFileName.Text; if (cbxRecordType.Text == FCMConstant.RecordType.FOLDER) cbxDocumentType.Text = MackkadoITFramework.Helper.Utils.DocumentType.FOLDER; docSave.DocumentType = cbxDocumentType.Text; if (string.IsNullOrEmpty( cbxRecordType.Text )) { MessageBox.Show( "Record Type is mandatory." ); return; } if (string.IsNullOrEmpty( cbxDocumentType.Text )) { MessageBox.Show( "Document Type is mandatory." ); return; } // Parent UID is sourced from document tree // if (string.IsNullOrEmpty( txtParentUID.Text )) docSave.ParentUID = 0; else docSave.ParentUID = Convert.ToInt32( txtParentUID.Text ); if (string.IsNullOrEmpty( txtSeqNum.Text )) docSave.SequenceNumber = 0; else docSave.SequenceNumber = Convert.ToInt32( txtSeqNum.Text ); docSave.Comments = txtComments.Text; docSave.FileName = txtFileName.Text; docSave.FileExtension = MKITHelper.Utils.GetFileExtensionString( txtFileName.Text ); docSave.SourceCode = cbxSourceCode.Text; if (string.IsNullOrEmpty( txtClientUID.Text )) docSave.FKClientUID = 0; else docSave.FKClientUID = Convert.ToInt32( txtClientUID.Text ); if (docSave.SourceCode == "CLIENT" && docSave.FKClientUID == 0) { MessageBox.Show( "Client ID is mandatory if source type is CLIENT" ); return; } // docSave.Save(HeaderInfo.Instance, FCMConstant.SaveType.UPDATE); // RepDocument.Save(HeaderInfo.Instance, docSave, FCMConstant.SaveType.UPDATE); var documentSaveRequest = new DocumentSaveRequest(); documentSaveRequest.inDocument = docSave; documentSaveRequest.headerInfo = HeaderInfo.Instance; documentSaveRequest.saveType = FCMConstant.SaveType.UPDATE; var resp = BUSDocument.DocumentSave(documentSaveRequest); docSave.UID = resp.document.UID; if (uidl != null) uidl.Refresh(); txtLocation.Text = resp.document.Location; MessageBox.Show( resp.response.Message); txtCUID.Enabled = false; txtCUID.ReadOnly = true; //txtDirectory.Focus(); documentSavedSuccessfully = true; if (treeNode == null) { // There is no need to set the treenode unless it is passed in. } else { treeNode.Tag = docSave; treeNode.Name = docSave.FileName; } } private void btnOpenFile_Click(object sender, EventArgs e) { // Separate the file name from the path // Store both in separate fields // // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Show file dialog openFileDialog1.InitialDirectory = templateFolder; openFileDialog1.Filter = "*.doc|*.xls|*.xlsx|*.docx"; openFileDialog1.FileName = "*"; var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; // Extract File Path string pathOnly = fullPathFileName.Replace(fileName, ""); txtFileName.Text = fileName; txtLocation.Text = pathOnly; string pathPartToCheck = ""; if (pathOnly.Length >= templateFolder.Length) pathPartToCheck = pathOnly.Substring(0, templateFolder.Length); else pathPartToCheck = pathOnly; if (pathPartToCheck != templateFolder) { txtFileName.Text = ""; txtLocation.Text = ""; MessageBox.Show("Please select file from allowed folder. " + templateFolder); return; } // Get reference path // string refPath = Utils.getReferenceFilePathName(txtLocation.Text); txtLocation.Text = refPath; // This is the name of the document and not the file name // If it is already set for the client, there is no need // to replace it. The idea here is to suggest a name only // when the document is being created. // if (string.IsNullOrEmpty(txtName.Text)) { txtName.Text = openFileDialog1.SafeFileName.Substring(0, openFileDialog1.SafeFileName.Length - 4); } txtFileName.Text = openFileDialog1.SafeFileName; // 03.04.2013 // CLA-00-00 txtDisplayName.Text = txtFileName.Text; txtCUID.Text = txtFileName.Text.Substring(0, 6); cbxDocumentType.Text = "WORD"; cbxRecordType.Text = FCMConstant.RecordType.DOCUMENT; if ( txtFileName.Text.Length >= 10 ) { txtSimpleFileName.Text = txtFileName.Text.Substring(10, txtFileName.Text.Length - 10); } enableSave(sender, e); } } /// <summary> /// Get file details from file name /// </summary> private void FileSelected(string fileName, string fullPathFileName) { // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Extract File Path string pathOnly = fullPathFileName.Replace(fileName, ""); txtFileName.Text = fileName; txtLocation.Text = pathOnly; string pathPartToCheck = ""; if (pathOnly.Length >= templateFolder.Length) pathPartToCheck = pathOnly.Substring(0, templateFolder.Length); else pathPartToCheck = pathOnly; if (pathPartToCheck != templateFolder) { txtFileName.Text = ""; txtLocation.Text = ""; MessageBox.Show("Please select file from allowed folder. " + templateFolder); return; } // Get reference path // string refPath = Utils.getReferenceFilePathName(txtLocation.Text); txtLocation.Text = refPath; // This is the name of the document and not the file name // If it is already set for the client, there is no need // to replace it. The idea here is to suggest a name only // when the document is being created. // if (string.IsNullOrEmpty(txtName.Text)) { txtName.Text = fileName.Substring(0, fileName.Length - 4); } txtFileName.Text = fileName; } private void btnNewIssue_Click(object sender, EventArgs e) { Document document = new Document(); document.UID = Convert.ToInt32( txtUID.Text ); document.CUID = txtCUID.Text; document.Location = txtLocation.Text; document.IssueNumber = Convert.ToInt32( txtIssueNumber.Text ); document.Name = txtName.Text; document.SequenceNumber = Convert.ToInt32( txtSeqNum.Text ); document.FileName = txtFileName.Text; document.ParentUID = Convert.ToInt32(txtParentUID.Text); // var response = document.NewVersion(HeaderInfo.Instance); // var response = RepDocument.NewVersion(HeaderInfo.Instance, document); // var documentNewVersionRequest = new DocumentNewVersionRequest(); documentNewVersionRequest.headerInfo = HeaderInfo.Instance; documentNewVersionRequest.inDocument = document; var respNewVersion = BUSDocument.DocumentNewVersion(documentNewVersionRequest); if (respNewVersion.response.ReturnCode != 0001) { ControllerUtils.ShowFCMMessage(respNewVersion.response.UniqueCode, Utils.UserID); return; } var i = respNewVersion.response.Contents.ToString(); MessageBox.Show("New issue #" + i + " created successfully."); txtFileName.Text = document.FileName; txtName.Text = document.Name; txtIssueNumber.Text = document.IssueNumber.ToString(); } private void btnEditDocument_Click(object sender, EventArgs e) { Utils.OpenDocument(txtLocation.Text, txtFileName.Text, cbxDocumentType.Text, vkReadOnly: true); } private void btnDirectory_Click(object sender, EventArgs e) { CodeValue cv = new CodeValue(); cv.FKCodeType = "DIRECTORY"; UIReferenceData uird = new UIReferenceData(cv); uird.ShowDialog(); //txtDirectory.Text = cv.ID; //txtDirectoryDescription.Text = cv.Description; } private void btnSubDirectory_Click(object sender, EventArgs e) { CodeValue cv = new CodeValue(); cv.FKCodeType = "SUBDIRECTORY"; UIReferenceData uird = new UIReferenceData(cv); uird.ShowDialog(); //txtSubDirectory.Text = cv.ID; //txtSubDirectoryDescription.Text = cv.Description; } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnClient_Click(object sender, EventArgs e) { UIClientList uicl = new UIClientList(this); uicl.ShowDialog(); txtClientUID.Text = Utils.ClientID.ToString(); } private void enableSave(object sender, EventArgs e) { bool enable = true; // Check conditions to enable the save if (string.IsNullOrEmpty(txtIssueNumber.Text)) enable = false; if (string.IsNullOrEmpty(txtSeqNum.Text)) enable = false; if (string.IsNullOrEmpty(txtName.Text)) enable = false; if (string.IsNullOrEmpty(txtCUID.Text)) enable = false; if (cbxRecordType.Text == FCMConstant.RecordType.FOLDER) { // file name is not mandatory for folders // } else { if (string.IsNullOrEmpty(txtFileName.Text)) enable = false; } // Enable if that's the case if (enable) tsSave.Enabled = true; else tsSave.Enabled = false; txtName.Text = UIHelper.ClientDocumentUIHelper.SetDocumentName( txtSimpleFileName.Text, txtIssueNumber.Text, txtCUID.Text, cbxRecordType.Text, txtFileName.Text); } private void cbxSourceCode_SelectedIndexChanged(object sender, EventArgs e) { if (cbxSourceCode.Text == FCMConstant.SourceCode.CLIENT) { btnClient.Enabled = true; } else { btnClient.Enabled = false; } } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void cbxRecordType_SelectedIndexChanged(object sender, EventArgs e) { btnNewIssue.Enabled = true; txtSeqNum.Enabled = true; cbxSourceCode.Enabled = true; lblDocumentUID.Text = "Document ID:"; if (cbxRecordType.Text == FCMConstant.RecordType.FOLDER) { btnNewIssue.Enabled = false; txtSeqNum.Enabled = false; cbxSourceCode.Text = FCMConstant.SourceCode.FCM; cbxSourceCode.Enabled = false; lblDocumentUID.Text = "Folder ID:"; } enableSave(sender, e); } private void cbxDocumentType_SelectedIndexChanged(object sender, EventArgs e) { } private void txtSimpleFileName_TextChanged(object sender, EventArgs e) { txtName.Text = UIHelper.ClientDocumentUIHelper.SetDocumentName( txtSimpleFileName.Text, txtIssueNumber.Text, txtCUID.Text, cbxRecordType.Text, txtFileName.Text); enableSave( sender, e ); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (_previousForm != null) _previousForm.Activate(); this.Dispose(); } private void btnEdit_Click(object sender, EventArgs e) { Utils.OpenDocument(txtLocation.Text, txtFileName.Text, cbxDocumentType.Text, vkReadOnly: false); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Interface; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.ServiceContract; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using Utils = MackkadoITFramework.Helper.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service { public class BUSClientDocument { /// <summary> /// Client document list /// </summary> /// <returns></returns> public static ClientDocumentListResponse List( ClientDocumentListRequest request ) { var response = new ClientDocumentListResponse(); response.clientList = new List<scClientDocSetDocLink>(); response.clientList = RepClientDocument.ListS( request.clientUID, request.clientDocumentSetUID ); return response; } /// <summary> /// Client document list /// </summary> /// <param name="clientDocument"> </param> /// <param name="clientID"> </param> /// <param name="clientDocumentSetUID"> </param> /// <returns></returns> public static void ListCD( ClientDocument clientDocument, int clientID, int clientDocumentSetUID ) { RepClientDocument.List( clientDocument, clientID, clientDocumentSetUID ); } /// <summary> /// Client document read /// </summary> /// <returns></returns> public static ClientDocument ClientDocumentReadS(int clientDocumentUID) { return RepClientDocument.Read( clientDocumentUID ); } /// <summary> /// Client document update /// </summary> /// <returns></returns> public static SCClientDocument.ClientDocumentUpdateResponse ClientDocumentUpdate( ClientDocument clientDocument ) { var clientDocumentUpdateResponse = new SCClientDocument.ClientDocumentUpdateResponse(); clientDocumentUpdateResponse.responseStatus = RepClientDocument.Update( clientDocument ); return clientDocumentUpdateResponse; } /// <summary> /// Client document delete multiple /// </summary> /// <returns></returns> public static ResponseStatus ClientDocumentDeleteMultiple( HeaderInfo headerInfo, int clientUID, int clientDocumentSetUID, List<int> documentIDList ) { ResponseStatus response = new ResponseStatus(); foreach (var i in documentIDList) { response = ClientDocumentDelete(headerInfo, clientUID, clientDocumentSetUID, i); } return response; } /// <summary> /// Client document delete /// </summary> /// <returns></returns> public static ResponseStatus ClientDocumentDelete( HeaderInfo headerInfo, int clientUID, int clientDocumentSetUID, int clientDocumentUID ) { string filePhysicallyRemoved = ""; // Get client document var clientDocument = RepClientDocument.Read( clientDocumentUID ); // Delete file from folder var fileNamePath = Utils.getFilePathNameLOCAL( clientDocument.clientDocumentSet.Folder + clientDocument.Location, clientDocument.FileName ); if ( File.Exists( fileNamePath ) ) { filePhysicallyRemoved = " File exists but not removed. "; try { File.Delete( fileNamePath ); filePhysicallyRemoved = " File exists and has been removed. "; } catch ( Exception ex ) { LogFile.WriteToTodaysLogFile( "Error deleting file after Remove issued" + ex ); filePhysicallyRemoved = " File exists but not removed. "; } } // Delete record from database var response = RepClientDocument.Delete( clientUID, clientDocumentSetUID, clientDocumentUID ); response.Message = response.Message.Trim() + filePhysicallyRemoved; LogFile.WriteToTodaysLogFile( response.Message + " " + clientDocument.FileName + " " + clientDocument.UID, headerInfo.UserID, "", "BUSClientDocument.cs" ); return response; } public static string NewVersion( ClientDocument clientDocument ) { return RepClientDocument.NewVersion( clientDocument ); } public static string NewVersionWeb( ClientDocument clientDocument ) { return RepClientDocument.NewVersionWeb( clientDocument ); } public static void ListProjectPlanInTree(ClientDocument clientDocument, int clientID, int clientDocumentSetUID, TreeView fileList) { RepClientDocument.ListProjectPlanInTree(clientDocument, clientID, clientDocumentSetUID, fileList); } public static void ListInTree(ClientDocument clientDocument, TreeView fileList, string listType) { RepClientDocument.ListInTree(clientDocument, fileList, listType); } public static void ListImpacted(ClientDocument clientDocument, Model.ModelDocument.Document document) { RepClientDocument.ListImpacted(clientDocument, document); } public static void AddRootFolder( ClientDocument clientDocument, int clientUID, int DocSetUID, string DestinationFolder ) { RepClientDocument.AddRootFolder(clientDocument, clientUID, DocSetUID, DestinationFolder); } public static string GetComboIssueNumber( string documentCUID, int documentVersionNumber, int clientUID ) { return RepClientDocument.GetComboIssueNumber( documentCUID, documentVersionNumber, clientUID ); } public static int GetLastClientCUID( int clientUID ) { return RepClientDocument.GetLastClientCUID( clientUID ); } public static int LinkDocumentToClientSet(scClientDocSetDocLink doco) { return RepClientDocument.LinkDocumentToClientSet(doco); } public static ResponseStatus SetToVoid(int clientUID, int clientDocumentSetUID, int documentUID) { RepClientDocument.SetToVoid(clientUID, clientDocumentSetUID, documentUID); return new ResponseStatus(); } /// <summary> /// Delete file /// </summary> /// <param name="clientDocumentUID"></param> /// <returns></returns> public static ResponseStatus DeleteFile( int clientDocumentUID ) { RepClientDocument.DeleteFile( clientDocumentUID ); return new ResponseStatus(); } /// <summary> /// Get Client Document Path /// </summary> /// <param name="clientDocument"></param> /// <returns></returns> public static ResponseStatus GetClientDocumentPath(ClientDocument clientDocument) { var response = RepClientDocument.GetDocumentPath(clientDocument); return response; } /// <summary> /// /// </summary> public class ClientDocumentListRequest { public HeaderInfo headerInfo; public int clientUID; public int clientDocumentSetUID; } /// <summary> /// /// </summary> public class ClientDocumentListResponse { public List<scClientDocSetDocLink> clientList; public ResponseStatus response; } /// <summary> /// /// </summary> public class ClientDocumentListCDResponse { public List<ClientDocument> clientList; public ResponseStatus response; } /// <summary> /// Associate documents from selected document set to selected client /// </summary> /// <param name="clientDocumentSet"> </param> /// <param name="documentSetUID"></param> /// <param name="headerInfo"> </param> public static void AssociateDocumentsToClient( ClientDocumentSet clientDocumentSet, int documentSetUID, HeaderInfo headerInfo) { // It is a new client document set // It maybe a new client, the client document set MUST be new or empty // 1) Instantiate a TREE for the Client Document Set document // 2) Instantiate a second tree for the documents related to that document set // 3) Now the old copy all starts, all the nodes from the second tree are moved to the new tree // following current process // 4) Save happens as per usual // TreeView tvFileList = new TreeView(); // This is the list of documents for a client, it should be EMPTY TreeView tvDocumentsAvailable = new TreeView(); // This is the list of documents for a client, it should be EMPTY string folderOnly = clientDocumentSet.FolderOnly; // Contains the folder location of the file // Add root folder // ClientDocument clientDocument = new ClientDocument(); // clientDocument.AddRootFolder( clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID, clientDocumentSet.FolderOnly ); RepClientDocument.AddRootFolder( clientDocument, clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID, clientDocumentSet.FolderOnly ); // List client document list !!!!!!! Important because the ROOT folder is loaded ;-) var documentSetList = new ClientDocument(); // documentSetList.List( clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID ); RepClientDocument.List( documentSetList, clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID ); tvFileList.Nodes.Clear(); // documentSetList.ListInTree(tvFileList, "CLIENT"); RepClientDocument.ListInTree(documentSetList, tvFileList, "CLIENT" ); if (tvFileList.Nodes.Count > 0) tvFileList.Nodes[0].Expand(); // Load available documents // tvDocumentsAvailable.Nodes.Clear(); // Get document list for a given document set // DocumentSet documentSet = new DocumentSet(); documentSet.UID = documentSetUID; documentSet.Read(IncludeDocuments: 'Y'); // Load document in the treeview // Model.ModelDocument.Document root = new Model.ModelDocument.Document(); // root.GetRoot(headerInfo); root = RepDocument.GetRoot(headerInfo); DocumentList.ListInTree(tvDocumentsAvailable, documentSet.documentList, root); while (tvDocumentsAvailable.Nodes[0].Nodes.Count > 0) { TreeNode tn = tvDocumentsAvailable.Nodes[0].Nodes[0]; tn.Remove(); tvFileList.Nodes[0].Nodes.Add(tn); } tvFileList.SelectedNode = tvFileList.Nodes[0]; // ------------------------------------------------------------------- // The documents have been moved from the available to client's tree // Now it is time to save the documents // ------------------------------------------------------------------- Save(clientDocumentSet, documentSetUID, tvFileList); ClientDocumentLink cloneLinks = new ClientDocumentLink(); cloneLinks.ReplicateDocSetDocLinkToClient(clientDocumentSet.FKClientUID, clientDocumentSet.ClientSetID, documentSetUID); } // ---------------------------------------------------------- // Save client documents // ---------------------------------------------------------- private static void Save( ClientDocumentSet clientDocumentSet, int documentSetUID, TreeView tvFileList ) { ClientDocument cdsl = new ClientDocument(); ClientDocumentSet docSet = new ClientDocumentSet(); var lodsl = new ListOfscClientDocSetDocLink(); lodsl.list = new List<scClientDocSetDocLink>(); // Move data into views.. int selUID = documentSetUID; docSet.Get(clientDocumentSet.FKClientUID, selUID); docSet.ClientSetID = selUID; docSet.Folder = clientDocumentSet.Folder; docSet.SourceFolder = clientDocumentSet.SourceFolder; docSet.Description = clientDocumentSet.Description; docSet.Update(); // Save complete tree... SaveTreeViewToClient(tvFileList, 0, clientDocumentSet); } // ------------------------------------------------------------------- // Saves TreeView of a client tree // ------------------------------------------------------------------- private static void SaveTreeViewToClient(TreeView treeView, int parentID, ClientDocumentSet clientDocumentSet) { foreach (TreeNode node in treeView.Nodes) { var documentLink = (scClientDocSetDocLink)node.Tag; SaveTreeNodeToClient(node, documentLink.clientDocument.UID, clientDocumentSet); } } // ------------------------------------------------------------------- // Saves TreeNode of a client tree // ------------------------------------------------------------------- private static TreeNode SaveTreeNodeToClient(TreeNode treeNode, int parentID, ClientDocumentSet clientDocumentSet) { TreeNode ret = new TreeNode(); ClientDocument cdsl = new ClientDocument(); var t = treeNode.Tag.GetType(); // If the type is not document, it is an existing document // // var documentLink = new FCMStructures.scClientDocSetDocLink(); var documentLink = new scClientDocSetDocLink(); if (t.Name == "scClientDocSetDocLink") { documentLink = (scClientDocSetDocLink)treeNode.Tag; documentLink.clientDocument.SequenceNumber = treeNode.Index; } // // If the type is Document, it means a new document added to the client // list // if (t.Name == "Document") #region Document { documentLink.document = new Model.ModelDocument.Document(); documentLink.document = (Model.ModelDocument.Document)treeNode.Tag; documentLink.clientDocument = new ClientDocument(); documentLink.clientDocumentSet = new ClientDocumentSet(); // Fill in the extra details... // documentLink.clientDocument.EndDate = System.DateTime.MaxValue; documentLink.clientDocument.FKClientDocumentSetUID = clientDocumentSet.ClientSetID; // Utils.ClientSetID; documentLink.clientDocument.FKClientUID = clientDocumentSet.FKClientUID; //Utils.ClientID; if (clientDocumentSet.FKClientUID <= 0) { MessageBox.Show("Client ID not supplied."); return null; } documentLink.clientDocument.FKDocumentUID = documentLink.document.UID; documentLink.clientDocument.Generated = 'N'; documentLink.clientDocument.SourceIssueNumber = documentLink.document.IssueNumber; documentLink.clientDocument.ClientIssueNumber = 00; // When the source is client, the name will have already all the numbers // //if (documentLink.document.SourceCode == Utils.SourceCode.CLIENT) //{ // documentLink.clientDocument.ComboIssueNumber = documentLink.document.CUID; //} //else //{ //} if (documentLink.document.RecordType == Utils.RecordType.FOLDER) { documentLink.clientDocument.ComboIssueNumber = documentLink.document.CUID; documentLink.clientDocument.FileName = documentLink.document.SimpleFileName; } else { documentLink.clientDocument.ComboIssueNumber = RepClientDocument.GetComboIssueNumber(documentLink.document.CUID, documentLink.document.IssueNumber, clientDocumentSet.FKClientUID); documentLink.clientDocument.FileName = documentLink.clientDocument.ComboIssueNumber + " " + documentLink.document.SimpleFileName; } documentLink.clientDocument.IsProjectPlan = documentLink.document.IsProjectPlan; documentLink.clientDocument.DocumentCUID = documentLink.document.CUID; documentLink.clientDocument.DocumentType = documentLink.document.DocumentType; // The client document location includes the client path (%CLIENTFOLDER%) plus the client document set id // %CLIENTFOLDER%\CLIENTSET201000001R0001\ // How to identify the parent folder // // documentLink.clientDocument.ParentUID = destFolder.clientDocument.UID; documentLink.clientDocument.ParentUID = parentID; // documentLink.clientDocument.Location = txtDestinationFolder.Text + // Utils.GetClientPathInside(documentLink.document.Location); documentLink.clientDocument.Location = GetClientDocumentLocation(parentID); documentLink.clientDocument.RecordType = documentLink.document.RecordType; documentLink.clientDocument.SequenceNumber = treeNode.Index; documentLink.clientDocument.SourceFileName = documentLink.document.FileName; documentLink.clientDocument.SourceLocation = documentLink.document.Location; documentLink.clientDocument.StartDate = System.DateTime.Today; documentLink.clientDocument.UID = 0; documentLink.clientDocumentSet.UID = clientDocumentSet.ClientSetID; // clientDocumentSet.UID; // Utils.ClientSetID; documentLink.clientDocumentSet.SourceFolder = clientDocumentSet.SourceFolder; documentLink.clientDocumentSet.ClientSetID = clientDocumentSet.ClientSetID; // Utils.ClientSetID; documentLink.clientDocumentSet.FKClientUID = clientDocumentSet.FKClientUID; documentLink.clientDocumentSet.Folder = clientDocumentSet.Folder; } #endregion Document // Save link to database // // documentLink.clientDocument.UID = cdsl.LinkDocumentToClientSet(documentLink); documentLink.clientDocument.UID = RepClientDocument.LinkDocumentToClientSet( documentLink ); foreach (TreeNode children in treeNode.Nodes) { SaveTreeNodeToClient(children, documentLink.clientDocument.UID, clientDocumentSet); } return ret; } /// <summary> /// Retrieve the parent folder for a given document /// </summary> /// <returns></returns> public static string GetClientDocumentLocation(int clientDocumentUID) { string ret = ""; var clientDocument = BUSClientDocument.ClientDocumentReadS( clientDocumentUID ); if ( clientDocument.UID > 0) { // This is to prevent the first level from taking an extra \\ at the front // it was causing the folder to be like \\%CLIENTFOLDER%\\ // At the end the client folder was replace by a physical path // and it appears like "\\c:\\fcm\\document\\" clientDocument.Location = clientDocument.Location.Trim(); if (string.IsNullOrEmpty(clientDocument.Location)) ret = clientDocument.FileName; else ret = clientDocument.Location + "\\" + clientDocument.SourceFileName; // ret = clientDocument.Location + "\\" + clientDocument.FileName; } return ret; } /// <summary> /// List of documents /// </summary> public static List<Document> ListDocumentsNotInSet( HeaderInfo headerInfo, int clientUID, int documentSetUID ) { ClientDocumentSet documentSet = new ClientDocumentSet(); documentSet.UID = documentSetUID; var documentsNotInSet = documentSet.ListDocumentsNotInSet( headerInfo, clientUID, documentSetUID ); return documentsNotInSet; } /// <summary> /// Add FCM document to Client Set /// </summary> /// <param name="headerInfo"></param> /// <param name="clientUID"></param> /// <param name="clientDocumentSetUID"></param> /// <param name="documentUID"></param> /// <returns></returns> public static ResponseStatus AddDocumentToSet( HeaderInfo headerInfo, int clientUID, int clientDocumentSetUID, int documentUID ) { string sourceFolder = ""; string destinationFolder = ""; if ( clientUID <= 0 ) return new ResponseStatus { Message = "Client UID was not supplied.", XMessageType = MessageType.Error, ReturnCode = -0020, ReasonCode = 0001}; if ( clientDocumentSetUID <= 0 ) return new ResponseStatus { Message = "Client Document Set UID was not supplied.", XMessageType = MessageType.Error, ReturnCode = -0020, ReasonCode = 0002 }; if ( documentUID <= 0 ) return new ResponseStatus { Message = "Document UID was not supplied.", XMessageType = MessageType.Error, ReturnCode = -0020, ReasonCode = 0003 }; // Find Document // DocumentReadRequest documentReadRequest = new DocumentReadRequest(); documentReadRequest.headerInfo = headerInfo; documentReadRequest.retrieveVoidedDocuments = false; documentReadRequest.UID = documentUID; var documentReadResponse = BUSDocument.DocumentRead( documentReadRequest ); var documentSelected = new Document(); documentSelected = documentReadResponse.document; // Find parent of the document // var folderReadRequestParent = new DocumentReadRequest(); folderReadRequestParent.headerInfo = headerInfo; folderReadRequestParent.retrieveVoidedDocuments = false; folderReadRequestParent.UID = documentSelected.ParentUID; // Reading parent var folderParentResponse = BUSDocument.DocumentRead( folderReadRequestParent ); var folderParent = new Document(); folderParent = folderParentResponse.document; // Find the equivalent parent in ClientDocumentSetDocument // var foundParent = RepClientDocument.Find(folderParent.UID, clientDocumentSetUID, 'N', clientUID); if ( foundParent.UID <= 0 ) return new ResponseStatus { Message = "Parent folder not found.", XMessageType = MessageType.Error, ReturnCode = -0020, ReasonCode = 0006 }; // Find ClientDocumentSet // var clientDocumentSet = new ClientDocumentSet(); clientDocumentSet.UID = clientDocumentSetUID; clientDocumentSet.FKClientUID = clientUID; clientDocumentSet.Read(); if ( clientDocumentSet.UID <= 0 ) return new ResponseStatus { Message = "Client Document Set not found.", XMessageType = MessageType.Error, ReturnCode = -0030, ReasonCode = 0004}; // Create link // var documentLink = new scClientDocSetDocLink(); if ( documentSelected.RecordType == "DOCUMENT" ) #region Document { documentLink.document = new Document(); documentLink.document = documentSelected; documentLink.clientDocument = new ClientDocument(); documentLink.clientDocumentSet = new ClientDocumentSet(); // Fill in the extra details... // documentLink.clientDocument.EndDate = System.DateTime.MaxValue; documentLink.clientDocument.FKClientDocumentSetUID = clientDocumentSet.UID; documentLink.clientDocument.FKClientUID = clientDocumentSet.FKClientUID; documentLink.clientDocument.FKDocumentUID = documentLink.document.UID; documentLink.clientDocument.Generated = 'N'; documentLink.clientDocument.SourceIssueNumber = documentLink.document.IssueNumber; documentLink.clientDocument.ClientIssueNumber = 00; if ( documentLink.document.RecordType == FCMConstant.RecordType.FOLDER ) { documentLink.clientDocument.ComboIssueNumber = documentLink.document.CUID; documentLink.clientDocument.FileName = documentLink.document.SimpleFileName; } else { documentLink.clientDocument.ComboIssueNumber = BUSClientDocument.GetComboIssueNumber( documentLink.document.CUID, documentLink.document.IssueNumber, clientDocumentSet.FKClientUID ); documentLink.clientDocument.FileName = documentLink.clientDocument.ComboIssueNumber + " " + documentLink.document.SimpleFileName; } documentLink.clientDocument.IsProjectPlan = documentLink.document.IsProjectPlan; documentLink.clientDocument.DocumentCUID = documentLink.document.CUID; documentLink.clientDocument.DocumentType = documentLink.document.DocumentType; // The client document location includes the client path (%CLIENTFOLDER%) plus the client document set id // %CLIENTFOLDER%\CLIENTSET201000001R0001\ // How to identify the parent folder // documentLink.clientDocument.ParentUID = foundParent.UID; // Daniel // 01-Jul-2013 // Retrieving the clientdocument parent using the UID for the parent clientdocument // // documentLink.clientDocument.Location = BUSClientDocument.GetClientDocumentLocation(folderReadRequestParent.UID); documentLink.clientDocument.Location = BUSClientDocument.GetClientDocumentLocation(foundParent.UID); documentLink.clientDocument.RecordType = documentLink.document.RecordType; documentLink.clientDocument.SequenceNumber = 1; documentLink.clientDocument.SourceFileName = documentLink.document.FileName; documentLink.clientDocument.SourceLocation = documentLink.document.Location; documentLink.clientDocument.StartDate = System.DateTime.Today; documentLink.clientDocument.UID = 0; documentLink.clientDocumentSet.UID = clientDocumentSetUID; documentLink.clientDocumentSet.SourceFolder = sourceFolder; documentLink.clientDocumentSet.ClientSetID = clientDocumentSet.UID; documentLink.clientDocumentSet.FKClientUID = clientDocumentSet.FKClientUID; documentLink.clientDocumentSet.Folder = destinationFolder; } #endregion Document // Save link to database // // documentLink.clientDocument.UID = cdsl.LinkDocumentToClientSet(documentLink); documentLink.clientDocument.UID = LinkDocumentToClientSet( documentLink ); return new ResponseStatus(); } /// <summary> /// This method adds a new document to a client. /// The document is not a document from the MASTER set. /// It is a specific document for the client - it will not be replaced or generated. /// This client document is not related to a MASTER document. /// </summary> /// <returns></returns> public static ResponseStatus AddNewDocumentToClient( ClientDocument clientDocument ) { var response = RepClientDocument.Add(clientDocument); return new ResponseStatus(); } /// <summary> /// List of documents /// </summary> public static ClientDocument ListClientDocumentsByFolder(int clientUID, int documentSetUID) { ClientDocumentSet documentSet = new ClientDocumentSet(); documentSet.UID = documentSetUID; var clientdocument = documentSet.ListClientDocumentsByFolder(clientUID, documentSetUID); return clientdocument; } /// <summary> /// Client document list /// </summary> /// <returns></returns> public static void ListDocuments(ClientDocument clientDocument, int clientID, int clientDocumentSetUID) { RepClientDocument.List(clientDocument, clientID, clientDocumentSetUID, " AND CD.RecordType = 'DOCUMENT' "); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Security.AccessControl; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; using MackkadoITFramework.Utils; namespace fcm.Windows.Others { public partial class UISendEmail : Form { private int emailCount; private string groupType; public UISendEmail() { InitializeComponent(); txtHTMLPath.Text = "c:/temp/LetterClient.html"; txtAttachmentLocation.Text = "c:/FCM_FINAL SafetySeminars 4page eFlyer.pdf"; txtDestination.Text = "<EMAIL>"; txtinlineAttachment.Text = "c:/temp/FCMSignature.jpg"; txtEmailCount.Text = "2"; emailCount = 2; groupType = "Client"; webBrowser1.Navigate(txtHTMLPath.Text); rbtClient.Checked = true; } private void btnShowEmail_Click(object sender, EventArgs e) { try { webBrowser1.Navigate(txtHTMLPath.Text); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void label1_Click(object sender, EventArgs e) { } private void btnSendEmail_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; string emailTO = txtDestination.Text; string emailSubject = "Free Safety Management Plan - October 2014"; switch (groupType) { case "Client": emailSubject = "Free Safety Management Plan - October 2014"; break; case "Contractor": emailSubject = "Construction Safety Workshop - October 2014 - Not to be missed"; break; } string emailBody = webBrowser1.DocumentText; string firstname = "Graham"; string finalemailBody = ""; switch (groupType) { case "Client": finalemailBody = "<html><body>" + " Hello " + firstname + " " + emailBody; break; case "Sponsor": finalemailBody = "<html><body>" + " Dear " + firstname + " " + emailBody; break; case "Presenter": finalemailBody = "<html><body>" + " Dear " + firstname + " " + emailBody; break; case "Contractor": finalemailBody = "<html><body>" + " Dear " + firstname + " " + emailBody; break; } string emailinlineAttachment = txtinlineAttachment.Text; var resp1 = FCMEmail.SendEmailSimple( iRecipient: emailTO, iSubject: emailSubject, iBody: finalemailBody, // iAttachmentLocation:txtAttachmentLocation.Text, inlineAttachment: emailinlineAttachment); Cursor.Current = Cursors.Arrow; MessageBox.Show("Done."); } private void btnToGraham_Click(object sender, EventArgs e) { txtDestination.Text = "<EMAIL>"; } private void btnToDaniel_Click(object sender, EventArgs e) { txtDestination.Text = "<EMAIL>"; } private void btnSendGroupEmail_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; SendEmailToGroup(groupType); Cursor.Current = Cursors.Arrow; // MessageBox.Show("Function has been commented out."); } private void SendEmailToGroup(string tgroupType) { emailCount = Convert.ToInt32(txtEmailCount.Text); int numberOfEmailsSent = 0; // Client string emailSubject = "Free Safety Management Plan"; // string emailSubject = "Construction Safety Workshop "; string emailBody = webBrowser1.DocumentText; var listOfClientEmail = RepClientEmail.List(tgroupType); foreach (var clientEmail in listOfClientEmail) { if (numberOfEmailsSent >= emailCount) break; if (string.IsNullOrEmpty(clientEmail.EmailAddress)) { LogFile.WriteToTodaysLogFile("Email NOT sent to : " + clientEmail.FirstName + " Empty email address ", "DM0001"); continue; } string finalemailBody = ""; switch (tgroupType) { case "Client": emailSubject = "Free Safety Management Plan - October 2014 "; finalemailBody = "<html><body>" + " Hello " + clientEmail.FirstName + " " + emailBody; break; case "Sponsor": finalemailBody = "<html><body>" + " Dear " + clientEmail.FirstName + " " + emailBody; break; case "Presenter": finalemailBody = "<html><body>" + " Dear " + clientEmail.FirstName + " " + emailBody; break; case "Contractor": emailSubject = "Construction Safety Workshop - October 2014 - Not to be missed"; finalemailBody = "<html><body>" + " Dear " + clientEmail.FirstName + " " + emailBody; break; } string emailinlineAttachment = txtinlineAttachment.Text; var resp1 = FCMEmail.SendEmailSimple( iRecipient: clientEmail.EmailAddress, iSubject: emailSubject, iBody: finalemailBody, // iAttachmentLocation: txtAttachmentLocation.Text, inlineAttachment: emailinlineAttachment); LogFile.WriteToTodaysLogFile("Email sent to : " + clientEmail.EmailAddress + " " + clientEmail.FirstName, "DM0001"); RepClientEmail.UpdateToEmailSent(clientEmail.UID); numberOfEmailsSent++; } } private void rbtClient_CheckedChanged(object sender, EventArgs e) { groupType = "Client"; ShowEmail(groupType); ListDestination(groupType); } private void rbtSponsor_CheckedChanged(object sender, EventArgs e) { groupType = "Sponsor"; ShowEmail(groupType); ListDestination(groupType); } private void rbtPresenter_CheckedChanged(object sender, EventArgs e) { groupType = "Presenter"; ShowEmail(groupType); ListDestination(groupType); } private void rbtChampion_CheckedChanged(object sender, EventArgs e) { groupType = "Contractor"; ShowEmail(groupType); ListDestination(groupType); } private void ShowEmail(string emailType) { switch (emailType) { case "Client": txtHTMLPath.Text = @"C:/I_Daniel/Dropbox/I_Projects/FCM_Projects/Workshops/Dec2014/Letters/LetterParticipant.html"; webBrowser1.Navigate(txtHTMLPath.Text); break; case "Sponsor": txtHTMLPath.Text = "c:/temp/LetterSponsor.html"; webBrowser1.Navigate(txtHTMLPath.Text); break; case "Contractor": txtHTMLPath.Text = "c:/temp/LetterContractor.html"; webBrowser1.Navigate(txtHTMLPath.Text); break; case "Presenter": txtHTMLPath.Text = "c:/temp/LetterPresenter.html"; webBrowser1.Navigate(txtHTMLPath.Text); break; case "ISS": txtHTMLPath.Text = "c:/temp/CertificateISS.html"; webBrowser1.Navigate(txtHTMLPath.Text); break; case "WSP": txtHTMLPath.Text = "c:/temp/CertificateWSP.html"; webBrowser1.Navigate(txtHTMLPath.Text); break; } } private void ListDestination(string tgroupType) { List<ClientEmail> listOfClientEmail; if (groupType == "ISS" || groupType == "WSP") listOfClientEmail = RepClientEmail.ListCertificates(tgroupType); else listOfClientEmail = RepClientEmail.List(tgroupType); txtTotalEmail.Text = listOfClientEmail.Count.ToString(); listBox1.Items.Clear(); foreach (var clientEmail in listOfClientEmail) { listBox1.Items.Add(clientEmail.FirstName +" "+ clientEmail.EmailAddress + " == " + clientEmail.Type); } } private void rbtCert2_CheckedChanged(object sender, EventArgs e) { groupType = "ISS"; ShowEmail("ISS"); ListDestination(groupType); } private void rbtCert1_CheckedChanged(object sender, EventArgs e) { groupType = "WSP"; ShowEmail("WSP"); ListDestination(groupType); } private void btnEmailCertificates_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; emailCount = Convert.ToInt32(txtEmailCount.Text); int numberOfEmailsSent = 0; string emailSubject = ""; string emailBody = webBrowser1.DocumentText; var listOfClientEmail = RepClientEmail.ListCertificates(groupType); // "Cert" foreach (var clientEmail in listOfClientEmail) { if (numberOfEmailsSent >= emailCount) break; if (string.IsNullOrEmpty(clientEmail.EmailAddress)) { LogFile.WriteToTodaysLogFile("Email NOT sent to : " + clientEmail.FirstName + " Empty email address ", "DM0001"); continue; } string finalemailBody = ""; if (clientEmail.CertificateType == "WSP") emailSubject = "Working Safely With Plant 2013 Certificate and Question and Answers"; else emailSubject = "FCM 2014 Final Construction Safety Workshop Presentations"; finalemailBody = "<html><body>" + " Dear " + clientEmail.FirstName + " " + emailBody; string emailinlineAttachment = txtinlineAttachment.Text; // iAttachmentLocation: @"C:\I_Daniel\Dropbox\I_Projects\FCM_Projects\Workshops\Dec2014\FullPresentation.pdf", var resp1 = FCMEmail.SendEmailSimple( iRecipient: clientEmail.EmailAddress, iSubject: emailSubject, iBody: finalemailBody, iAttachmentLocation: "", iAttachmentLocation2: "", inlineAttachment: emailinlineAttachment); LogFile.WriteToTodaysLogFile("Email sent to : " + clientEmail.EmailAddress + " " + clientEmail.FirstName, "DM0001"); RepClientEmail.UpdateToEmailSent(clientEmail.UID); numberOfEmailsSent++; } Cursor.Current = Cursors.Arrow; } private void UISendEmail_Load(object sender, EventArgs e) { } } } <file_sep>using System.ServiceModel; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Interface { [ServiceContract] public interface IBUSClientDetails { [OperationContract] ClientAddResponse ClientAdd(ClientAddRequest clientAddRequest); ClientUpdateResponse ClientUpdate(ClientUpdateRequest clientUpdateRequest); } } <file_sep>using System; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Interface; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public class BUSClientContract : IBUSClientContract { /// <summary> /// Client contract add /// </summary> /// <param name="clientContract"></param> /// <returns></returns> public ClientContractAddResponse ClientContractAdd(ClientContractAddRequest clientContract) { // Using Repository ClientContractAddResponse response = new ClientContractAddResponse(); response.responseStatus = RepClientContract.Insert( clientContract.headerInfo, clientContract.clientContract); return response; } /// <summary> /// Client contract list /// </summary> /// <param name="clientContractUID"> </param> /// <returns></returns> public static ResponseStatus ClientContractList(int clientContractUID) { var response = new ResponseStatus { Contents = RepClientContract.List(clientContractUID) }; return response; } /// <summary> /// Client contract read /// </summary> /// <param name="clientContractUID"> </param> /// <returns></returns> public static ResponseStatus Read(int clientContractUID) { var response = new ResponseStatus { Contents = RepClientContract.Read(clientContractUID) }; return response; } /// <summary> /// Update details of a client's contract /// </summary> /// <param name="clientContract"></param> /// <returns></returns> public ClientContractUpdateResponse ClientContractUpdate(ClientContractUpdateRequest clientContract) { // Using Repository ClientContractUpdateResponse response = new ClientContractUpdateResponse(); response.responseStatus = RepClientContract.Update( clientContract.headerInfo, clientContract.clientContract); return response; } /// <summary> /// Delete a client's contract /// </summary> /// <param name="clientContract"></param> /// <returns></returns> public static ClientContractDeleteResponse ClientContractDelete(ClientContractDeleteRequest clientContractDelete) { var response = new ClientContractDeleteResponse(); response.responseStatus = RepClientContract.Delete( clientContractDelete.headerInfo, clientContractDelete.clientContract); return response; } /// <summary> /// Client contract list /// </summary> /// <returns></returns> public static ResponseStatus GetValidContractOnDate(int clientContractUID, DateTime date) { var response = RepClientContract.GetValidContractOnDate(clientContractUID, date); return response; } } } <file_sep>CREATE DATABASE IF NOT EXISTS `management` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `management`; -- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86) -- -- Host: localhost Database: management -- ------------------------------------------------------ -- Server version 5.5.32-MariaDB /*!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 utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `usersettings` -- DROP TABLE IF EXISTS `usersettings`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `usersettings` ( `FKUserID` varchar(50) NOT NULL, `FKScreenCode` varchar(50) NOT NULL, `FKControlCode` varchar(50) NOT NULL, `FKPropertyCode` varchar(50) NOT NULL, `Value` char(10) CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`FKUserID`,`FKScreenCode`,`FKControlCode`,`FKPropertyCode`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `usersettings` -- LOCK TABLES `usersettings` WRITE; /*!40000 ALTER TABLE `usersettings` DISABLE KEYS */; INSERT INTO `usersettings` VALUES ('DM0001','CLNTDOCSET','TVCLNTDOCLIST','FONTSIZE','8.25'),('DM0001','CLNTDOCSET','TVCLNTDOCLIST','ICONSIZE','16'),('DM0001','CLNTDOCSET','TVCLNTDOCLISTDOCSET','ICONSIZE','16'); /*!40000 ALTER TABLE `usersettings` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2013-10-19 18:09:49 <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; namespace MackkadoITFramework.Security { public class SecurityRoleScreen { public string FKRoleCode { get; set; } public string FKScreenCode { get; set; } public ResponseStatus Add() { ResponseStatus response = new ResponseStatus(); response.Message = "Role Screen Linked Successfully."; response.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; DateTime _now = DateTime.Today; if (FKRoleCode == null && FKScreenCode == null) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "Role and Screen codes are mandatory."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000001; response.Contents = 0; return response; } using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO SecurityRoleScreen " + "(FKRoleCode, FKScreenCode" + ")" + " VALUES " + "( " + " @FKRoleCode " + ", @FKScreenCode " + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKRoleCode", MySqlDbType.VarChar).Value = FKRoleCode; command.Parameters.Add("@FKScreenCode", MySqlDbType.VarChar).Value = FKScreenCode; connection.Open(); command.ExecuteNonQuery(); } } return response; } /// <summary> /// Delete User Role /// </summary> /// <param name="userRoleUniqueID"></param> /// <returns></returns> public ResponseStatus Delete() { ResponseStatus ret = new ResponseStatus(); ret.Message = "User role deleted successfully"; ret.ReturnCode = 0001; ret.ReasonCode = 0001; ret.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "DELETE FROM SecurityRoleScreen " + " WHERE " + " FKRoleCode = @FKRoleCode " + " " ); try { using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@FKRoleCode", MySqlDbType.Int32).Value = FKRoleCode; connection.Open(); command.ExecuteNonQuery(); } } catch (Exception ex) { ret.Message = "Error deleting screen/role association."; ret.ReturnCode = -0010; ret.ReasonCode = 0001; ret.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000001; } } return ret; } /// <summary> /// List employees /// </summary> /// <param name="clientID"></param> public static List<SecurityRoleScreen> List(string role) { List<SecurityRoleScreen> roleList = new List<SecurityRoleScreen>(); using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + " FKRoleCode, " + " FKScreenCode " + " FROM SecurityRoleScreen " + " WHERE FKRoleCode = '{0}'", role); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { SecurityRoleScreen rolescreen = new SecurityRoleScreen(); rolescreen.FKRoleCode = reader["FKRoleCode"].ToString(); rolescreen.FKScreenCode = reader["FKScreenCode"].ToString(); roleList.Add(rolescreen); } } } } return roleList; } } } <file_sep>CREATE DATABASE IF NOT EXISTS `management` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `management`; -- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86) -- -- Host: localhost Database: management -- ------------------------------------------------------ -- Server version 5.5.32-MariaDB /*!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 utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `rdrelatedcodevalue` -- DROP TABLE IF EXISTS `rdrelatedcodevalue`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `rdrelatedcodevalue` ( `FKCodeTypeFrom` varchar(20) NOT NULL, `FKCodeValueFrom` varchar(20) NOT NULL, `FKCodeTypeTo` varchar(20) NOT NULL, `FKCodeValueTo` varchar(20) NOT NULL, `FKRelatedCodeID` varchar(20) NOT NULL, PRIMARY KEY (`FKCodeTypeFrom`,`FKCodeValueFrom`,`FKCodeTypeTo`,`FKCodeValueTo`,`FKRelatedCodeID`), KEY `FK_Destination` (`FKCodeTypeTo`,`FKCodeValueTo`), KEY `fk_relatedcodevalue_relatedcode1` (`FKRelatedCodeID`), CONSTRAINT `FK_Destination` FOREIGN KEY (`FKCodeTypeTo`, `FKCodeValueTo`) REFERENCES `rdcodevalue` (`FKCodeType`, `ID`), CONSTRAINT `fk_relatedcodevalue_relatedcode1` FOREIGN KEY (`FKRelatedCodeID`) REFERENCES `rdrelatedcode` (`RelatedCodeID`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `FK_Source` FOREIGN KEY (`FKCodeTypeFrom`, `FKCodeValueFrom`) REFERENCES `rdcodevalue` (`FKCodeType`, `ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `rdrelatedcodevalue` -- LOCK TABLES `rdrelatedcodevalue` WRITE; /*!40000 ALTER TABLE `rdrelatedcodevalue` DISABLE KEYS */; /*!40000 ALTER TABLE `rdrelatedcodevalue` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2013-10-19 18:09:48 <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UILogon : Form { public UILogon() { InitializeComponent(); } private void Logon_Leave(object sender, EventArgs e) { Application.Exit(); } private void Logon_Load(object sender, EventArgs e) { cbxDB.Items.Add(ConnString.Toshiba); cbxDB.Items.Add(ConnString.DeanPC); cbxDB.Items.Add(ConnString.HPLaptop); cbxDB.Items.Add(ConnString.Desktop); cbxDB.Items.Add(ConnString.HPMINI); cbxDB.SelectedIndex = 0; } private void Logon_FormClosed(object sender, FormClosedEventArgs e) { if ( String.IsNullOrEmpty( txtUserID.Text )) Application.Exit(); } private void btnLogon_Click(object sender, EventArgs e) { Utils.UserID = txtUserID.Text; ConnString.ConnectionString = cbxDB.SelectedItem.ToString(); Utils.ClientList = new ClientList(); Utils.ClientList.List(); this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UICompanyMetadata : Form { private string _connectionString; private string _userID; public DataTable elementSourceDataTable; public UICompanyMetadata(string userID, string connectionString) { InitializeComponent(); _connectionString = connectionString; _userID = userID; // // Create datatable // var UID = new DataColumn("UID", typeof(String)); var InformationType = new DataColumn("InformationType", typeof(String)); var FieldCode = new DataColumn("FieldCode", typeof(String)); var TableName = new DataColumn("TableName", typeof(String)); var FieldName = new DataColumn("FieldName", typeof(String)); var FilePath = new DataColumn("FilePath", typeof(String)); var FileName = new DataColumn("FileName", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(UID); elementSourceDataTable.Columns.Add(InformationType); elementSourceDataTable.Columns.Add(FieldCode); elementSourceDataTable.Columns.Add(TableName); elementSourceDataTable.Columns.Add(FieldName); elementSourceDataTable.Columns.Add(FilePath); elementSourceDataTable.Columns.Add(FileName); dgvGlobalFields.DataSource = elementSourceDataTable; } private void DocumentTemplate_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'managementDataSet.DocumentTemplateType' table. You can move, or remove it, as needed. } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void btnSaveModifications_Click(object sender, EventArgs e) { // documentTemplateTypeTableAdapter.Updatep } // ------------------------------------------------------- // This method copies one document // ------------------------------------------------------- private void btnCopyDocument_Click(object sender, EventArgs e) { openFileDialog1.Title = "Copy document FROM"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { object fromFileName = openFileDialog1.FileName; object destinationFileName = fromFileName + "_v01.doc"; var fromString = new List<string>(); var toString = new List<string>(); fromString.Add("<<Company Name>>"); toString.Add("<NAME>"); WordDocumentTasks.CopyDocument( fromFileName, destinationFileName, fromString, toString ); } } private void button1_Click(object sender, EventArgs e) { ReplicateFolderFilesReplace(); MessageBox.Show("Folder replicated successfully"); } // -------------------------------------------------------- // This method copies the whole folder structure // -------------------------------------------------------- private void btnCopyFolder_Click(object sender, EventArgs e) { string newFolder = "C:\\projects\\Systems\\TemplateCopy"; WordDocumentTasks.CopyFolder( "C:\\projects\\Research\\TestTemplate\\TemplateFrom", newFolder); var parentFolder = Directory.GetParent(newFolder); if (parentFolder != null) parentFolder.Refresh(); } // ----------------------------------------------------------------------- // This method replicates an entire folder structure including files // It also replaces the metadata by database fields // ----------------------------------------------------------------------- private void ReplicateFolderFilesReplace() { Word.ApplicationClass vkWordApp = new Word.ApplicationClass(); string sourceFolder = "C:\\projects\\Research\\TestTemplate\\TemplateFrom"; string destinationFolder = "C:\\projects\\Research\\TestTemplate\\TemplateTo"; var ts = new List<WordDocumentTasks.TagStructure>(); ts.Add(new WordDocumentTasks.TagStructure(){Tag="<<XX>>", TagValue="VV1"}); ts.Add(new WordDocumentTasks.TagStructure(){Tag="<<YY>>", TagValue="VV2"}); ts.Add(new WordDocumentTasks.TagStructure(){Tag="<<VV>>", TagValue="VV3"}); WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder); WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp); } // ------------------------------------------------------ // Display list of companies on the datatable // ------------------------------------------------------ private void loadFieldList() { elementSourceDataTable.Clear(); var compList = new CompanyList(_userID, _connectionString); compList.List(); foreach (Company company in compList.companyList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["UID"] = company.UID; elementRow["Name"] = company.Name; elementRow["Phone"] = company.Phone; elementRow["Fax"] = company.Fax; elementRow["EmailAddress"] = company.EmailAddress; elementRow["MainContactPersonName"] = company.MainContactPersonName; elementRow["Address"] = company.Address; elementSourceDataTable.Rows.Add(elementRow); } } } }<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using System.IO; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Interface; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Security; using MackkadoITFramework.Utils; using HeaderInfo = MackkadoITFramework.Utils.HeaderInfo; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace fcm.Windows { public partial class UIClientRegistration : Form, IBUSClientDetails { private Client _client; private Form _calledFrom; public UIClientRegistration(Form calledFrom, int icuid) { InitializeComponent(); _calledFrom = calledFrom; var busClientRead = BUSClient.ClientRead(new ClientReadRequest() { clientUID = icuid, headerInfo= HeaderInfo.Instance }); _client = busClientRead.client; // Load User ID // var ua = UserAccess.List(); foreach (var user in ua) { comboUserID.Items.Add(user.UserID); } // Load Contractor Size // var dsl = new DocumentSetList(); dsl.List(); foreach (var documentSet in dsl.documentSetList) { comboContractorSize.Items.Add(documentSet.UIDNameDisplay); } MapFieldsToScreen(); } public UIClientRegistration(Form calledFrom) { InitializeComponent(); _calledFrom = calledFrom; _client = new Client(HeaderInfo.Instance); // Load User ID // var ua = UserAccess.List(); foreach (var user in ua) { comboUserID.Items.Add(user.UserID); } // Load Contractor Size // var dsl = new DocumentSetList(); dsl.List(); foreach (var documentSet in dsl.documentSetList) { comboContractorSize.Items.Add(documentSet.UIDNameDisplay); } ClearScreenFields(); } private void miSave_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; SaveClient(); MapFieldsToScreen(); } private void MapFieldsToScreen() { txtUID.Text = _client.UID.ToString(CultureInfo.InvariantCulture); comboUserID.Text = _client.FKUserID; txtName.Text = _client.Name; txtLegalName.Text = _client.LegalName; comboContractorSize.Text = _client.DocSetUIDDisplay; // cbxAssociateInitialSet.Text = false; txtAddress.Text = _client.Address; txtPhone.Text = _client.Phone; txtFax.Text = _client.Fax; txtMobile.Text = _client.Mobile; txtEmailAddress.Text = _client.EmailAddress; txtContactPerson.Text = _client.MainContactPersonName; txtABN.Text = _client.ABN; txtRecordVersion.Text = _client.RecordVersion.ToString(CultureInfo.InvariantCulture); txtLogo1Location.Text = _client.Logo1Location; string logoLocation = Utils.GetPathName( txtLogo1Location.Text ); var dispLogo = _client.DisplayLogo; checkDisplayLogo.Checked = dispLogo == 'Y' ? true : false; // Get Company Logo // // logoLocation = Client.GetClientLogoLocation(client.UID); Bitmap MyImage; // Check if location exists if (File.Exists(logoLocation)) { MyImage = new Bitmap(logoLocation); pbxLogo.Image = (Image)MyImage; } else { LogFile.WriteToTodaysLogFile( " FCMERR00000009 (01)" + " Error. Client logo not found. " + logoLocation + " Client : " + _client.UID, Utils.UserID); } if (_client.clientExtraInformation != null) { if (_client.clientExtraInformation.DateToEnterOnPolicies <= DateTime.MinValue || _client.clientExtraInformation.DateToEnterOnPolicies >= DateTime.MaxValue) { _client.clientExtraInformation.DateToEnterOnPolicies = Utils.MinDate; dtpDateToEnterOnPolicies.Value = _client.clientExtraInformation.DateToEnterOnPolicies; } else { dtpDateToEnterOnPolicies.Value = _client.clientExtraInformation.DateToEnterOnPolicies; } if (_client.clientExtraInformation.ActionPlanDate <= DateTime.MinValue || _client.clientExtraInformation.ActionPlanDate >= DateTime.MaxValue) { _client.clientExtraInformation.ActionPlanDate = Utils.MinDate; dtpActionPlanDate.Value = _client.clientExtraInformation.ActionPlanDate; } else { dtpActionPlanDate.Value = _client.clientExtraInformation.ActionPlanDate; } if (_client.clientExtraInformation.CertificationTargetDate <= DateTime.MinValue || _client.clientExtraInformation.CertificationTargetDate >= DateTime.MaxValue) { _client.clientExtraInformation.CertificationTargetDate = Utils.MinDate; dtpCertificationTargetDate.Value = _client.clientExtraInformation.CertificationTargetDate; } else { dtpCertificationTargetDate.Value = _client.clientExtraInformation.CertificationTargetDate; } txtScopeOfServices.Text = _client.clientExtraInformation.ScopeOfServices; txtTimeTrading.Text = _client.clientExtraInformation.TimeTrading; txtRegionsOfOperation.Text = _client.clientExtraInformation.RegionsOfOperation; txtOperationalMeetings.Text = _client.clientExtraInformation.OperationalMeetingsFrequency; txtProjectMeetings.Text = _client.clientExtraInformation.ProjectMeetingsFrequency; } } /// <summary> /// Map fields from screen to object. /// </summary> private void MapScreenToObject() { _client.UID = Convert.ToInt32( txtUID.Text ); _client.FKUserID = comboUserID.Text; _client.Name = txtName.Text; _client.LegalName = txtLegalName.Text; _client.DocSetUIDDisplay = comboContractorSize.Text; _client.Address = txtAddress.Text; _client.Phone = txtPhone.Text; _client.Fax = txtFax.Text; _client.Mobile = txtMobile.Text; _client.EmailAddress = txtEmailAddress.Text; _client.MainContactPersonName = txtContactPerson.Text; _client.ABN = txtABN.Text; _client.RecordVersion = Convert.ToInt32( txtRecordVersion.Text ); if (_client.clientExtraInformation != null) { _client.clientExtraInformation.DateToEnterOnPolicies = dtpDateToEnterOnPolicies.Value; _client.clientExtraInformation.ActionPlanDate = dtpActionPlanDate.Value; _client.clientExtraInformation.CertificationTargetDate = dtpCertificationTargetDate.Value; _client.clientExtraInformation.ScopeOfServices = txtScopeOfServices.Text; _client.clientExtraInformation.TimeTrading = txtTimeTrading.Text; _client.clientExtraInformation.RegionsOfOperation = txtRegionsOfOperation.Text; _client.clientExtraInformation.OperationalMeetingsFrequency = txtOperationalMeetings.Text; _client.clientExtraInformation.ProjectMeetingsFrequency = txtProjectMeetings.Text; } } private void btnSave_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; SaveClient(); Cursor.Current = Cursors.Arrow; } /// <summary> /// Add/ Update client /// </summary> /// <param name="client"></param> public void SaveClient() { if (cbxAssociateInitialSet.Checked) { if (comboContractorSize.SelectedIndex < 0) { MessageBox.Show("Please select contractor size."); return; } } // Check if the client is new. // If the UID is empty, it is a new client. // If the UID is populated, it is an existing client. // if (string.IsNullOrEmpty(txtUID.Text)) _client.UID = 0; else _client.UID = Convert.ToInt32(txtUID.Text); _client.ABN = txtABN.Text; _client.Name = txtName.Text; _client.LegalName = txtLegalName.Text; _client.Address = txtAddress.Text; _client.Phone = txtPhone.Text; _client.Fax = txtFax.Text; _client.Mobile = txtMobile.Text; _client.Logo1Location = txtLogo1Location.Text; _client.Logo2Location = ""; _client.Logo3Location = ""; _client.EmailAddress = txtEmailAddress.Text; _client.MainContactPersonName = txtContactPerson.Text; _client.FKUserID = comboUserID.Text; _client.DocSetUIDDisplay = comboContractorSize.Text; _client.DisplayLogo = checkDisplayLogo.Checked ? 'Y' : 'N'; if (string.IsNullOrEmpty(_client.DocSetUIDDisplay)) { _client.FKDocumentSetUID = 0; } else { string[] part = _client.DocSetUIDDisplay.Split(';'); _client.FKDocumentSetUID = Convert.ToInt32(part[0]); } _client.DisplayLogo = checkDisplayLogo.Checked ? 'Y' : 'N'; _client.clientExtraInformation = new ClientExtraInformation(); _client.clientExtraInformation.FKClientUID = _client.UID; _client.clientExtraInformation.DateToEnterOnPolicies = dtpDateToEnterOnPolicies.Value; _client.clientExtraInformation.ActionPlanDate = dtpActionPlanDate.Value; _client.clientExtraInformation.CertificationTargetDate = dtpCertificationTargetDate.Value; _client.clientExtraInformation.ScopeOfServices = txtScopeOfServices.Text; _client.clientExtraInformation.TimeTrading = txtTimeTrading.Text; _client.clientExtraInformation.RegionsOfOperation = txtRegionsOfOperation.Text; _client.clientExtraInformation.OperationalMeetingsFrequency = txtOperationalMeetings.Text; _client.clientExtraInformation.ProjectMeetingsFrequency = txtProjectMeetings.Text; // Check if it is to add / update if (_client.UID <= 0) { string associateInitialSet = "N"; if (cbxAssociateInitialSet.Checked) associateInitialSet = "Y"; var clientAddRequest = new ClientAddRequest(); clientAddRequest.headerInfo = HeaderInfo.Instance; clientAddRequest.eventClient = _client; clientAddRequest.linkInitialSet = associateInitialSet; // var response = new BUSClient().ClientAdd(clientAddRequest); var response = ClientAdd(clientAddRequest); ControllerUtils.ShowFCMMessage(response.responseStatus, Utils.UserID); _client.UID = 0; if (response.responseStatus.Successful) { _client.UID = response.clientUID; txtUID.Text = _client.UID.ToString(); txtRecordVersion.Text = _client.RecordVersion.ToString(); } } else { var requestClientUpdate = new ClientUpdateRequest(); requestClientUpdate.headerInfo = HeaderInfo.Instance; requestClientUpdate.eventClient = _client; // var response = new BUSClient().ClientUpdate(requestClientUpdate); var response = ClientUpdate(requestClientUpdate); txtRecordVersion.Text = _client.RecordVersion.ToString(CultureInfo.InvariantCulture); ControllerUtils.ShowFCMMessage( response.response, Utils.UserID ); } // Refresh client list // Utils.ClientID = _client.UID; var responseClientList = new BUSClient().ClientList(HeaderInfo.Instance); Utils.ClientList = responseClientList.clientList; } private void tsbExit_Click(object sender, EventArgs e) { _calledFrom.Refresh(); _calledFrom.Activate(); this.Dispose(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void showDocumentsToolStripMenuItem_Click(object sender, EventArgs e) { } private void miDocuments_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtUID.Text)) return; Utils.ClientID = Convert.ToInt32(txtUID.Text); UIClientDocumentSet uicds = new UIClientDocumentSet(); uicds.Show(); } private void tsbNew_Click(object sender, EventArgs e) { ClearScreenFields(); } private void ClearScreenFields() { txtUID.Text = ""; comboUserID.Text = ""; txtName.Text = ""; txtLegalName.Text = ""; comboContractorSize.Text = ""; txtAddress.Text = ""; txtPhone.Text = ""; txtFax.Text = ""; txtMobile.Text = ""; txtEmailAddress.Text = ""; txtContactPerson.Text = ""; txtABN.Text = ""; txtRecordVersion.Text = ""; //dtpDateToEnterOnPolicies.Value = Utils.MinDate; //dtpActionPlanDate.Value = Utils.MinDate; //dtpCertificationTargetDate.Value = Utils.MinDate; dtpDateToEnterOnPolicies.Value = System.DateTime.Today; dtpActionPlanDate.Value = System.DateTime.Today; dtpCertificationTargetDate.Value = System.DateTime.Today; txtScopeOfServices.Text = ""; txtTimeTrading.Text = ""; txtRegionsOfOperation.Text = ""; txtOperationalMeetings.Text = ""; } private void pbxLogo_Click(object sender, EventArgs e) { } private void pbxLogo_DoubleClick(object sender, EventArgs e) { // Show file dialog var logoFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGOFOLDER); openFileDialog1.InitialDirectory = logoFolder; var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; // Extract File Path string pathOnly = fullPathFileName.Replace(fileName, ""); if (pathOnly.ToUpper() != logoFolder.ToUpper()) { MessageBox.Show("Logo must be selected from folder " + logoFolder); return; } txtLogo1Location.Text = FCMConstant.SYSFOLDER.LOGOFOLDER + fileName; Bitmap MyImage; pbxLogo.SizeMode = PictureBoxSizeMode.StretchImage; if (logoFolder != null) { // MyImage = new Bitmap(rmd.Condition); string logoLocation = logoFolder + fileName; try { MyImage = new Bitmap(logoLocation); pbxLogo.Image = (Image)MyImage; } catch (Exception ex) { MessageBox.Show("Error importing file. Please try another file type. File Location: " + logoLocation + " >> System Message " + ex.ToString()); } } } } private void OLDLogoDoubleClick(object sender, EventArgs e) { // Show file dialog var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; // Extract File Path string pathOnly = fullPathFileName.Replace(fileName, ""); // Get Company Logo // ReportMetadata rmd = new ReportMetadata(); rmd.ClientUID = Utils.ClientID; rmd.RecordType = FCMConstant.MetadataRecordType.CLIENT; rmd.FieldCode = "COMPANYLOGO"; rmd.Read(clientUID: Utils.ClientID, fieldCode: "COMPANYLOGO"); rmd.InformationType = MackkadoITFramework.Helper.Utils.InformationType.IMAGE; rmd.ClientType = ""; rmd.CompareWith = ""; rmd.Description = "Company"; // rmd.Condition = fullPathFileName; var logoFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGOFOLDER); // rmd.Condition = logoFolder + fileName; // The intention is to save the reference path %XXX% // rmd.Condition = FCMConstant.SYSFOLDER.LOGOFOLDER + fileName; txtLogo1Location.Text = rmd.Condition; rmd.Save(); Bitmap MyImage; pbxLogo.SizeMode = PictureBoxSizeMode.StretchImage; if (rmd.Condition != null) { // MyImage = new Bitmap(rmd.Condition); string logoLocation = logoFolder + fileName; MyImage = new Bitmap(logoLocation); pbxLogo.Image = (Image)MyImage; } } } private void tsmMetadata_Click(object sender, EventArgs e) { UIClientMetadata ucm = new UIClientMetadata(this); ucm.Show(); } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { var answer = MessageBox.Show("Are you sure? Do you really want to delete the client?", "Delete Client", MessageBoxButtons.YesNo); if (answer == DialogResult.Yes) { Client client = new Client(HeaderInfo.Instance); client.UID = Convert.ToInt32( txtUID.Text ); var response = new BUSClient().ClientDelete( new ClientDeleteRequest() { clientUID = client.UID, headerInfo = HeaderInfo.Instance }); ControllerUtils.ShowFCMMessage(response.responseStatus, Utils.UserID); } } private void tsRefresh_Click(object sender, EventArgs e) { ClientReadRequest crr = new ClientReadRequest(); crr.clientUID = _client.UID; var crresponse = BUSClient.ClientRead( crr ); _client = crresponse.client; //var bclient = _client.Read(); //if (_client == null) // _client = new Client(HeaderInfo.Instance); MapFieldsToScreen(); MessageBox.Show("Client details reloaded from database."); } private void UIClientRegistration_Load(object sender, EventArgs e) { } private void tsEmployees_Click(object sender, EventArgs e) { UIClientEmployee uce = new UIClientEmployee(_client); uce.Show(); } private void label12_Click(object sender, EventArgs e) { } public ClientAddResponse ClientAdd(ClientAddRequest clientAddRequest) { var response = new BUSClient().ClientAdd(clientAddRequest); return response; } public ClientUpdateResponse ClientUpdate(ClientUpdateRequest clientUpdateRequest) { var response = new BUSClient().ClientUpdate(clientUpdateRequest); return response; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Windows { public partial class UIReportMetadata : Form { private string _userID; public DataTable elementSourceDataTable; public UIReportMetadata(string userID) { InitializeComponent(); this._userID = userID; // // Create datatable // var UID = new DataColumn("UID", typeof(String)); var RecordType = new DataColumn("RecordType", typeof(String)); var FieldCode = new DataColumn("FieldCode", typeof(String)); var Description = new DataColumn("Description", typeof(String)); var ClientType = new DataColumn("ClientType", typeof(String)); var ClientUID = new DataColumn("ClientUID", typeof(String)); var InformationType = new DataColumn("InformationType", typeof(String)); var TableName = new DataColumn("TableName", typeof(String)); var FieldName = new DataColumn("FieldName", typeof(String)); var FilePath = new DataColumn("FilePath", typeof(String)); var FileName = new DataColumn("FileName", typeof(String)); elementSourceDataTable = new DataTable("ElementSourceDataTable"); elementSourceDataTable.Columns.Add(UID); elementSourceDataTable.Columns.Add(RecordType); elementSourceDataTable.Columns.Add(FieldCode); elementSourceDataTable.Columns.Add(Description); elementSourceDataTable.Columns.Add(ClientType); elementSourceDataTable.Columns.Add(ClientUID); elementSourceDataTable.Columns.Add(InformationType); elementSourceDataTable.Columns.Add(TableName); elementSourceDataTable.Columns.Add(FieldName); elementSourceDataTable.Columns.Add(FilePath); elementSourceDataTable.Columns.Add(FileName); dgvClientMetadata.DataSource = elementSourceDataTable; } private void btnList_Click(object sender, EventArgs e) { loadMetadataList(0); } private void UIGeneralMetadata_Load(object sender, EventArgs e) { ucReportMetadata1.Visible = false; // Pass this instance to the component to enable the manipulation/refresh // of the list // ucReportMetadata1.SetUIReportInst(this); loadMetadataList(0); } // Toggle edit screen private void btnEditValue_Click(object sender, EventArgs e) { EditMetadata(false); } // Toggle edit screen private void dgvClientMetadata_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { EditMetadata(false); } // Update contents only private void dgvClientMetadata_CellContentClick(object sender, DataGridViewCellEventArgs e) { EditMetadata(true); } // Using keyboard to change private void dgvClientMetadata_SelectionChanged(object sender, EventArgs e) { EditMetadata(true); } private void dgvClientMetadata_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { EditMetadata(false); } private void btnDetails_Click(object sender, EventArgs e) { EditMetadata(false); } private void ucReportMetadata1_Load(object sender, EventArgs e) { } // // List companies // public void loadMetadataList(int iUID) { elementSourceDataTable.Clear(); int rts = 0; int cnt = 0; var metaList = new ReportMetadataList(_userID); metaList.List(); foreach (ReportMetadata metadata in metaList.reportMetadataList) { DataRow elementRow = elementSourceDataTable.NewRow(); elementRow["UID"] = metadata.UID; elementRow["RecordType"] = metadata.RecordType; elementRow["FieldCode"] = metadata.FieldCode; elementRow["Description"] = metadata.Description; elementRow["ClientType"] = metadata.ClientType; elementRow["ClientUID"] = metadata.ClientUID; elementRow["InformationType"] = metadata.InformationType; elementRow["TableName"] = metadata.TableName; elementRow["FieldName"] = metadata.FieldName; elementRow["FilePath"] = metadata.FilePath; elementRow["FileName"] = metadata.FileName; elementSourceDataTable.Rows.Add(elementRow); if (metadata.UID == iUID) rts = cnt; cnt++; } dgvClientMetadata.Rows[rts].Selected = true; } // // // private void EditMetadata(bool RefreshOnly) { if (!RefreshOnly) { if (ucReportMetadata1.Visible == true) { ucReportMetadata1.Visible = false; loadMetadataList(0); return; } ucReportMetadata1.Visible = true; } if (dgvClientMetadata.SelectedRows.Count <= 0) return; var selectedRow = dgvClientMetadata.SelectedRows; ReportMetadata rm = new ReportMetadata(); rm.UID = Convert.ToInt32(selectedRow[0].Cells["UID"].Value); rm.RecordType = selectedRow[0].Cells["RecordType"].Value.ToString(); rm.FieldCode = selectedRow[0].Cells["FieldCode"].Value.ToString(); rm.ClientType = selectedRow[0].Cells["ClientType"].Value.ToString(); rm.Description = selectedRow[0].Cells["Description"].Value.ToString(); rm.ClientUID = Convert.ToInt32( selectedRow[0].Cells["ClientUID"].Value); rm.InformationType = selectedRow[0].Cells["InformationType"].Value.ToString(); rm.TableName = selectedRow[0].Cells["TableName"].Value.ToString(); rm.FieldName = selectedRow[0].Cells["FieldName"].Value.ToString(); rm.FilePath = selectedRow[0].Cells["FilePath"].Value.ToString(); rm.FileName = selectedRow[0].Cells["FileName"].Value.ToString(); ucReportMetadata1.SetValues(rm); } private void miEdit_Click(object sender, EventArgs e) { EditMetadata(false); } private void miDelete_Click(object sender, EventArgs e) { } } } <file_sep>CREATE DATABASE IF NOT EXISTS `management` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `management`; -- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86) -- -- Host: localhost Database: management -- ------------------------------------------------------ -- Server version 5.5.32-MariaDB /*!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 utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `securityuser` -- DROP TABLE IF EXISTS `securityuser`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `securityuser` ( `UserID` varchar(50) NOT NULL, `Password` varchar(50) NOT NULL, `Salt` varchar(50) NOT NULL, `UserName` varchar(50) DEFAULT NULL, `LogonAttempts` int(11) DEFAULT NULL, PRIMARY KEY (`UserID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `securityuser` -- LOCK TABLES `securityuser` WRITE; /*!40000 ALTER TABLE `securityuser` DISABLE KEYS */; INSERT INTO `securityuser` VALUES ('CLIENT01','136','21','CLIENT01',0),('DAN','113','8','DAN',5),('DAN2','163','20','Dan2',0),('DanielLuiz','113','19','<NAME>',0),('DM0001','163','19','<NAME>',0),('DM0022','113','17','Daniel Machado User',0),('dm0023','113','17','Daniel Machado User',0),('dm0024','113','17','<NAME>',0),('dm0025','113','17','<NAME>',0),('dm0027','113','17','<NAME>',0),('dm0030','113','19','Daniel',0),('dm0031','113','19','daniel',0),('dm0040','113','19','Daniel 40',0),('dm0041','113','19','Daniel',0),('dm0042','113','19','daniel',0),('dm0043','113','19','daniel',0),('dm0044','113','19','daniel',0),('dm0045','113','19','daniel',0),('dm0046','113','20','daniel',0),('dm0050','113','20','daniel',0),('dm0060','113','20','daniel',0),('dm0070','113','20','daniel',0),('dm0100','113','21','daniel',0),('dm0200','113','22','daniel',0),('DM0300','113','7','DANIEL 0300',0),('dm0400','113','7','daniel 0400',0),('GC0001','134','23','<NAME>',0); /*!40000 ALTER TABLE `securityuser` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2013-10-19 18:09:53 <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.Security { public class SecurityUserRole { public int UniqueID { get; set; } public string FK_UserID { get; set; } public string FK_Role { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string IsActive { get; set; } public string IsVoid { get; set; } private HeaderInfo _headerInfo; public List<SecurityUserRole> securityUserRoles { get; set; } public string ListForUserID { get; set; } public struct FieldName { public const string UniqueID = "UniqueID"; public const string FK_UserID = "FK_UserID"; public const string FK_Role = "FK_Role"; public const string IsActive = "IsActive"; } public SecurityUserRole() { } public SecurityUserRole(HeaderInfo headerInfo) { _headerInfo = headerInfo; } public bool UserHasAccessToRole(string userid, string roleToCheck ) { var roleList = UserRoleList(userid); foreach (var role in roleList) { if (role.FK_Role == roleToCheck) return true; } return false; } public List<SecurityUserRole> UserRoleList( string userid ) { List<SecurityUserRole> rolelist = new List<SecurityUserRole>(); securityUserRoles = new List<SecurityUserRole>(); using (var connection = new MySqlConnection( ConnString.ConnectionStringFramework )) { var commandString = string.Format( " SELECT " + " UniqueID " + " ,FK_UserID " + " ,FK_Role " + " ,StartDate " + " ,EndDate " + " ,IsActive " + " ,IsVoid " + " FROM SecurityUserRole " + " WHERE FK_UserID = '{0}' AND IsActive='Y' ", userid ); using (var command = new MySqlCommand( commandString, connection )) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { SecurityUserRole SecurityUserRole = new SecurityUserRole(_headerInfo); SecurityUserRole.UniqueID = Convert.ToInt32( reader["UniqueID"].ToString() ); SecurityUserRole.FK_UserID = reader["FK_UserID"].ToString(); SecurityUserRole.FK_Role = reader["FK_Role"].ToString(); SecurityUserRole.StartDate = Convert.ToDateTime( reader["StartDate"].ToString() ); SecurityUserRole.EndDate = Convert.ToDateTime( reader["EndDate"] ); SecurityUserRole.IsActive = reader["IsActive"].ToString(); SecurityUserRole.IsVoid = reader["IsVoid"].ToString(); rolelist.Add( SecurityUserRole ); securityUserRoles.Add( SecurityUserRole ); } } } } return rolelist; } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = "SELECT MAX(UniqueID) LASTUID FROM SecurityUserRole"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add Role to User /// </summary> public ResponseStatus Add() { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item added successfully."; ret.ReturnCode = 0001; ret.ReasonCode = 0001; ret.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000002; int nextID = GetLastUID() + 1; StartDate = System.DateTime.Today; EndDate = System.DateTime.MaxValue; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO SecurityUserRole " + "(UniqueID, FK_UserID, FK_Role, StartDate, EndDate, IsActive, IsVoid)" + " VALUES " + "( " + " @UniqueID " + ", @FK_UserID " + ", @FK_Role " + ", @StartDate " + ", @EndDate " + ", @IsActive " + ", @IsVoid " + " )" ); /* INSERT INTO SecurityUserRole (UniqueID, FK_UserID, FK_Role, StartDate, EndDate, IsActive, IsVoid ) VALUES ( 1 , "DM0001", "ADMIN", '2012-02-19', '2012-12-31', "Y", "N" ) */ using (var command = new MySqlCommand(commandString, connection)) { command.Parameters.AddWithValue("@UniqueID", nextID); command.Parameters.AddWithValue("@FK_UserID", FK_UserID); command.Parameters.AddWithValue("@FK_Role", FK_Role); command.Parameters.AddWithValue("@StartDate", StartDate); command.Parameters.AddWithValue("@EndDate", "9999-12-31"); command.Parameters.AddWithValue("@IsActive", "Y"); command.Parameters.AddWithValue("@IsVoid", "N"); connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// Delete User Role /// </summary> /// <param name="userRoleUniqueID"></param> /// <returns></returns> public ResponseStatus Delete() { ResponseStatus ret = new ResponseStatus(); ret.Message = "User role deleted successfully"; ret.ReturnCode = 0001; ret.ReasonCode = 0001; ret.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000003; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "DELETE FROM SecurityUserRole " + " WHERE " + " UniqueID = @UniqueID " + " " ); try { using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UniqueID", MySqlDbType.Int32).Value = UniqueID; connection.Open(); command.ExecuteNonQuery(); } } catch (Exception ex) { LogFile.WriteToTodaysLogFile( ex.ToString(), _headerInfo.UserID, "", "SecurityUserRole.cs"); return new ResponseStatus(MessageType.Error) { ReturnCode = -0010, ReasonCode = 0001, Message = "Error deleting user role.", UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000002 }; } } return ret; } /// <summary> /// List user settings for a given user /// </summary> /// <returns></returns> public ResponseStatus ListRoleForUser(string userID, List<SecurityUserRole> roleList) { using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = string.Format( " SELECT " + FieldName.FK_UserID + "," + FieldName.FK_Role + " " + " FROM SecurityUserRole " + " WHERE FK_UserID = '{0}' "+ " ORDER BY FK_Role ASC ", userID ); using (var command = new MySqlCommand( commandString, connection)) { try { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var userRole = new SecurityUserRole(_headerInfo); userRole.FK_UserID = reader[FieldName.FK_UserID].ToString(); userRole.FK_Role = reader[FieldName.FK_Role].ToString(); // Check if document exists // roleList.Add(userRole); } } } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), HeaderInfo.Instance.UserID); } } } return new ResponseStatus(); } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> private static string SQLConcat() { string ret = " " + FieldName.FK_UserID + "," + FieldName.FK_Role + " "; return ret; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.Windows.Forms; using System.Collections.Generic; using System.Linq; using FCMMySQLBusinessLibrary.Repository; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; using System.IO; namespace FCMMySQLBusinessLibrary.Model.ModelClientDocument { public class ClientDocument { #region properties public ClientDocumentSet clientDocumentSet { get; set; } public List<scClientDocSetDocLink> clientDocSetDocLink { get; set; } public List<ClientDocument> clientDocumentList { get; set; } public int UID { get; set; } [Display( Name = "Document Unique ID" )] public string DocumentCUID { get { return _DocumentCUID; } set { _DocumentCUID = value; if (_DocumentCUID.Trim().ToUpper() == "ROOT") IsRoot = 'Y'; else IsRoot = 'N'; } } [Display( Name = "Client Identifier" )] public int FKClientUID { get; set; } [Display( Name = "Client Document Set Identifier" )] public int FKClientDocumentSetUID { get; set; } [Display( Name = "Document Identifier" )] public int FKDocumentUID { get; set; } [Display( Name = "Source Location" )] public string SourceLocation { get; set; } [Display( Name = "Source File Name" )] public string SourceFileName { get; set; } [Display( Name = "Location" )] public string Location { get; set; } [Display( Name = "File Name" )] public string FileName { get; set; } [Display( Name = "Source Issue Number" )] public int SourceIssueNumber { get; set; } [Display( Name = "Client Version Number" )] public int ClientIssueNumber { get; set; } [Display( Name = "Sequence Number" )] public int SequenceNumber { get; set; } [Display( Name = "Generated" )] public char Generated { get; set; } [Display( Name = "Source File Present" )] public char SourceFilePresent { get; set; } [Display( Name = "Destination File Present" )] public char DestinationFilePresent { get; set; } [Display( Name = "Start Date" )] public DateTime StartDate { get; set; } [Display( Name = "End Date" )] public DateTime EndDate { get; set; } [Display( Name = "Record Type" )] public string RecordType { get { return _RecordType; } set { _RecordType = value; if (_RecordType.Trim() == FCMConstant.RecordType.FOLDER) IsFolder = 'Y'; else IsFolder = 'N'; } } [Display( Name = "Parent UID" )] public int ParentUID { get; set; } [Display( Name = "Is Project Plan" )] public string IsProjectPlan { get; set; } [Display( Name = "Document Type" )] public string DocumentType { get; set; } [Display( Name = "Combo Issue Number" )] public string ComboIssueNumber { get; set; } [Display( Name = "Is Void" )] public char IsVoid { get; set; } [Display( Name = "Is Root" )] public char IsRoot { get; set; } [Display( Name = "Is Folder" )] public char IsFolder { get; set; } [Display( Name = "Is Checked" )] public bool IsChecked { get; set; } [Display( Name = "Is Locked" )] public char IsLocked { get; set; } [Display( Name = "Generation Message" )] public string GenerationMessage { get; set; } #endregion properties #region attributes private string _DocumentCUID; private string _RecordType; #endregion attributes public ClientDocument() { clientDocumentSet = new ClientDocumentSet(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.Service; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; namespace fcm.Components { public partial class UCDocumentList : UserControl { public UCDocumentList(string mode, string listType) { InitializeComponent(); if (mode == FCMConstant.DocumentListMode.SELECT) { btnKeep.Visible = false; btnSaveSet.Visible = false; btnRemove.Visible = false; } if (listType == FCMConstant.DocumentListType.FCM) { cbxDocumentSet.Visible = false; label1.Visible = false; } if (listType == FCMConstant.DocumentListType.DOCUMENTSET) { cbxDocumentSet.Visible = true; label1.Visible = true; } } private void UCDocumentList_Load(object sender, EventArgs e) { DocumentSetList dsl = new DocumentSetList(); dsl.ListInComboBox(cbxDocumentSet); cbxDocumentSet.SelectedIndex = 0; SelectIndexChanged(); } public void loadDocumentList() { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvFileList.ImageList = imageList; // Clear nodes tvFileList.Nodes.Clear(); var docoList = new DocumentList(); docoList.List(); // Load document in the treeview // // docoList.ListInTree(tvFileList); Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); // root = RepDocument.Read(false,0, "ROOT"); // Using Business Layer root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvFileList, docoList, root); // tvFileList.ExpandAll(); tvFileList.Nodes[0].Expand(); } public void loadDocumentList(int documentSetUID = 0) { // Image list // ImageList imageList = ControllerUtils.GetImageList(); // Binding tvFileList.ImageList = imageList; // Clear nodes tvFileList.Nodes.Clear(); var docoList = new DocumentList(); docoList.ListDocSet(documentSetUID); // Load document in the treeview // Document root = new Document(); root.CUID = "ROOT"; root.RecordType = FCMConstant.RecordType.FOLDER; root.UID = 0; // root.Read(); //root = RepDocument.Read(false, 0, "ROOT"); root = BUSDocument.GetRootDocument(); DocumentList.ListInTree(tvFileList, docoList, root); tvFileList.Nodes[0].Expand(); } private void cbxDocumentSet_SelectedIndexChanged(object sender, EventArgs e) { SelectIndexChanged(); } // Handles the selection index change // private void SelectIndexChanged() { int documentSetUID = 0; if (string.IsNullOrEmpty(cbxDocumentSet.Text) || cbxDocumentSet.Visible == false ) { documentSetUID = 0; } else { string[] ArrayDocSetText = cbxDocumentSet.Text.Split(';'); documentSetUID = Convert.ToInt32(ArrayDocSetText[0]); } if (documentSetUID == 0) loadDocumentList(); else loadDocumentList(documentSetUID); } private void groupBox1_Enter(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.APIDocument; using MackkadoITFramework.ReferenceData; using MakUtils = MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Interfaces; using MakHelperUtils = MackkadoITFramework.Helper.Utils; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.APIDocument; using FCMUtils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace FCMMySQLBusinessLibrary.FCMUtils { public static class Utils { public static ImageList imageList; private static string userID; private static int clientID; private static int clientSetID; private static string clientSetText; private static string clientName; private static List<Client> clientList; private static int clientIndex; private static int imageLogoStartsFrom; // private static string fcmenvironment; private static UserSettings _UserSettingsCache; public static DateTime MinDate { get { return new DateTime(1901, 01, 01); } } public static UserSettings UserSettingsCache { set { _UserSettingsCache = value; } get { return _UserSettingsCache; } } /// <summary> /// Read or Write the userID in memory. /// </summary> public static string UserID { set { userID = value; // Save last user id to database CodeValue cv = new CodeValue(); cv.FKCodeType = "LASTINFO"; cv.ID = "USERID"; cv.Read(false); cv.ValueExtended = Utils.UserID; cv.Save(); } get { return userID; } } public static string ClientSetText { set { clientSetText = value; } get { return clientSetText; } } public static int ClientID { set { clientID = value; // Save last user id to database CodeValue cv = new CodeValue(); cv.FKCodeType = "LASTINFO"; cv.ID = "CLIENTID"; cv.Read(false); cv.ValueExtended = Utils.ClientID.ToString(); cv.Save(); if (clientList == null) return; int c=0; foreach (var client in clientList) { if (client.UID == clientID) { Utils.clientIndex = c; break; } c++; } } get { return clientID; } } public static int ClientSetID { set { clientSetID = value; } get { return clientSetID; } } public static int ClientIndex { // set { clientIndex = value; } get { return clientIndex; } } public static string ClientName { set { clientName = value; } get { return clientName; } } public static int ImageLogoStartsFrom { set { imageLogoStartsFrom = value; } get { return imageLogoStartsFrom; } } public static List<Client> ClientList { set { clientList = value; } get { return clientList; } } public static string FCMenvironment { get; set; } // Print document for Location and Name // public static void PrintDocument( string Location, string Name, string Type ) { if (Type == MackkadoITFramework.Helper.Utils.DocumentType.WORD) { string filePathName = Utils.getFilePathName( Location, Name ); WordDocumentTasks.PrintDocument( filePathName ); } if (Type == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL) { string filePathName = Utils.getFilePathName( Location, Name ); var Response = ExcelSpreadsheetTasks.PrintDocument( filePathName ); if (Response.ReturnCode < 1) { MessageBox.Show( Response.Message ); } } if (Type == MackkadoITFramework.Helper.Utils.DocumentType.PDF) { string filePathName = Utils.getFilePathName( Location, Name ); System.Diagnostics.Process proc = new System.Diagnostics.Process(); var adobe = CodeValue.GetCodeValueExtended( iCodeType: FCMConstant.CodeTypeString.SYSTSET, iCodeValueID: "PDFEXEPATH" ); if (!File.Exists( adobe )) { MessageBox.Show( "I can't find Adobe Reader. Please configure SYSTSET.PDFEXTPATH." ); return; } proc.StartInfo.FileName = adobe ; // Print PDF proc.StartInfo.Arguments = " /h /p "+ filePathName; proc.Start(); } } /// <summary> /// Compare documents /// </summary> /// <param name="Location"></param> /// <param name="Name"></param> /// <param name="Type"></param> /// <param name="DestinationFile"></param> public static void CompareDocuments( string Source, string Destination, string Type) { if (Type == MackkadoITFramework.Helper.Utils.DocumentType.WORD) { WordDocumentTasks.CompareDocuments(Source, Destination); } } // It transforms the reference path into a physical path and add name to it // public static string getFilePathName( string path, string name ) { string filePathName = path + "\\" + name; string fullPathFileName = ""; var fcmPort = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, MackkadoITFramework.Helper.Utils.SYSTSET.WEBPORT); var fcmHost = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, MackkadoITFramework.Helper.Utils.SYSTSET.HOSTIPADDRESS); // Get template folder var templateFolder = CodeValue.GetCodeValueExtended("SYSTSET", FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Get template folder var clientFolder = CodeValue.GetCodeValueExtended("SYSTSET", FCMConstant.SYSFOLDER.CLIENTFOLDER); // Get version folder var versionFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.VERSIONFOLDER); // Get logo folder var logoFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGOFOLDER); // Get log file folder var logFileFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGFILEFOLDER); // WEB if (Utils.FCMenvironment == MackkadoITFramework.Helper.Utils.EnvironmentList.WEB) { string rpath = path.Replace(@"\", @"/"); path = rpath; // Different for WEB filePathName = path + @"/" + name; // ---------------------- // Get WEB template folder // ---------------------- templateFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.WEBTEMPLATEFOLDER ); templateFolder = templateFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.WEBPORT, fcmPort); templateFolder = templateFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.HOSTIPADDRESS, fcmHost); // ---------------------- // Get WEB client folder // ---------------------- clientFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.WEBCLIENTFOLDER ); clientFolder = clientFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.WEBPORT, fcmPort); clientFolder = clientFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.HOSTIPADDRESS, fcmHost); // ---------------------- // Get WEB version folder // ---------------------- versionFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.WEBVERSIONFOLDER ); versionFolder = versionFolder.Replace( MackkadoITFramework.Helper.Utils.SYSTSET.WEBPORT, fcmPort ); versionFolder = versionFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.HOSTIPADDRESS, fcmHost); // ---------------------- // Get WEB logo folder // ---------------------- logoFolder = CodeValue.GetCodeValueExtended( FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.WEBLOGOFOLDER ); logoFolder = logoFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.WEBPORT, fcmPort); logoFolder = logoFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.HOSTIPADDRESS, fcmHost); // -------------------------------------------------------------- // Get WEB LOG folder - This is LOG for recording what happened // -------------------------------------------------------------- logFileFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGFILEFOLDER); logFileFolder = logFileFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.WEBPORT, fcmPort); logFileFolder = logFileFolder.Replace(MackkadoITFramework.Helper.Utils.SYSTSET.HOSTIPADDRESS, fcmHost); } if (filePathName.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { fullPathFileName = filePathName.Replace( FCMConstant.SYSFOLDER.TEMPLATEFOLDER, templateFolder ); } if (filePathName.Contains(FCMConstant.SYSFOLDER.CLIENTFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.CLIENTFOLDER, clientFolder); } if (filePathName.Contains(FCMConstant.SYSFOLDER.VERSIONFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.VERSIONFOLDER, versionFolder); } if (filePathName.Contains( FCMConstant.SYSFOLDER.LOGOFOLDER)) { fullPathFileName = filePathName.Replace( FCMConstant.SYSFOLDER.LOGOFOLDER, logoFolder); } if (filePathName.Contains(FCMConstant.SYSFOLDER.LOGFILEFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.LOGFILEFOLDER, logFileFolder); } if (string.IsNullOrEmpty(fullPathFileName)) fullPathFileName = path + "\\" + name; fullPathFileName = fullPathFileName.Replace("\r", ""); return fullPathFileName; } // It transforms the reference path into a physical path and add name to it // public static string GetPathName(string path) { string filePathName = path; string fullPathFileName = ""; // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Get main client folder var clientFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.CLIENTFOLDER); // Get version folder var versionFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.VERSIONFOLDER); // Get logo folder var logoFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGOFOLDER); if (filePathName.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.TEMPLATEFOLDER, templateFolder); } if (filePathName.Contains(FCMConstant.SYSFOLDER.CLIENTFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.CLIENTFOLDER, clientFolder); } if (filePathName.Contains(FCMConstant.SYSFOLDER.VERSIONFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.VERSIONFOLDER, versionFolder); } if (filePathName.Contains(FCMConstant.SYSFOLDER.LOGOFOLDER)) { fullPathFileName = filePathName.Replace(FCMConstant.SYSFOLDER.LOGOFOLDER, logoFolder); } return fullPathFileName; } // // It returns a reference path // public static string getReferenceFilePathName(string path) { string filePathName = path; string referencePathFileName = ""; // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Get template folder var clientFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.CLIENTFOLDER); if (filePathName.Contains(templateFolder)) { referencePathFileName = filePathName.Replace(templateFolder, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); } if (filePathName.Contains(clientFolder)) { referencePathFileName = filePathName.Replace(clientFolder, FCMConstant.SYSFOLDER.CLIENTFOLDER); } if (string.IsNullOrEmpty(referencePathFileName)) referencePathFileName = path; return referencePathFileName; } /// <summary> /// It returns the opposite path (client to template or vice-versa) /// </summary> /// <param name="path"></param> /// <returns></returns> public static string getOppositePath(string path) { string filePathName = path; string opposite = ""; if (filePathName.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { opposite = filePathName.Replace(FCMConstant.SYSFOLDER.TEMPLATEFOLDER, FCMConstant.SYSFOLDER.CLIENTFOLDER); } if (filePathName.Contains(FCMConstant.SYSFOLDER.CLIENTFOLDER)) { opposite = filePathName.Replace(FCMConstant.SYSFOLDER.CLIENTFOLDER, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); } if (string.IsNullOrEmpty(opposite)) opposite = path; return opposite; } /// <summary> /// It returns the path of the document inside the client path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetClientPathInside(string path) { string filePathName = path; string opposite = ""; if (filePathName.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { opposite = filePathName.Replace(FCMConstant.SYSFOLDER.TEMPLATEFOLDER, ""); } //if (string.IsNullOrEmpty(opposite)) // opposite = path; return opposite; } /// <summary> /// It returns the Client path /// </summary> /// <param name="path"></param> /// <param name="destinationPath"></param> /// <returns></returns> public static string GetClientPath(string path, string destinationPath) { string destination = ""; string ultimateDestination = ""; if (path.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { destination = path.Replace(FCMConstant.SYSFOLDER.TEMPLATEFOLDER, FCMConstant.SYSFOLDER.CLIENTFOLDER); } // path = %TEMPLATEFOLDER%\\something\\ // destinationPath = %CLIENTFOLDER%\\CLIENT01\\ // destination = %CLIENTFOLDER%\\something\\ // // stripDestination = \\something\\ string stripDestination = destination.Replace(FCMConstant.SYSFOLDER.CLIENTFOLDER, ""); // ultimateDestination = \\Client01\\ ultimateDestination = destinationPath.Replace(FCMConstant.SYSFOLDER.CLIENTFOLDER, ""); ultimateDestination = FCMConstant.SYSFOLDER.CLIENTFOLDER + // %CLIENTFOLDER% ultimateDestination + // \\client01\\ stripDestination; // \\something\\ if (string.IsNullOrEmpty(ultimateDestination)) ultimateDestination = path; return ultimateDestination; } /// <summary> /// It returns the Client path /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetVersionPath(string path) { string destination = path; if (path.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { destination = path.Replace(FCMConstant.SYSFOLDER.TEMPLATEFOLDER, FCMConstant.SYSFOLDER.VERSIONFOLDER); } return destination; } /// <summary> /// Open document /// </summary> /// <param name="document"></param> /// <param name="vkReadOnly"></param> /// <param name="isFromWeb"></param> public static void OpenDocument(Model.ModelDocument.Document document, object vkReadOnly, bool isFromWeb) { if (document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.WORD) { string filePathName = Utils.getFilePathName(document.Location, document.Name ); WordDocumentTasks.OpenDocument( filePathName, vkReadOnly, isFromWeb ); } } // Open document for Location and Name // public static void OpenDocument(string Location, string Name, string Type, object vkReadOnly, bool isFromWeb = false) { if (Type == MackkadoITFramework.Helper.Utils.DocumentType.WORD) { string filePathName = Utils.getFilePathName(Location, Name); WordDocumentTasks.OpenDocument( filePathName, vkReadOnly, isFromWeb ); } if (Type == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL) { string filePathName = Utils.getFilePathName(Location, Name); var Response = ExcelSpreadsheetTasks.OpenDocument(filePathName); if (Response.ReturnCode < 1) { MessageBox.Show(Response.Message); } } if (Type == MackkadoITFramework.Helper.Utils.DocumentType.PDF) { string filePathName = Utils.getFilePathName( Location, Name ); System.Diagnostics.Process proc = new System.Diagnostics.Process(); var adobe = CodeValue.GetCodeValueExtended( iCodeType: FCMConstant.CodeTypeString.SYSTSET, iCodeValueID: "PDFEXEPATH" ); if (!File.Exists( adobe )) { MessageBox.Show( "I can't find Adobe Reader. Please configure SYSTSET.PDFEXTPATH." ); return; } proc.StartInfo.FileName = adobe; proc.StartInfo.Arguments = filePathName; proc.Start(); } } /// <summary> /// Return image according to Record Type /// </summary> /// <param name="RecordType"></param> /// <returns></returns> public static int ImageSelect(string RecordType) { int image = FCMConstant.Image.Document; switch (RecordType) { case FCMConstant.RecordType.DOCUMENT: image = FCMConstant.Image.Document; break; case FCMConstant.RecordType.APPENDIX: image = FCMConstant.Image.Document; break; case FCMConstant.RecordType.FOLDER: image = FCMConstant.Image.Folder; break; default: image = FCMConstant.Image.Document; break; } return image; } /// <summary> /// Get Logo location for a client. /// </summary> /// <param name="clientUID"></param> /// <returns></returns> public static string GetImageUrl( string DocumentType, string curEnvironment = MackkadoITFramework.Helper.Utils.EnvironmentList.LOCAL ) { string image = ""; string logoPath = ""; string logoName = ""; string logoPathName = ""; Utils.FCMenvironment = curEnvironment; switch (DocumentType) { case MackkadoITFramework.Helper.Utils.DocumentType.WORD: logoName = FCMConstant.ImageFileName.Document; break; case MackkadoITFramework.Helper.Utils.DocumentType.EXCEL: logoName = FCMConstant.ImageFileName.Excel; break; case MackkadoITFramework.Helper.Utils.DocumentType.FOLDER: logoName = FCMConstant.ImageFileName.Folder; break; case MackkadoITFramework.Helper.Utils.DocumentType.PDF: logoName = FCMConstant.ImageFileName.PDF; break; default: logoName = FCMConstant.ImageFileName.Document; break; } // Set no icon image if necessary // logoPath = FCMConstant.SYSFOLDER.LOGOFOLDER; logoName = logoName.Replace( FCMConstant.SYSFOLDER.LOGOFOLDER, string.Empty ); logoPathName = Utils.getFilePathName( logoPath, logoName ); return logoPathName; } /// <summary> /// Return sequence number of the client's logo from the image list /// </summary> /// <returns></returns> public static int GetClientLogoImageSeqNum(int clientUID) { int image = 0; foreach (var client in Utils.ClientList) { if (client.UID == clientUID) { image = client.LogoImageSeqNum; break; } } return image; } /// <summary> /// Get image for file /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <returns></returns> public static int GetFileImage(char source, char destination, string documentType ) { int image = FCMConstant.Image.WordFileSourceNoDestinationNo; if (source == 'Y') { if (destination == 'Y') { // Source = "Y"; Destination = "Y" switch (documentType) { case MackkadoITFramework.Helper.Utils.DocumentType.WORD: image = FCMConstant.Image.WordFileSourceYesDestinationYes; break; case MackkadoITFramework.Helper.Utils.DocumentType.EXCEL: image = FCMConstant.Image.ExcelFileSourceYesDestinationYes; break; case MackkadoITFramework.Helper.Utils.DocumentType.PDF: image = FCMConstant.Image.PDFFileSourceYesDestinationYes; break; case MackkadoITFramework.Helper.Utils.DocumentType.FOLDER: image = FCMConstant.Image.Folder; break; case MackkadoITFramework.Helper.Utils.DocumentType.APPENDIX: image = FCMConstant.Image.Appendix; break; } } else { // Source = "Y"; Destination = "N" image = FCMConstant.Image.WordFileSourceYesDestinationNo; switch (documentType) { case MackkadoITFramework.Helper.Utils.DocumentType.WORD: image = FCMConstant.Image.WordFileSourceYesDestinationNo; break; case MackkadoITFramework.Helper.Utils.DocumentType.EXCEL: image = FCMConstant.Image.ExcelFileSourceYesDestinationNo; break; case MackkadoITFramework.Helper.Utils.DocumentType.PDF: image = FCMConstant.Image.PDFFileSourceYesDestinationNo; break; case MackkadoITFramework.Helper.Utils.DocumentType.FOLDER: image = FCMConstant.Image.Folder; break; case MackkadoITFramework.Helper.Utils.DocumentType.APPENDIX: image = FCMConstant.Image.Appendix; break; } } } else { if (destination == 'Y') { // Source = "N"; Destination = "Y" image = FCMConstant.Image.WordFileSourceNoDestinationYes; switch (documentType) { case MackkadoITFramework.Helper.Utils.DocumentType.WORD: image = FCMConstant.Image.WordFileSourceNoDestinationYes; break; case MackkadoITFramework.Helper.Utils.DocumentType.EXCEL: image = FCMConstant.Image.ExcelFileSourceNoDestinationYes; break; case MackkadoITFramework.Helper.Utils.DocumentType.PDF: image = FCMConstant.Image.PDFFileSourceNoDestinationYes; break; case MackkadoITFramework.Helper.Utils.DocumentType.FOLDER: image = FCMConstant.Image.Folder; break; case MackkadoITFramework.Helper.Utils.DocumentType.APPENDIX: image = FCMConstant.Image.Appendix; break; } } else { // Source = "N"; Destination = "N" image = FCMConstant.Image.WordFileSourceNoDestinationNo; switch (documentType) { case MackkadoITFramework.Helper.Utils.DocumentType.WORD: image = FCMConstant.Image.WordFileSourceNoDestinationNo; break; case MackkadoITFramework.Helper.Utils.DocumentType.EXCEL: image = FCMConstant.Image.ExcelFileSourceNoDestinationNo; break; case MackkadoITFramework.Helper.Utils.DocumentType.PDF: image = FCMConstant.Image.PDFFileSourceNoDestinationNo; break; case MackkadoITFramework.Helper.Utils.DocumentType.FOLDER: image = FCMConstant.Image.Folder; break; case MackkadoITFramework.Helper.Utils.DocumentType.APPENDIX: image = FCMConstant.Image.Appendix; break; } } } return image; } /// <summary> /// Retrieves cached value for user settings /// </summary> /// <returns></returns> public static string UserSettingGetCacheValue( UserSettings userSettings) { string valueReturned = ""; if (Utils.UserSettingsCache == null) return valueReturned; foreach (var userSet in Utils.UserSettingsCache.ListOfUserSettings) { if ( userSet.FKUserID == userSettings.FKUserID && userSet.FKScreenCode == userSettings.FKScreenCode && userSet.FKControlCode == userSettings.FKControlCode && userSet.FKPropertyCode == userSettings.FKPropertyCode ) { valueReturned = userSet.Value; } } valueReturned = valueReturned.Trim(); return valueReturned; } /// <summary> /// Refresh cache /// </summary> /// <returns></returns> public static void RefreshCache() { Utils.UserSettingsCache.ListOfUserSettings.Clear(); Utils.UserSettingsCache.ListOfUserSettings = UserSettings.List(Utils.UserID); } /// <summary> /// Refresh cache /// </summary> /// <returns></returns> public static void LoadUserSettingsInCache() { Utils.UserSettingsCache = new UserSettings(); Utils.UserSettingsCache.ListOfUserSettings = UserSettings.List(Utils.UserID); } /// <summary> /// Load folder into FCM Database and into FCM folder /// </summary> /// <param name="sourceFolder"></param> /// <param name="uioutput"></param> /// <param name="parentUID"></param> /// <param name="sequenceNumber"></param> /// <param name="headerInfo"></param> /// <returns></returns> static public ResponseStatus LoadFolder(string sourceFolder, IOutputMessage uioutput, int parentUID, int sequenceNumber, HeaderInfo headerInfo) { ResponseStatus response = new ResponseStatus(); response.Message = "Folder loaded successfully."; if (!Directory.Exists(sourceFolder)) { response.ReturnCode = -0010; response.ReasonCode = -0001; response.Message = "Source folder does not exist."; response.UniqueCode = "E00.00.0001"; response.Icon = MessageBoxIcon.Error; return response; } string[] folderNameSplit = sourceFolder.Split('\\'); string folderName = folderNameSplit[folderNameSplit.Length - 1]; uioutput.Activate(); string[] files = Directory.GetFiles(sourceFolder); // Create folder that contains files and keep the parent // // ... Model.ModelDocument.Document folder = new Model.ModelDocument.Document(); if (folderName.Length >= 7) folder.CUID = folderName.Substring(0, 7); else folder.CUID = folderName; folder.FileName = folderName; folder.Comments = "Loaded by batch"; folder.Name = folderName; folder.DisplayName = folderName; folder.FKClientUID = 0; folder.IssueNumber = 0; string refPath = MakHelperUtils.getReferenceFilePathName(sourceFolder); if (string.IsNullOrEmpty(refPath)) { response.ReturnCode = -0010; response.ReasonCode = -0002; response.Message = "Folder selected is not under managed template folder."; response.UniqueCode = "E00.00.0001"; return response; } folder.Location = refPath; // Store the folder being loaded at the root level // folder.Location = MakConstant.SYSFOLDER.TEMPLATEFOLDER; folder.ParentUID = parentUID; folder.SequenceNumber = 0; folder.SourceCode = "FCM"; folder.UID = 0; folder.RecordType = MakHelperUtils.RecordType.FOLDER; folder.DocumentType = MakHelperUtils.DocumentType.FOLDER; folder.SimpleFileName = folder.Name; folder.FileExtension = "FOLDER"; folder.IsProjectPlan = "N"; // parentUID = folder.Save(headerInfo, MakHelperUtils.SaveType.NEWONLY); parentUID = RepDocument.Save(headerInfo, folder, MakHelperUtils.SaveType.NEWONLY); // Store each file // foreach (string file in files) { #region File Processing string name = Path.GetFileName(file); string fileName = Path.GetFileNameWithoutExtension(file); string fileExtension = Path.GetExtension(file); string validExtensions = ".doc .docx .xls .xlsx .pdf .dotx"; // Not every extension will be loaded // if (!validExtensions.Contains(fileExtension)) continue; string fileNameExt = Path.GetFileName(file); string simpleFileName = fileNameExt; if (fileNameExt.Length > 10) simpleFileName = fileNameExt.Substring(10).Trim(); Model.ModelDocument.Document document = new Model.ModelDocument.Document(); document.CUID = fileName.Substring(0, 6); document.FileName = fileNameExt; //string refPath = // Utils.getReferenceFilePathName(sourceFolder); document.Location = refPath; string issue = "1"; document.IssueNumber = Convert.ToInt32(issue); try { issue = fileName.Substring(7, 2); document.IssueNumber = Convert.ToInt32(issue); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString()); } document.Name = fileName; document.SimpleFileName = simpleFileName; document.DisplayName = simpleFileName; document.SequenceNumber = sequenceNumber; document.ParentUID = parentUID; document.Comments = "Loaded via batch"; document.SourceCode = "FCM"; document.FKClientUID = 0; document.RecordType = MakHelperUtils.RecordType.DOCUMENT; document.FileExtension = fileExtension; document.Status = FCMUtils.FCMConstant.DocumentStatus.ACTIVE; document.IsProjectPlan = "N"; switch (fileExtension) { case ".doc": document.DocumentType = MakHelperUtils.DocumentType.WORD; break; case ".docx": document.DocumentType = MakHelperUtils.DocumentType.WORD; break; case ".dotx": document.DocumentType = MakHelperUtils.DocumentType.WORD; break; case ".xls": document.DocumentType = MakHelperUtils.DocumentType.EXCEL; break; case ".xlsx": document.DocumentType = MakHelperUtils.DocumentType.EXCEL; break; case ".pdf": document.DocumentType = MakHelperUtils.DocumentType.PDF; break; default: document.DocumentType = MakHelperUtils.DocumentType.UNDEFINED; break; } // document.Save(headerInfo, MakHelperUtils.SaveType.NEWONLY); RepDocument.Save(headerInfo, document, MakHelperUtils.SaveType.NEWONLY); uioutput.AddOutputMessage( document.Name, "", userID ); sequenceNumber++; #endregion File Processing } // Recursion removed // string[] folders = Directory.GetDirectories(sourceFolder); foreach (string directory in folders) { string name = Path.GetFileName(directory); LoadFolder(directory, uioutput, parentUID, 0, headerInfo); } return response; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace FCMApplicationLoader { public partial class UIFCMAppLoader : Form { public UIFCMAppLoader() { InitializeComponent(); } private void btnLoadApplication_Click(object sender, EventArgs e) { AssemblyLoader load = new AssemblyLoader(); if (load.AssemblyCanBeLoaded) { load.LoadFCMClient(); // this.Hide(); this.Dispose(); } } private void Form1_Load(object sender, EventArgs e) { } private void UIFCMAppLoader_Leave(object sender, EventArgs e) { this.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using ConnString = MackkadoITFramework.Utils.ConnString; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace FCMMySQLBusinessLibrary.Repository.RepositoryClient { internal class RepClientContract: ClientContract { // var student1 = new Student{firstName = "Bruce", lastName = "Willis"}; /// <summary> /// Get Employee details /// </summary> internal static ClientContract Read(int clientContractUID) { // // EA SQL database // ClientContract clientContract = new ClientContract(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientContractFieldsString() + " FROM ClientContract" + " WHERE UID = @UID"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); command.Parameters.Add("@UID", MySqlDbType.Int32).Value = clientContractUID; MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadClientContractObject(reader, clientContract); } catch (Exception) { clientContract.UID = 0; } } } } return clientContract; } /// <summary> /// List client contracts /// </summary> /// <param name="clientID"></param> internal static List<ClientContract> List(int clientID) { List<ClientContract> clientContractList = new List<ClientContract>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + ClientContractFieldsString() + " FROM ClientContract " + " WHERE FKCompanyUID = {0}", clientID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ClientContract _clientContract = new ClientContract(); LoadClientContractObject(reader, _clientContract); clientContractList.Add(_clientContract); } } } } return clientContractList; } // ----------------------------------------------------- // Retrieve last Contract UID // ----------------------------------------------------- private static int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientContract "; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add new contract /// </summary> /// <returns></returns> public static ResponseStatus Insert( HeaderInfo headerInfo, ClientContract clientContract) { var rs = new ResponseStatus(); rs.Message = "Client Contract Added Successfully"; rs.ReturnCode = 1; rs.ReasonCode = 1; int _uid = 0; _uid = GetLastUID() + 1; clientContract.UID = _uid; DateTime _now = DateTime.Today; clientContract.CreationDateTime = _now; clientContract.UpdateDateTime = _now; if (clientContract.ExternalID == null) clientContract.ExternalID = ""; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO ClientContract " + "( " + ClientContractFieldsString() + ")" + " VALUES " + "( " + " @" + FCMDBFieldName.ClientContract.FKCompanyUID + ", @" + FCMDBFieldName.ClientContract.UID + ", @" + FCMDBFieldName.ClientContract.ExternalID + ", @" + FCMDBFieldName.ClientContract.Status + ", @" + FCMDBFieldName.ClientContract.Type + ", @" + FCMDBFieldName.ClientContract.StartDate + ", @" + FCMDBFieldName.ClientContract.EndDate + ", @" + FCMDBFieldName.ClientContract.UserIdCreatedBy + ", @" + FCMDBFieldName.ClientContract.UserIdUpdatedBy + ", @" + FCMDBFieldName.ClientContract.CreationDateTime + ", @" + FCMDBFieldName.ClientContract.UpdateDateTime + " )" ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command, clientContract, headerInfo); command.Parameters.Add(FCMDBFieldName.ClientContract.CreationDateTime, MySqlDbType.DateTime).Value = headerInfo.CurrentDateTime; command.Parameters.Add(FCMDBFieldName.ClientContract.UserIdCreatedBy, MySqlDbType.VarChar).Value = headerInfo.UserID; connection.Open(); command.ExecuteNonQuery(); } } return rs; } /// <summary> /// Update Contract /// </summary> /// <returns></returns> public static ResponseStatus Update( HeaderInfo headerInfo, ClientContract clientContract ) { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item updated successfully"; if (clientContract.ExternalID == null) clientContract.ExternalID = ""; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE ClientContract " + " SET " + FCMDBFieldName.ClientContract.ExternalID + " = @" + FCMDBFieldName.ClientContract.ExternalID + ", " + FCMDBFieldName.ClientContract.UpdateDateTime + " = @" + FCMDBFieldName.ClientContract.UpdateDateTime + ", " + FCMDBFieldName.ClientContract.Type + " = @" + FCMDBFieldName.ClientContract.Type + ", " + FCMDBFieldName.ClientContract.UserIdUpdatedBy + " = @" + FCMDBFieldName.ClientContract.UserIdUpdatedBy + ", " + FCMDBFieldName.ClientContract.Status + " = @" + FCMDBFieldName.ClientContract.Status + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command, clientContract, headerInfo); connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// Delete Employee /// </summary> /// <returns></returns> public static ResponseStatus Delete( HeaderInfo headerInfo, ClientContract clientContract) { var ret = new ResponseStatus(); ret.Message = "Employee Deleted successfully"; if (clientContract.ExternalID == null) clientContract.ExternalID = ""; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "DELETE ClientContract " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.VarChar).Value = clientContract.UID; connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// Add Employee parameters to the SQL Command. /// </summary> /// <param name="command"></param> private static void AddSQLParameters(MySqlCommand command, ClientContract clientContract, HeaderInfo headerInfo) { command.Parameters.Add(FCMDBFieldName.ClientContract.FKCompanyUID, MySqlDbType.Int32).Value = clientContract.FKCompanyUID; command.Parameters.Add(FCMDBFieldName.ClientContract.UID, MySqlDbType.Int32).Value = clientContract.UID; command.Parameters.Add(FCMDBFieldName.ClientContract.ExternalID, MySqlDbType.VarChar).Value = clientContract.ExternalID; command.Parameters.Add(FCMDBFieldName.ClientContract.Status, MySqlDbType.VarChar).Value = clientContract.Status; command.Parameters.Add(FCMDBFieldName.ClientContract.Type, MySqlDbType.VarChar).Value = clientContract.Type; command.Parameters.Add(FCMDBFieldName.ClientContract.StartDate, MySqlDbType.DateTime).Value = clientContract.StartDate; command.Parameters.Add(FCMDBFieldName.ClientContract.EndDate, MySqlDbType.DateTime).Value = clientContract.EndDate; command.Parameters.Add(FCMDBFieldName.ClientContract.UserIdUpdatedBy, MySqlDbType.VarChar).Value = headerInfo.UserID; command.Parameters.Add(FCMDBFieldName.ClientContract.UpdateDateTime, MySqlDbType.DateTime).Value = headerInfo.CurrentDateTime; } private static string ClientContractFieldsString() { return ( FCMDBFieldName.ClientContract.FKCompanyUID + "," + FCMDBFieldName.ClientContract.UID + "," + FCMDBFieldName.ClientContract.ExternalID + "," + FCMDBFieldName.ClientContract.Status + "," + FCMDBFieldName.ClientContract.Type + "," + FCMDBFieldName.ClientContract.StartDate + "," + FCMDBFieldName.ClientContract.EndDate + "," + FCMDBFieldName.ClientContract.UserIdUpdatedBy + "," + FCMDBFieldName.ClientContract.UserIdCreatedBy + "," + FCMDBFieldName.ClientContract.CreationDateTime + "," + FCMDBFieldName.ClientContract.UpdateDateTime ); } /// <summary> /// This method loads the information from the sqlreader into the Employee object /// </summary> /// <param name="reader"></param> /// <param name="clientContract"> </param> private static void LoadClientContractObject(MySqlDataReader reader, ClientContract clientContract) { clientContract.FKCompanyUID = Convert.ToInt32(reader[FCMDBFieldName.ClientContract.FKCompanyUID]); clientContract.UID = Convert.ToInt32(reader[FCMDBFieldName.ClientContract.UID].ToString()); clientContract.ExternalID = reader[FCMDBFieldName.ClientContract.ExternalID].ToString(); try { clientContract.Status = reader[FCMDBFieldName.ClientContract.Status].ToString(); } catch { clientContract.Status = "ACTIVE"; } try { clientContract.Type = reader[FCMDBFieldName.ClientContract.Type].ToString(); } catch { clientContract.Type = "BASIC"; } try { clientContract.StartDate = Convert.ToDateTime(reader[FCMDBFieldName.ClientContract.StartDate].ToString()); } catch { clientContract.StartDate = DateTime.Now; } try { clientContract.EndDate = Convert.ToDateTime(reader[FCMDBFieldName.ClientContract.EndDate].ToString()); } catch { clientContract.EndDate = DateTime.Now; } clientContract.UserIdCreatedBy = reader[FCMDBFieldName.ClientContract.UserIdCreatedBy].ToString(); clientContract.UserIdUpdatedBy = reader[FCMDBFieldName.ClientContract.UserIdUpdatedBy].ToString(); try { clientContract.UpdateDateTime = Convert.ToDateTime(reader[FCMDBFieldName.ClientContract.UpdateDateTime].ToString()); } catch { clientContract.UpdateDateTime = DateTime.Now; } try { clientContract.CreationDateTime = Convert.ToDateTime(reader[FCMDBFieldName.ClientContract.CreationDateTime].ToString()); } catch { clientContract.CreationDateTime = DateTime.Now; } } public static ResponseStatus GetValidContractOnDate(int clientID, DateTime date) { ResponseStatus ret = new ResponseStatus(); ret.Message = "Valid contract not found."; ret.ReturnCode = 0001; ret.ReasonCode = 0002; ret.UniqueCode = ResponseStatus.MessageCode.Warning.FCMWAR00000002; ClientContract clientContract = new ClientContract(); string dateString = date.ToString().Substring(0, 10); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + ClientContractFieldsString() + " FROM ClientContract " + " WHERE FKCompanyUID = @FKCompanyUID " + " AND StartDate <= @StartDate " + " AND EndDate >= @EndDate "; using (var command = new MySqlCommand(commandString, connection)) { command.Parameters.Add("@FKCompanyUID", MySqlDbType.Int32).Value = clientID; command.Parameters.Add("@StartDate", MySqlDbType.DateTime).Value = date; command.Parameters.Add("@EndDate", MySqlDbType.DateTime).Value = date; connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ClientContract _clientContract = new ClientContract(); LoadClientContractObject(reader, _clientContract); clientContract = _clientContract; ret.Message = "Valid contract found."; ret.ReturnCode = 0001; ret.ReasonCode = 0001; ret.XMessageType = MessageType.Informational; ret.UniqueCode = ResponseStatus.MessageCode.Informational.FCMINF00000001; break; } } } } ret.Contents = clientContract; return ret; } } } <file_sep>[itarchitecture - Copy.jpeg] rotate=rotate(1) <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; namespace fcm.Windows { public partial class UIReferenceData : Form { private string _userID; public DataTable dtCodeValue; public List<CodeType> codeTypeList; private CodeValue codeValue; private bool listForType; private Form _comingFromForm; // This constructor is invoked when a code type list is selected. // public UIReferenceData(CodeValue _codeValue) : this() { codeValue = _codeValue; cbxCodeType.Enabled = false; listForType = true; } public UIReferenceData(Form comingFromForm): this() { _comingFromForm = comingFromForm; } // This is for an open code type listed // public UIReferenceData() { InitializeComponent(); _userID = Utils.UserID; // // Create datatable = Code Value // var FKCodeType = new DataColumn("FKCodeType", typeof(String)); var ID = new DataColumn("ID", typeof(String)); var Description = new DataColumn("Description", typeof(String)); var Abbreviation = new DataColumn("Abbreviation", typeof(String)); var ValueExtended = new DataColumn("ValueExtended", typeof(String)); dtCodeValue = new DataTable("dtCodeValue"); dtCodeValue.Columns.Add(FKCodeType); dtCodeValue.Columns.Add(ID); dtCodeValue.Columns.Add(Description); dtCodeValue.Columns.Add(Abbreviation); dtCodeValue.Columns.Add(ValueExtended); dgvCodeValue.DataSource = dtCodeValue; listForType = false; cbxCodeType.Enabled = true; } private void btnCodeTypeList_Click(object sender, EventArgs e) { } private void UIReferenceData_Load(object sender, EventArgs e) { LoadCodeType(); if ((codeValue == null) || (string.IsNullOrEmpty(codeValue.FKCodeType))) { cbxCodeType.SelectedIndex = 0; } else { cbxCodeType.SelectedText = codeValue.FKCodeType; // Load code values // loadCodeValue(codeValue.FKCodeType); //for (int i = 0; i < cbxCodeType.Items.Count; i++) //{ // if (cbxCodeType.Items[i].ToString() == codeValue.FKCodeType) // { // cbxCodeType.SelectedItem = i; // break; // } //} } cbxCodeType.Focus(); } // Load code value selected // private bool loadCodeValueSelectedInMemory() { if (dgvCodeValue.SelectedRows.Count < 1) return false; var selectedRow = dgvCodeValue.SelectedRows; if (codeValue == null) { codeValue = new CodeValue(); } codeValue.ID = selectedRow[0].Cells["ID"].Value.ToString(); codeValue.FKCodeType = selectedRow[0].Cells["FKCodeType"].Value.ToString(); codeValue.Description = selectedRow[0].Cells["Description"].Value.ToString(); codeValue.Abbreviation = selectedRow[0].Cells["Abbreviation"].Value.ToString(); codeValue.ValueExtended = selectedRow[0].Cells["ValueExtended"].Value.ToString(); return true; } private void LoadCodeType() { var codeType = new CodeType(); codeType.List(HeaderInfo.Instance); cbxCodeType.Items.Clear(); foreach (CodeType c in codeType.codeTypeList) { cbxCodeType.Items.Add(c.Code); } ucCodeType1.Visible = false; ucCodeValue1.Visible = false; } private void cbxCodeType_SelectedIndexChanged(object sender, EventArgs e) { string valueSelected = cbxCodeType.SelectedItem.ToString(); loadCodeValue(valueSelected); } // // List values // private void loadCodeValue( string codeType ) { dtCodeValue.Clear(); var codeList = new CodeValue(); codeList.List( codeType ); foreach (CodeValue code in codeList.codeValueList) { DataRow elementRow = dtCodeValue.NewRow(); elementRow["FKCodeType"] = code.FKCodeType; elementRow["ID"] = code.ID; elementRow["Description"] = code.Description; elementRow["Abbreviation"] = code.Abbreviation; elementRow["ValueExtended"] = code.ValueExtended; dtCodeValue.Rows.Add(elementRow); } } private void btnNewType_Click(object sender, EventArgs e) { ucCodeValue1.Visible = false; if (ucCodeType1.Visible == true) ucCodeType1.Visible = false; else ucCodeType1.Visible = true; } // // New code value // private void btnNewCodeValue_Click(object sender, EventArgs e) { CodeValueSelected(false); } private void dgvCodeValue_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (string.IsNullOrEmpty(codeValue.FKCodeType)) { CodeValueSelected(false); } else { loadCodeValueSelectedInMemory(); this.Close(); } } private void cbxCodeType_Enter(object sender, EventArgs e) { LoadCodeType(); } // // // private void CodeValueSelected(bool RefreshOnly) { ucCodeType1.Visible = false; if (! RefreshOnly) { if (ucCodeValue1.Visible == true) { ucCodeValue1.Visible = false; if (cbxCodeType.SelectedItem != null) { string valueSelected = cbxCodeType.SelectedItem.ToString(); loadCodeValue(valueSelected); } return; } ucCodeValue1.Visible = true; } if (dgvCodeValue.SelectedRows.Count <= 0) return; var selectedRow = dgvCodeValue.SelectedRows; if (loadCodeValueSelectedInMemory()) { ucCodeValue1.SetFKCodeType(this.codeValue.FKCodeType); ucCodeValue1.SetCodeID(this.codeValue.ID); ucCodeValue1.SetCodeDescription(this.codeValue.Description); ucCodeValue1.SetAbbreviation(this.codeValue.Abbreviation); ucCodeValue1.SetValueExtended(this.codeValue.ValueExtended); } } private void dgvCodeValue_CellClick(object sender, DataGridViewCellEventArgs e) { CodeValueSelected(true); } private void dgvCodeValue_SelectionChanged(object sender, EventArgs e) { CodeValueSelected(true); } private void dgvCodeValue_CellBorderStyleChanged(object sender, EventArgs e) { } private void newCodeValueToolStripMenuItem_Click(object sender, EventArgs e) { } private void gbCodeType_Enter(object sender, EventArgs e) { } private void dgvCodeValue_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void UIReferenceData_Leave(object sender, EventArgs e) { _comingFromForm.Activate(); } private void UIReferenceData_FormClosed(object sender, FormClosedEventArgs e) { if (_comingFromForm != null) { _comingFromForm.Activate(); } } private void eToolStripMenuItem_Click(object sender, EventArgs e) { if (_comingFromForm != null) { this.Close(); _comingFromForm.Activate(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace fcm { public class DataColector { public static string Get( ReportMetadata metadata ) { string ret = ""; string sql = ""; switch (metadata.TableName.ToUpper()) { case "CLIENT" : Client.ReadFieldClient(metadata.FieldName.ToUpper(), Utils.ClientID); break; case "EMPLOYEE" : // Write in Employee Class break; } return ret; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using MackkadoITFramework.APIDocument; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Interfaces; using Excel=Microsoft.Office.Interop.Excel; using System.Reflection; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary { public class ExcelSpreadsheetTasks { public void Test() { Excel._Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; Excel.Range oRng; try { //Start Excel and get Application object. oXL = new Excel.Application(); oXL.Visible = true; //Get a new workbook. oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); oSheet = (Excel._Worksheet)oWB.ActiveSheet; //Add table headers going cell by cell. oSheet.Cells[1, 1] = "First Name"; oSheet.Cells[1, 2] = "Last Name"; oSheet.Cells[1, 3] = "Full Name"; oSheet.Cells[1, 4] = "Salary"; //Format A1:D1 as bold, vertical alignment = center. oSheet.get_Range("A1", "D1").Font.Bold = true; oSheet.get_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; // Create an array to multiple values at once. string[,] saNames = new string[5, 2]; saNames[0, 0] = "John"; saNames[0, 1] = "Smith"; saNames[1, 0] = "Tom"; saNames[1, 1] = "Brown"; saNames[2, 0] = "Sue"; saNames[2, 1] = "Thomas"; saNames[3, 0] = "Jane"; saNames[3, 1] = "Jones"; saNames[4, 0] = "Adam"; saNames[4, 1] = "Johnson"; //Fill A2:B6 with an array of values (First and Last Names). oSheet.get_Range("A2", "B6").Value2 = saNames; //Fill C2:C6 with a relative formula (=A2 & " " & B2). oRng = oSheet.get_Range("C2", "C6"); oRng.Formula = "=A2 & \" \" & B2"; //Fill D2:D6 with a formula(=RAND()*100000) and apply format. oRng = oSheet.get_Range("D2", "D6"); oRng.Formula = "=RAND()*100000"; oRng.NumberFormat = "$0.00"; //AutoFit columns A:D. oRng = oSheet.get_Range("A1", "D1"); oRng.EntireColumn.AutoFit(); //Make sure Excel is visible and give the user control //of Microsoft Excel's lifetime. oXL.Visible = true; oXL.UserControl = true; } catch (Exception theException) { String errorMessage; errorMessage = "Error: "; errorMessage = String.Concat(errorMessage, theException.Message); errorMessage = String.Concat(errorMessage, " Line: "); errorMessage = String.Concat(errorMessage, theException.Source); } } public static ResponseStatus OpenDocument(string FileName) { ResponseStatus ret = new ResponseStatus(); ret.ReasonCode = 1; ret.ReturnCode = 1; ret.Message = "Successful Execution"; if (!File.Exists(FileName)) { ret.ReturnCode = -10; ret.ReasonCode = 1; ret.Message ="File not found. " + FileName; return ret; } Excel.Application xlApp; Excel.Workbook xlWorkBook; object missing = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlApp.Visible = true; xlWorkBook = xlApp.Workbooks.Open(FileName, missing, false, missing, missing, missing, true, missing, "\t", missing, missing, missing, missing, missing, missing); return ret; } public static ResponseStatus PrintDocument( string FileName ) { ResponseStatus ret = new ResponseStatus(); ret.ReasonCode = 1; ret.ReturnCode = 1; ret.Message = "Successful Execution"; if (!File.Exists( FileName )) { ret.ReturnCode = -10; ret.ReasonCode = 1; ret.Message = "File not found. " + FileName; return ret; } Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object missing = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlApp.Visible = true; xlWorkBook = xlApp.Workbooks.Open( FileName, missing, false, missing, missing, missing, true, missing, "\t", missing, missing, missing, missing, missing, missing ); xlWorkBook.PrintOutEx(); xlWorkBook.Close(); xlApp.Quit(); return ret; } // ---------------------------------------------------- // Find and replace words in Excel // ---------------------------------------------------- public static void FindAndReplace( object vkFind, object vkReplace, object vkNum, Excel.Application vkExcelApp, Excel.Workbook vkMyDoc ) { string svkFind = vkFind.ToString(); string svkReplace = vkReplace.ToString(); // Retrieve workbooks Excel.Workbooks workbooks = vkExcelApp.Workbooks; // Switch off warnings vkExcelApp.ErrorCheckingOptions.UnlockedFormulaCells = false; vkExcelApp.ErrorCheckingOptions.EmptyCellReferences = false; vkExcelApp.ErrorCheckingOptions.Application.DisplayAlerts = false; // Replace Excel Document body // vkExcelApp.Cells.Replace(What: vkFind, Replacement: vkReplace, MatchCase: false, LookAt: Excel.XlLookAt.xlWhole); // Daniel 05-Aug-2013 // Replace is replace the entire content of the cell // I can't find a way to replace only the specific text by another text. // int i = vkExcelApp.Worksheets.Count; // Excel.Worksheet wsX = (Excel.Worksheet)vkExcelApp.Worksheets[1]; foreach (Excel.Worksheet ws in vkExcelApp.Worksheets) { // Daniel - Issue found here // try { ws.PageSetup.RightHeader = ws.PageSetup.RightHeader.Replace(svkFind, svkReplace); ws.PageSetup.LeftHeader = ws.PageSetup.LeftHeader.Replace(svkFind, svkReplace); ws.PageSetup.CenterHeader = ws.PageSetup.CenterHeader.Replace(svkFind, svkReplace); ws.PageSetup.RightFooter = ws.PageSetup.RightFooter.Replace(svkFind, svkReplace); ws.PageSetup.CenterFooter = ws.PageSetup.CenterFooter.Replace(svkFind, svkReplace); ws.PageSetup.LeftFooter = ws.PageSetup.LeftFooter.Replace(svkFind, svkReplace); } catch (Exception ex) { LogFile.WriteToTodaysLogFile(ex.ToString(), "", "", "ExcelSpreadSheetTasks.cs", ""); FCMEmail.SendEmailSimple("<EMAIL>", "FCM Error ConsoleGenerate", ex.ToString()); } } // vkExcelApp.WorksheetFunction.Substitute( Excel.HeaderFooter, vkFind.ToString(), vkReplace.ToString() ); // Excel.HeaderFooter x; // x.Text.Replace( vkFind.ToString(), vkReplace.ToString() ); // vkExcelApp.WorksheetFunction.Substitute( Excel.HeaderFooter, vkFind.ToString(), vkReplace.ToString() ); } // --------------------------------------------- // Copy Documents // --------------------------------------------- public static object CopyDocument( string fromFileName, string destinationFileName, List<WordDocumentTasks.TagStructure> tag, IOutputMessage uioutput, string processName, string userID ) { var vkExcelApp = new Microsoft.Office.Interop.Excel.Application(); vkExcelApp.Visible = false; // Excel.ApplicationClass vkExcelApp = new Excel.ApplicationClass(); string saveFile = destinationFileName; object vkReadOnly = false; object vkVisible = true; object vkFalse = false; object vkTrue = true; object vkDynamic = 2; object vkMissing = System.Reflection.Missing.Value; // Let's make the excel application not visible // vkExcelApp.Visible = false; // vkExcelApp.Activate(); // Let's copy the document File.Copy( fromFileName, destinationFileName, true ); // Let's open the DESTINATION document //Word.Document vkMyDoc = vkExcelApp.Documents.Open( // ref destinationFileName, ref vkMissing, ref vkReadOnly, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkMissing, // ref vkMissing, ref vkMissing, ref vkVisible ); Excel.Workbook vkMyDoc = vkExcelApp.Workbooks.Open( destinationFileName, vkMissing, false, vkMissing, vkMissing, vkMissing, true, vkMissing, "\t", vkMissing, vkMissing, vkMissing, vkMissing, vkMissing, vkMissing ); foreach (var t in tag) { // 17/02/2013 // Ignore **MD** and other with ** because it is too risky // if (t.Tag == "**MD**" || t.Tag == "**PM**" || t.Tag == "**SM**" || t.Tag == "**ADDRESS**") continue; if (t.TagType == "IMAGE") continue; FindAndReplace( t.Tag, t.TagValue, 1, vkExcelApp, vkMyDoc ); } try { vkMyDoc.Save(); } catch (Exception ex) { uioutput.AddOutputMessage( "(Excel) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID ); uioutput.AddErrorMessage( "(Excel) ERROR in file: " + fromFileName + " --- Message: " + ex.ToString(), processName, userID ); } // close the new document vkMyDoc.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject( vkMyDoc ); // close excel application vkExcelApp.Quit(); return saveFile; } } } <file_sep>using System; using System.Collections.Generic; using System.Windows.Forms; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; namespace fcm.Components { public partial class UCClientOtherInfo : UserControl { private Client client; private List<ClientOtherInfo> clientOtherInfoList; public UCClientOtherInfo() { InitializeComponent(); } private void UCClientOtherInfo_Load(object sender, EventArgs e) { } public void PopulateData(int iclientUID) { client = new Client(HeaderInfo.Instance); client.UID = iclientUID; var repclient = RepClient.Read(client.UID); var response = repclient.responseStatus; // var response = client.Read(); if (response.ReturnCode == 1 && response.ReasonCode == 1) { clientOtherInfoList = ClientOtherInfo.List(client.UID); clientOtherInfoBindingSource.DataSource = clientOtherInfoList; var codeValue = new CodeValue(); var list = new List<CodeValue>(); var codeValueResponse = codeValue.ListS(CodeType.CodeTypeValue.ClientOtherField, list); codeValueBindingSource.DataSource = list; } else { MessageBox.Show(response.Message, "Error Populating Data.", MessageBoxButtons.OK, response.Icon); } } private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { //if (dataGridView1.SelectedRows.Count <= 0) // return; //var selectedRow = dataGridView1.SelectedRows; //selectedRow[0].Cells["dgv" + ClientOtherInfo.FieldName.UID].Value = 0; //selectedRow[0].Cells["dgv" + ClientOtherInfo.FieldName.FKClientUID].Value = client.UID; } } } <file_sep>CREATE DATABASE IF NOT EXISTS `management` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `management`; -- MySQL dump 10.13 Distrib 5.6.13, for Win32 (x86) -- -- Host: localhost Database: management -- ------------------------------------------------------ -- Server version 5.5.32-MariaDB /*!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 utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `rdrelatedcode` -- DROP TABLE IF EXISTS `rdrelatedcode`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `rdrelatedcode` ( `RelatedCodeID` varchar(20) NOT NULL, `Description` varchar(100) DEFAULT NULL, `FKCodeTypeFrom` varchar(20) NOT NULL, `FKCodeTypeTo` varchar(20) NOT NULL, PRIMARY KEY (`RelatedCodeID`), KEY `fk_relatedcode_codetype1` (`FKCodeTypeFrom`), KEY `fk_relatedcode_codetype2` (`FKCodeTypeTo`), CONSTRAINT `fk_relatedcode_codetype1` FOREIGN KEY (`FKCodeTypeFrom`) REFERENCES `rdcodetype` (`CodeType`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_relatedcode_codetype2` FOREIGN KEY (`FKCodeTypeTo`) REFERENCES `rdcodetype` (`CodeType`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `rdrelatedcode` -- LOCK TABLES `rdrelatedcode` WRITE; /*!40000 ALTER TABLE `rdrelatedcode` DISABLE KEYS */; INSERT INTO `rdrelatedcode` VALUES ('Screen Group','','SCREENCODE','SCREENACTION'),('Screen Gtroup','','SCREENCODE','SCREENACTION'); /*!40000 ALTER TABLE `rdrelatedcode` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2013-10-19 18:09:48 <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace fcm.Components { public partial class UCCodeValue : UserControl { public CodeTypeList codeTypeList; public UCCodeValue() { InitializeComponent(); } public UCCodeValue(string iCodeType, string iCodeValue) { InitializeComponent(); this.ReadCodeValue(iCodeType, iCodeValue); } // // Set control fields // public void SetFKCodeType(string fkCodeType) { this.cbxCodeType.Text = fkCodeType; cbxCodeType.Enabled = false; } public void SetCodeID(string codeValueID) { this.txtCodeValueCode.Text = codeValueID; txtCodeValueCode.Enabled = false; } public void SetCodeDescription(string codeDescription) { this.txtCodeDescription.Text = codeDescription; } public void SetValueExtended(string valueExtended) { this.txtValueExtended.Text = valueExtended; } public void SetAbbreviation(string Abbreviation) { this.txtAbbreviation.Text = Abbreviation; } private void btnSave_Click(object sender, EventArgs e) { CodeValue cv = new CodeValue(); if (cbxCodeType.SelectedItem == null) { MessageBox.Show("Select Code Type."); return; } cv.FKCodeType = cbxCodeType.SelectedItem.ToString(); cv.ID = txtCodeValueCode.Text; cv.Description = txtCodeDescription.Text; cv.Abbreviation = txtAbbreviation.Text; cv.ValueExtended = txtValueExtended.Text; cv.Save(); MessageBox.Show("Code Type Save Successfully."); ResetFields(); } private void UCCodeValue_Load(object sender, EventArgs e) { LoadCodeType(); } private void cbxCodeType_SelectedIndexChanged(object sender, EventArgs e) { string valueSelected = cbxCodeType.SelectedItem.ToString(); } private void UCCodeValue_Enter(object sender, EventArgs e) { var ctsel = cbxCodeType.SelectedItem; LoadCodeType(); cbxCodeType.SelectedItem = ctsel; } private void LoadCodeType() { codeTypeList = new CodeTypeList(); codeTypeList.List(); cbxCodeType.Items.Clear(); foreach (CodeType c in codeTypeList.codeTypeList) { cbxCodeType.Items.Add(c.Code); } } private void txtCodeValueCode_Leave(object sender, EventArgs e) { string CodeType = cbxCodeType.SelectedItem.ToString(); string CodeValue = txtCodeValueCode.Text; this.ReadCodeValue(CodeType, CodeValue); } private void ReadCodeValue(string iCodeType, string iCodeValue) { CodeValue cv = new CodeValue(); cv.FKCodeType = iCodeType; cv.ID = iCodeValue; cv.Read(false); txtCodeDescription.Text = cv.Description; txtValueExtended.Text = cv.ValueExtended; txtAbbreviation.Text = cv.Abbreviation; } private void btnNew_Click(object sender, EventArgs e) { ResetFields(); } private void ResetFields() { txtCodeValueCode.Enabled = true; cbxCodeType.Enabled = true; txtCodeValueCode.Text = ""; txtCodeDescription.Text = ""; txtAbbreviation.Text = ""; txtValueExtended.Text = ""; txtCodeValueCode.Focus(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Model.ModelDocument; namespace FCMMySQLBusinessLibrary { public struct scDocoSetDocumentLink { public Model.ModelDocument.Document document; public DocumentSet documentSet; public DocumentSetDocument DocumentSetDocument; } public struct ListOfscDocoSetDocumentLink { public List<scDocoSetDocumentLink> list; } public struct scClientDocSetDocLink { public Model.ModelDocument.Document document; public ClientDocumentSet clientDocumentSet; public ClientDocument clientDocument; } public struct ListOfscClientDocSetDocLink { public List<scClientDocSetDocLink> list; } public struct scDocumentSetDocumentLink { public DocumentSetDocument dsdparent; public DocumentSetDocument dsdschild; public Model.ModelDocument.Document documentChild; public DocumentSetDocumentLink dsdlink; } } <file_sep>//using FCMMySQLBusinessLibrary.Document; using System; using System.Collections.Generic; using System.IO; using System.Linq; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Service.SVCDocument.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Helper; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using System.Data.Odbc; using System.Windows.Forms; namespace FCModbcBusinessLibrary.Repository.RepositoryDocument { /// <summary> /// It represents a document, folder or appendix. /// </summary> internal class RepDocument : Document { /// <summary> /// Database fields /// </summary> public struct FieldName { public const string UID = "UID"; public const string SimpleFileName = "SimpleFileName"; public const string CUID = "CUID"; public const string Name = "Name"; public const string DisplayName = "DisplayName"; public const string SequenceNumber = "SequenceNumber"; public const string IssueNumber = "IssueNumber"; public const string Location = "Location"; public const string Comments = "Comments"; public const string FileName = "FileName"; public const string SourceCode = "SourceCode"; public const string FKClientUID = "FKClientUID"; public const string IsVoid = "IsVoid"; public const string Skip = "Skip"; public const string ParentUID = "ParentUID"; public const string RecordType = "RecordType"; public const string FileExtension = "FileExtension"; public const string IsProjectPlan = "IsProjectPlan"; public const string DocumentType = "DocumentType"; public const string Status = "Status"; public const string RecordVersion = "RecordVersion"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; } public static Document Read(bool includeVoid = false, int docuid = 0, string doccuid = "") { var retdocument = new Document(); // --------------- // EA SQL database // --------------- bool ret = false; string commandString = ""; string sincludeVoid = " AND DOC.IsVoid = 'N' "; if (includeVoid) sincludeVoid = " "; if (docuid > 0) { commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " FROM Document DOC" + " WHERE " + " DOC.UID = {0} " + sincludeVoid, docuid); } else { commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " FROM Document DOC " + " WHERE " + " DOC.IsVoid = 'N' " + " AND DOC.CUID = '{0}' ", doccuid); } using (var connection = new OdbcConnection(ConnString.ConnectionString)) { using (var command = new OdbcCommand( commandString, connection)) { connection.Open(); OdbcDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadDocumentFromReader(retdocument, "DOC", reader); ret = true; } catch (Exception) { retdocument.CUID = ""; retdocument.UID = 0; retdocument.Name = "Not found UID " + retdocument.UID.ToString("0000") + " CUID: " + retdocument.CUID; retdocument.FileName = "Not found UID " + retdocument.UID.ToString("0000") + " CUID: " + retdocument.CUID; retdocument.RecordType = ""; } } } } return retdocument; } public static string SQLDocumentConcat(string tablePrefix) { string ret = " " + tablePrefix + ".UID " + tablePrefix + "UID, " + tablePrefix + ".CUID " + tablePrefix + "CUID, " + tablePrefix + ".Name " + tablePrefix + "Name, " + tablePrefix + ".DisplayName " + tablePrefix + "DisplayName, " + tablePrefix + ".SequenceNumber " + tablePrefix + "SequenceNumber, " + tablePrefix + ".IssueNumber " + tablePrefix + "IssueNumber, " + tablePrefix + ".Location " + tablePrefix + "Location, " + tablePrefix + ".Comments " + tablePrefix + "Comments, " + tablePrefix + ".FileName " + tablePrefix + "FileName, " + tablePrefix + ".Status " + tablePrefix + "Status, " + tablePrefix + ".SimpleFileName " + tablePrefix + "SimpleFileName, " + tablePrefix + ".SourceCode " + tablePrefix + "SourceCode, " + tablePrefix + ".FKClientUID " + tablePrefix + "FKClientUID, " + tablePrefix + ".IsVoid " + tablePrefix + "IsVoid, " + tablePrefix + ".Skip " + tablePrefix + "Skip, " + tablePrefix + ".ParentUID " + tablePrefix + "ParentUID, " + tablePrefix + ".RecordType " + tablePrefix + "RecordType, " + tablePrefix + ".FileExtension " + tablePrefix + "FileExtension, " + tablePrefix + ".IsProjectPlan " + tablePrefix + "IsProjectPlan, " + tablePrefix + ".DocumentType " + tablePrefix + "DocumentType, " + tablePrefix + ".RecordVersion " + tablePrefix + "RecordVersion, " + tablePrefix + ".UpdateDateTime " + tablePrefix + "UpdateDateTime, " + tablePrefix + ".CreationDateTime " + tablePrefix + "CreationDateTime, " + tablePrefix + ".UserIdCreatedBy " + tablePrefix + "UserIdCreatedBy, " + tablePrefix + ".UserIdUpdatedBy " + tablePrefix + "UserIdUpdatedBy "; return ret; } /// <summary> /// Retrieve the name of the document /// </summary> /// <param name="documentUID"></param> /// <returns></returns> public static string GetName(int documentUID) { string ret = ""; // // EA SQL database // using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = " SELECT Name " + " FROM Document" + " WHERE UID = @UID "; using (var command = new OdbcCommand( commandString, connection)) { command.Parameters.Add("@UID", OdbcType.BigInt).Value = documentUID; connection.Open(); OdbcDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { ret = reader["Name"].ToString(); } catch (Exception exception) { LogFile.WriteToTodaysLogFile("Error retrieving name: " + exception, "", "", "RepOdbcDocument.cs"); } } } } return ret; } public string GetDocumentLocationAndName() { string ret = ""; Read(); ret = Utils.getFilePathName(this.Location, this.Name); return ret; } // // Set void flag (Logical Delete) // public static void SetToVoid(int DocumentUID) { string ret = "Item updated successfully"; using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE Document " + " SET " + " IsVoid = @IsVoid" + " WHERE UID = @UID " ); using (var command = new OdbcCommand( commandString, connection)) { command.Parameters.Add("@UID", OdbcType.BigInt).Value = DocumentUID; command.Parameters.Add("@IsVoid", OdbcType.VarChar).Value = 'Y'; connection.Open(); command.ExecuteNonQuery(); } } return; } // // Physical Delete // public static void Delete(int DocumentUID) { string ret = "Item updated successfully"; using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = ( "DELETE Document " + " WHERE UID = @UID " ); using (var command = new OdbcCommand( commandString, connection)) { command.Parameters.Add("@UID", OdbcType.BigInt).Value = DocumentUID; connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Add new Document /// </summary> /// <returns></returns> private static int Add(HeaderInfo headerInfo, FCMMySQLBusinessLibrary.Model.ModelDocument.Document docadd) { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; docadd.UID = _uid; if (string.IsNullOrEmpty(docadd.Status)) docadd.Status = "ACTIVE"; docadd.UserIdCreatedBy = headerInfo.UserID; docadd.UserIdUpdatedBy = headerInfo.UserID; docadd.CreationDateTime = headerInfo.CurrentDateTime; docadd.UpdateDateTime = headerInfo.CurrentDateTime; docadd.IsVoid = "N"; docadd.Skip = "N"; docadd.Status = "ACTIVE"; docadd.RecordVersion = 1; if (string.IsNullOrEmpty(docadd.DisplayName)) docadd.DisplayName = "TBA"; using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO Document " + "( " + DocumentFieldString() + ")" + " VALUES " + "( " + " @" + FieldName.UID + ", @" + FieldName.CUID + ", @" + FieldName.Name + ", @" + FieldName.DisplayName + ", @" + FieldName.SequenceNumber + ", @" + FieldName.IssueNumber + ", @" + FieldName.Location + ", @" + FieldName.Comments + ", @" + FieldName.FileName + ", @" + FieldName.Status + ", @" + FieldName.SimpleFileName + ", @" + FieldName.SourceCode + ", @" + FieldName.FKClientUID + ", @" + FieldName.IsVoid + ", @" + FieldName.Skip + ", @" + FieldName.ParentUID + ", @" + FieldName.RecordType + ", @" + FieldName.FileExtension + ", @" + FieldName.IsProjectPlan + ", @" + FieldName.DocumentType + ", @" + FieldName.RecordVersion + ", @" + FieldName.UpdateDateTime + ", @" + FieldName.CreationDateTime + ", @" + FieldName.UserIdCreatedBy + ", @" + FieldName.UserIdUpdatedBy + " ) " ); using (var command = new OdbcCommand( commandString, connection)) { command.Parameters.Add("@UID", OdbcType.BigInt).Value = docadd.UID; command.Parameters.Add( "@CUID", OdbcType.VarChar ).Value = docadd.CUID; command.Parameters.Add( "@Name", OdbcType.VarChar ).Value = docadd.Name; command.Parameters.Add( "@DisplayName", OdbcType.VarChar ).Value = docadd.DisplayName; command.Parameters.Add( "@SequenceNumber", OdbcType.VarChar ).Value = docadd.SequenceNumber; command.Parameters.Add( "@IssueNumber", OdbcType.Decimal ).Value = docadd.IssueNumber; command.Parameters.Add( "@Location", OdbcType.VarChar ).Value = docadd.Location; command.Parameters.Add( "@Comments", OdbcType.VarChar ).Value = docadd.Comments; command.Parameters.Add( "@FileName", OdbcType.VarChar ).Value = docadd.FileName; command.Parameters.Add( "@SimpleFileName", OdbcType.VarChar ).Value = docadd.SimpleFileName; command.Parameters.Add( "@SourceCode", OdbcType.VarChar ).Value = docadd.SourceCode; command.Parameters.Add("@FKClientUID", OdbcType.BigInt).Value = docadd.FKClientUID; command.Parameters.Add( "@IsVoid", OdbcType.VarChar ).Value = docadd.IsVoid; command.Parameters.Add( "@Skip", OdbcType.VarChar ).Value = docadd.Skip; command.Parameters.Add( "@ParentUID", OdbcType.VarChar ).Value = docadd.ParentUID; command.Parameters.Add( "@RecordType", OdbcType.VarChar ).Value = docadd.RecordType; command.Parameters.Add( "@IsProjectPlan", OdbcType.VarChar ).Value = docadd.IsProjectPlan; command.Parameters.Add( "@DocumentType", OdbcType.VarChar ).Value = docadd.DocumentType; command.Parameters.Add( "@FileExtension", OdbcType.VarChar ).Value = docadd.FileExtension; command.Parameters.Add( "@Status", OdbcType.VarChar ).Value = docadd.Status; command.Parameters.Add( "@RecordVersion", OdbcType.VarChar ).Value = docadd.RecordVersion; command.Parameters.Add( "@UserIdCreatedBy", OdbcType.VarChar ).Value = docadd.UserIdCreatedBy; command.Parameters.Add( "@UserIdUpdatedBy", OdbcType.VarChar ).Value = docadd.UserIdUpdatedBy; command.Parameters.Add( "@CreationDateTime", OdbcType.DateTime ).Value = docadd.CreationDateTime; command.Parameters.Add( "@UpdateDateTime", OdbcType.DateTime ).Value = docadd.UpdateDateTime; connection.Open(); try { command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Error adding new document." + ex.ToString(), headerInfo.UserID, "Document.cs" ); LogFile.WriteToTodaysLogFile( "SQL String: " + commandString, headerInfo.UserID, "Document.cs" ); // Error _uid = 0; } } } return _uid; } // ----------------------------------------------------- // Update Document Version // ----------------------------------------------------- private static void UpdateVersion(HeaderInfo headerInfo, FCMMySQLBusinessLibrary.Model.ModelDocument.Document indocument) { string ret = "Item updated successfully"; using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE Document " + " SET " + " Name = @Name " + ",IssueNumber = @IssueNumber" + ",Location = @Location" + ",FileName = @FileName" + " WHERE CUID = @CUID " ); using (var command = new OdbcCommand( commandString, connection)) { command.Parameters.Add("@CUID", OdbcType.VarChar).Value = indocument.CUID; command.Parameters.Add("@Name", OdbcType.VarChar).Value = indocument.Name; command.Parameters.Add("@IssueNumber", OdbcType.Decimal).Value = indocument.IssueNumber; command.Parameters.Add("@Location", OdbcType.VarChar).Value = indocument.Location; command.Parameters.Add("@FileName", OdbcType.VarChar).Value = indocument.FileName; connection.Open(); try { command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Error updating document version." + ex.ToString(), headerInfo.UserID, "Document.cs" ); } } } return; } /// <summary> /// Get Root document. If it does not exits, create a root document. /// </summary> public static FCMMySQLBusinessLibrary.Model.ModelDocument.Document GetRoot(HeaderInfo headerInfo) { FCMMySQLBusinessLibrary.Model.ModelDocument.Document docreturn = new FCMMySQLBusinessLibrary.Model.ModelDocument.Document(); docreturn.CUID = "ROOT"; docreturn.Name = "FCM Documents"; docreturn.RecordType = Utils.RecordType.FOLDER; docreturn.UID = 0; docreturn = RepDocument.Read(true,0, docreturn.CUID); if (docreturn.UID <= 0) // Document not found { // Create root // docreturn.CUID = "ROOT"; docreturn.RecordVersion = 1; docreturn.Name = "FCM Documents"; docreturn.DisplayName = "FCM Documents"; docreturn.RecordType = Utils.RecordType.FOLDER; docreturn.Comments = "Created automatically."; docreturn.DocumentType = Utils.DocumentType.FOLDER; docreturn.FileName = "ROOT"; docreturn.FKClientUID = 0; docreturn.IsProjectPlan = "N"; docreturn.IssueNumber = 0; docreturn.IsVoid = "N"; docreturn.Skip = "N"; docreturn.Location = "ROOT"; docreturn.RecordType = Utils.RecordType.FOLDER; docreturn.SequenceNumber = 0; docreturn.SimpleFileName = "ROOT"; docreturn.UID = 0; docreturn.SourceCode = Utils.SourceCode.FCM; docreturn.FileExtension = "ROOT"; Save(headerInfo, docreturn); } return docreturn; } // ----------------------------------------------------- // Update Document // ----------------------------------------------------- private static int Update(HeaderInfo headerInfo, FCMMySQLBusinessLibrary.Model.ModelDocument.Document docupdate) { string ret = "Item updated successfully"; docupdate.UserIdUpdatedBy = Utils.UserID; docupdate.UpdateDateTime = System.DateTime.Now; using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE Document " + " SET " + " CUID = @CUID " + ",Name = @Name " + ",DisplayName = @DisplayName " + ",SequenceNumber = @SequenceNumber " + ",IssueNumber = @IssueNumber" + ",Location = @Location" + ",Comments = @Comments " + ",FileName = @FileName" + ",SimpleFileName = @SimpleFileName" + ",SourceCode = @SourceCode " + ",IsProjectPlan = @IsProjectPlan " + ",FKClientUID = @FKClientUID " + ",ParentUID = @ParentUID " + ",DocumentType = @DocumentType " + ",UserIdUpdatedBy = @UserIdUpdatedBy " + ",UpdateDateTime = @UpdateDateTime " + " WHERE UID = @UID " ); using (var command = new OdbcCommand( commandString, connection)) { command.Parameters.Add("@UID", OdbcType.VarChar).Value = docupdate.UID; command.Parameters.Add("@CUID", OdbcType.VarChar).Value = docupdate.CUID; command.Parameters.Add("@Name", OdbcType.VarChar).Value = docupdate.Name; command.Parameters.Add("@DisplayName", OdbcType.VarChar).Value = docupdate.DisplayName; command.Parameters.Add("@SequenceNumber", OdbcType.VarChar).Value = docupdate.SequenceNumber; command.Parameters.Add("@IssueNumber", OdbcType.Decimal).Value = docupdate.IssueNumber; command.Parameters.Add("@Location", OdbcType.VarChar).Value = docupdate.Location; command.Parameters.Add("@IsProjectPlan", OdbcType.VarChar).Value = docupdate.IsProjectPlan; command.Parameters.Add("@Comments", OdbcType.VarChar).Value = docupdate.Comments; command.Parameters.Add("@FileName", OdbcType.VarChar).Value = docupdate.FileName; command.Parameters.Add("@SimpleFileName", OdbcType.VarChar).Value = docupdate.SimpleFileName; command.Parameters.Add("@SourceCode", OdbcType.VarChar).Value = docupdate.SourceCode; command.Parameters.Add("@FKClientUID", OdbcType.BigInt).Value = docupdate.FKClientUID; command.Parameters.Add("@ParentUID", OdbcType.BigInt).Value = docupdate.ParentUID; command.Parameters.Add("@DocumentType", OdbcType.VarChar).Value = docupdate.DocumentType; command.Parameters.Add("@UserIdUpdatedBy", OdbcType.VarChar).Value = docupdate.UserIdUpdatedBy; command.Parameters.Add("@UpdateDateTime", OdbcType.DateTime).Value = docupdate.UpdateDateTime; connection.Open(); try { command.ExecuteNonQuery(); } catch (Exception ex) { LogFile.WriteToTodaysLogFile( "Error updating document." + ex.ToString(), headerInfo.UserID, "Document.cs" ); } } } return docupdate.UID; } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private static int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM Document"; using (var command = new OdbcCommand( commandString, connection)) { connection.Open(); OdbcDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add or Update a record /// </summary> /// <param name="type">In case of an update, checks the issue number /// </param> /// <returns></returns> public static int Save(HeaderInfo headerInfo, Document indocument, string type = null) { // Check if code value exists. // If it exists, update // Else Add a new one int uidReturn = 0; FCMMySQLBusinessLibrary.Model.ModelDocument.Document currentdocument = Read(false, indocument.UID); if (currentdocument.UID > 0) { // If it is a new issue, save the old issue in the issue table // if (currentdocument.IssueNumber == indocument.IssueNumber) { if (type == Utils.SaveType.UPDATE) { // Update location - use reference path instead of fixed path var destLocationDerivedClient = Utils.getReferenceFilePathName(indocument.Location); indocument.Location = destLocationDerivedClient; uidReturn = Update(headerInfo, indocument); } } else { LogFile.WriteToTodaysLogFile( "Document Save - issue number is different. CUID: " + indocument.CUID, headerInfo.UserID, "Document.cs" ); } } else { uidReturn = Add(headerInfo, indocument); } return uidReturn; } // ----------------------------------------------------- // Create new document version // ----------------------------------------------------- public static DocumentNewVersionResponse NewVersion( HeaderInfo headerInfo, Document document ) { DocumentNewVersionResponse responseNewVersion = new DocumentNewVersionResponse(); responseNewVersion.response = new ResponseStatus(); responseNewVersion.response.Message = "New version created successfully."; // Update location - use reference path instead of fixed path var destLocationDerivedClient = Utils.getReferenceFilePathName( document.Location ); document.Location = destLocationDerivedClient; // Copy existing version to old folder version // Old folder comes from %VERSIONFOLDER% // var versionFolder = CodeValue.GetCodeValueExtended(MakConstant.CodeTypeString.SYSTSET, MakConstant.SYSFOLDER.VERSIONFOLDER); // Create a record to point to the old version var documentVersion = new DocumentVersion(); documentVersion.FKDocumentCUID = document.CUID; documentVersion.FKDocumentUID = document.UID; // Generate the new version id documentVersion.IssueNumber = document.IssueNumber; documentVersion.Location = Utils.GetVersionPath(document.Location); documentVersion.FileName = document.FileName; documentVersion.Add(); // Increments issue number document.IssueNumber++; // Create a new file name with version on it // POL-05-01 FILE NAME.doc // int version = Convert.ToInt32(document.IssueNumber); string tversion = version.ToString().PadLeft(2, '0'); // 12/02/2013 - Daniel - I am not sure if the number is POL-01 or POL-01-02 // It was 10, today it was 7, now I am making it 10 again... something will go wrong :-( // string simpleFileName = document.Name.Substring( 10 ).Trim(); // string simpleFileName = document.Name.Substring(07).Trim(); string newFileName = document.CUID + '-' + tversion + ' ' + simpleFileName; // string newFileNameWithExtension = newFileName + ".doc"; // Well, the simple file name has extension already... so I have commented out the line above // 30/04/2011 - Testing to see if it works. // string newFileNameWithExtension = newFileName; // Copy the file with new name // Let's copy the document //string realLocation = Utils.getFilePathName(document.Location, document.FileName); //string realDestination = Utils.getFilePathName(documentVersion.Location, documentVersion.FileName); //string realPathDestination = Utils.getFilePathName( documentVersion.Location ); string realLocation = Utils.getFilePathNameLOCAL( document.Location, document.FileName ); string realDestination = Utils.getFilePathNameLOCAL( documentVersion.Location, documentVersion.FileName ); string realPathDestination = Utils.getFilePathNameLOCAL( documentVersion.Location ); if (!System.IO.Directory.Exists(realPathDestination)) System.IO.Directory.CreateDirectory(realPathDestination); if (!System.IO.File.Exists(realLocation)) { responseNewVersion.response.Message = "File to be copied was not found. " + realLocation; responseNewVersion.response.ReturnCode = -0010; responseNewVersion.response.ReasonCode = 0001; responseNewVersion.response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000006; return responseNewVersion; } File.Copy(realLocation, realDestination, true); // Copy file to new name // string newFilePathName = Utils.getFilePathNameLOCAL(document.Location,newFileNameWithExtension); File.Copy(realLocation, newFilePathName, true); // Delete old version from main folder // try { File.Delete(realLocation); } catch (Exception ex) { responseNewVersion.response.Message = "Error deleting file. " + realLocation; responseNewVersion.response.ReturnCode = -0010; responseNewVersion.response.ReasonCode = 0004; responseNewVersion.response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00000006; LogFile.WriteToTodaysLogFile( responseNewVersion.response.Message + " " + ex.ToString(), "", "", "Document.cs" ); return responseNewVersion; } // Update document details - version, name, etc document.IssueNumber = version; // this.ComboIssueNumber = "C" + version. ; document.FileName = newFileNameWithExtension; document.Name = newFileName; // this.UpdateVersion(headerInfo); RepDocument.UpdateVersion(headerInfo, document ); // Build a screen to browse all versions of a file // Allow compare/ View // Check how to open a responseNewVersion.outDocument = new Document(); responseNewVersion.outDocument = RepDocument.Read( true, document.UID ); responseNewVersion.response.Contents = version; return responseNewVersion; } /// <summary> /// Load a document from a given reader /// </summary> /// <param name="retDocument"></param> /// <param name="tablePrefix"></param> /// <param name="reader"></param> public static void LoadDocumentFromReader( FCMMySQLBusinessLibrary.Model.ModelDocument.Document retDocument, string tablePrefix, OdbcDataReader reader) { retDocument.UID = Convert.ToInt32(reader[tablePrefix + FieldName.UID].ToString()); retDocument.CUID = reader[tablePrefix + FieldName.CUID].ToString(); retDocument.Name = reader[tablePrefix + FieldName.Name].ToString(); retDocument.DisplayName = reader[tablePrefix + FieldName.DisplayName].ToString(); retDocument.SequenceNumber = Convert.ToInt32(reader[tablePrefix + FieldName.SequenceNumber].ToString()); retDocument.IssueNumber = Convert.ToInt32(reader[tablePrefix + FieldName.IssueNumber].ToString()); retDocument.Location = reader[tablePrefix + FieldName.Location].ToString(); retDocument.Comments = reader[tablePrefix + FieldName.Comments].ToString(); retDocument.SourceCode = reader[tablePrefix + FieldName.SourceCode].ToString(); retDocument.FileName = reader[tablePrefix + FieldName.FileName].ToString(); retDocument.SimpleFileName = reader[tablePrefix + FieldName.SimpleFileName].ToString(); retDocument.FKClientUID = Convert.ToInt32(reader[tablePrefix + FieldName.FKClientUID].ToString()); retDocument.ParentUID = Convert.ToInt32(reader[tablePrefix + FieldName.ParentUID].ToString()); retDocument.RecordType = reader[tablePrefix + FieldName.RecordType].ToString(); retDocument.IsProjectPlan = reader[tablePrefix + FieldName.IsProjectPlan].ToString(); retDocument.IsVoid = reader [tablePrefix + FieldName.IsVoid].ToString(); retDocument.Skip = reader [tablePrefix + FieldName.Skip].ToString(); retDocument.DocumentType = reader [tablePrefix + FieldName.DocumentType].ToString(); retDocument.RecordVersion = Convert.ToInt32(reader[tablePrefix + FieldName.RecordVersion].ToString()); //try { retDocument.UpdateDateTime = Convert.ToDateTime(reader[FieldName.UpdateDateTime].ToString()); } //catch { retDocument.UpdateDateTime = DateTime.Now; } //try { retDocument.CreationDateTime = Convert.ToDateTime(reader[FieldName.CreationDateTime].ToString()); } //catch { retDocument.CreationDateTime = DateTime.Now; } //try { retDocument.IsVoid = reader[FieldName.IsVoid].ToString(); } //catch { retDocument.IsVoid = "N"; } //try { retDocument.UserIdCreatedBy = reader[FieldName.UserIdCreatedBy].ToString(); } //catch { retDocument.UserIdCreatedBy = "N"; } //try { retDocument.UserIdUpdatedBy = reader[FieldName.UserIdCreatedBy].ToString(); } //catch { retDocument.UserIdCreatedBy = "N"; } return; } /// <summary> /// Returns a string to be concatenated with a SQL statement /// </summary> /// <param name="tablePrefix"></param> /// <returns></returns> /// <summary> /// Document string of fields. /// </summary> /// <returns></returns> private static string DocumentFieldString() { return ( FieldName.UID + "," + FieldName.CUID + "," + FieldName.Name + "," + FieldName.DisplayName + "," + FieldName.SequenceNumber + "," + FieldName.IssueNumber + "," + FieldName.Location + "," + FieldName.Comments + "," + FieldName.FileName + "," + FieldName.Status + "," + FieldName.SimpleFileName + "," + FieldName.SourceCode + "," + FieldName.FKClientUID + "," + FieldName.IsVoid + "," + FieldName.Skip + "," + FieldName.ParentUID + "," + FieldName.RecordType + "," + FieldName.FileExtension + "," + FieldName.IsProjectPlan + "," + FieldName.DocumentType + "," + FieldName.RecordVersion + "," + FieldName.UpdateDateTime + "," + FieldName.CreationDateTime + "," + FieldName.UserIdCreatedBy + "," + FieldName.UserIdUpdatedBy ); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public void ListProjectPlans(HeaderInfo headerInfo) { List(headerInfo, " AND IsProjectPlan = 'Y' "); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public static List<Document> List(HeaderInfo headerInfo) { return List(headerInfo, null); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public static List<Document> ListDocuments( HeaderInfo headerInfo ) { return List( headerInfo, " AND DOC.RecordType = 'DOCUMENT' " ); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public static List<Document> ListFolders( HeaderInfo headerInfo ) { return List( headerInfo, " AND DOC.RecordType = 'FOLDER' " ); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public static List<Document> List(HeaderInfo _headerInfo, string Condition = null) { var documentList = new List<Document>(); documentList = new List<Document>(); using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " FROM Document DOC " + " WHERE DOC.SourceCode = 'FCM' " + " AND DOC.IsVoid = 'N' " + Condition + " ORDER BY PARENTUID ASC, SequenceNumber ASC " ); using (var command = new OdbcCommand( commandString, connection)) { connection.Open(); using (OdbcDataReader reader = command.ExecuteReader()) { while (reader.Read()) { FCMMySQLBusinessLibrary.Model.ModelDocument.Document _Document = new FCMMySQLBusinessLibrary.Model.ModelDocument.Document(); RepDocument.LoadDocumentFromReader(_Document, "DOC", reader); documentList.Add(_Document); } } } } return documentList; } // ----------------------------------------------------- // List Documents for a Document Set // ----------------------------------------------------- public void ListDocSet(int documentSetUID) { this.documentList = new List<Document>(); using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " ,LNK.FKParentDocumentUID " + " ,LNK.FKParentDocumentSetUID " + " ,LNK.SequenceNumber " + " FROM Document DOC " + " ,DocumentSetDocument LNK" + " WHERE " + " LNK.FKDocumentUID = DOC.UID " + " AND DOC.SourceCode = 'FCM' " + " AND LNK.IsVoid = 'N' " + " AND DOC.IsVoid = 'N' " + " AND LNK.FKDocumentSetUID = {0} " + " ORDER BY LNK.FKParentDocumentUID ASC, LNK.SequenceNumber ", documentSetUID ); using (var command = new OdbcCommand( commandString, connection)) { connection.Open(); using (OdbcDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Document _Document = new Document(); RepDocument.LoadDocumentFromReader(_Document, "DOC", reader); // This is necessary because when the list comes from DocumentSet, the parent may change // _Document.ParentUID = Convert.ToInt32(reader["FKParentDocumentUID"].ToString()); this.documentList.Add(_Document); } } } } } // ----------------------------------------------------- // Load documents in a tree // ----------------------------------------------------- public static void ListInTree( TreeView fileList, DocumentList documentList, FCMMySQLBusinessLibrary.Model.ModelDocument.Document root) { // Find root folder // FCMMySQLBusinessLibrary.Model.ModelDocument.Document rootDocument = new FCMMySQLBusinessLibrary.Model.ModelDocument.Document(); rootDocument.CUID = root.CUID; rootDocument.RecordType = root.RecordType; rootDocument.UID = root.UID; // rootDocument.Read(); rootDocument = RepDocument.Read(false, root.UID); // Create root // var rootNode = new TreeNode(rootDocument.Name, MakConstant.Image.Folder, MakConstant.Image.Folder); // Add root node to tree // fileList.Nodes.Add(rootNode); rootNode.Tag = rootDocument; rootNode.Name = rootDocument.Name; foreach (var document in documentList.documentList) { // Ignore root folder if (document.CUID == "ROOT") continue; // Check if folder has a parent string cdocumentUID = document.UID.ToString(); string cparentIUID = document.ParentUID.ToString(); int image = 0; int imageSelected = 0; document.RecordType = document.RecordType.Trim(); #region Image switch (document.DocumentType) { case Utils.DocumentType.WORD: image = MakConstant.Image.Word32; imageSelected = MakConstant.Image.Word32; // I have to think about this... // if (document.RecordType == Utils.RecordType.APPENDIX) { image = MakConstant.Image.Appendix; imageSelected = MakConstant.Image.Appendix; } break; case Utils.DocumentType.EXCEL: image = MakConstant.Image.Excel; imageSelected = MakConstant.Image.Excel; break; case Utils.DocumentType.FOLDER: image = MakConstant.Image.Folder; imageSelected = MakConstant.Image.Folder; break; case Utils.DocumentType.PDF: image = MakConstant.Image.PDF; imageSelected = MakConstant.Image.PDF; break; default: image = MakConstant.Image.Word32; imageSelected = MakConstant.Image.Word32; break; } #endregion Image if (document.ParentUID == 0) { var treeNode = new TreeNode(document.Name, image, image); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find(cparentIUID, true); if (node.Count( ) > 0) { var treeNode = new TreeNode(document.Name, image, imageSelected); treeNode.Tag = document; treeNode.Name = cdocumentUID; node[0].Nodes.Add(treeNode); } else { // Add Element to the root // var treeNode = new TreeNode(document.Name, image, imageSelected); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add(treeNode); } } } } // ----------------------------------------------------- // List Documents for a client // ----------------------------------------------------- public void ListClient(int clientUID) { this.documentList = new List<Document>(); using (var connection = new OdbcConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " FROM Document DOC " + " WHERE SourceCode = 'CLIENT' " + " AND FKClientUID = {0} " + " AND IsVoid <> 'Y' " + " ORDER BY PARENTUID ASC, SequenceNumber ASC ", clientUID); using (var command = new OdbcCommand( commandString, connection)) { connection.Open(); using (OdbcDataReader reader = command.ExecuteReader()) { while (reader.Read()) { FCMMySQLBusinessLibrary.Model.ModelDocument.Document _Document = new FCMMySQLBusinessLibrary.Model.ModelDocument.Document(); RepDocument.LoadDocumentFromReader(_Document, "DOC", reader); documentList.Add(_Document); } } } } } /// <summary> /// Update single field in document /// </summary> /// <param name="UID"></param> /// <param name="fieldName"></param> /// <param name="contents"></param> public void UpdateFieldString( int UID, string fieldName, string contents ) { string ret = "Item updated successfully"; using ( var connection = new OdbcConnection( ConnString.ConnectionString ) ) { var commandString = ( "UPDATE Document " + " SET " + fieldName + "= @contents " + " WHERE UID = @UID " ); using ( var command = new OdbcCommand( commandString, connection ) ) { command.Parameters.Add( "@UID", OdbcType.BigInt ).Value = UID; command.Parameters.Add( "@contents", OdbcType.VarChar ).Value = contents; connection.Open(); command.ExecuteNonQuery(); } } return; } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelDocument; using FCMMySQLBusinessLibrary.Model.ModelMetadata; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Service.SVCClient.ServiceContract; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Security; using MackkadoITFramework.Utils; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Repository; using FCMMySQLBusinessLibrary.Repository.RepositoryClient; namespace fcm.Windows { public partial class UIClientDetails : Form { private Form _callingForm; private int currentRowPosition; private Client original; private Client client; private ClientExtraInformation clientExtraInformation; public ResponseStatus response { get; set; } public List<Client> clientList { set; get; } public List<ClientContract> clientContractList { set; get; } public ClientContract clientContract { set; get; } /// <summary> /// Constructor /// </summary> /// <param name="callingForm"></param> public UIClientDetails(Form callingForm) { _callingForm = callingForm; InitializeComponent(); original = new Client(HeaderInfo.Instance); setCurrentRowPosition(0); clientContractList = new List<ClientContract>(); clientContract = new ClientContract(); clientList = new List<Client>(); // bindingSourceClient.DataSource = clientList; bsClient.DataSource = clientList; client = new Client(HeaderInfo.Instance); clientExtraInformation = new ClientExtraInformation(); // Load User ID // var ua = UserAccess.List(); foreach (var user in ua) { comboUserID.Items.Add(user.UserID); } // Load Contractor Size // DocumentSetList dsl = new DocumentSetList(); dsl.List(); foreach (var documentSet in dsl.documentSetList) { comboContractorSize.Items.Add(documentSet.UIDNameDisplay); } // ucClientOtherInfo1.PopulateData(Utils.ClientID); } /// <summary> /// Set current row position /// </summary> /// <param name="currRow"></param> private void setCurrentRowPosition(int currRow) { // Set the variable that controls the current row currentRowPosition = currRow; } // -------------------------------------------------- // Save click // -------------------------------------------------- private void btnSave_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; SaveClient(); Cursor.Current = Cursors.Arrow; } private void checkDisplayLogo_CheckedChanged( object sender, EventArgs e ) { // UpdateLogoStatus(); } private void ClientDetails_Load(object sender, EventArgs e) { ListClient(); ListClientContract(); } /// <summary> /// List employees /// </summary> private void ListClientContract() { var response = BUSClientContract.ClientContractList(Utils.ClientID); clientContractList = (List<ClientContract>)response.Contents; try { clientContractBindingSource.DataSource = clientContractList; } catch (Exception ex) { MessageBox.Show("P2 " + ex.ToString()); } return; } private void btnAddNewClient_Click(object sender, EventArgs e) { txtABN.Text = ""; txtAddress.Text = ""; txtContactPerson.Text = ""; txtEmailAddress.Text = ""; txtFax.Text = ""; txtName.Text = ""; txtPhone.Text = ""; txtUID.Text = ""; cbxAssociateInitialSet.Checked = false; comboContractorSize.Text = ""; comboUserID.Text = ""; Bitmap MyImage; pbxLogo.SizeMode = PictureBoxSizeMode.StretchImage; string filePathName = Utils.getFilePathName(FCMConstant.SYSFOLDER.LOGOFOLDER, "imgNoImage.jpg"); MyImage = new Bitmap(filePathName); pbxLogo.Image = (Image)MyImage; Utils.ClientID = 0; } private void dgvClientList_SelectionChanged(object sender, EventArgs e) { ShowClientDetails(); int t = 0; if (dgvClientList.CurrentRow == null) t = 0; else t = dgvClientList.CurrentRow.Index; setCurrentRowPosition(t); } private void btnDocuments_Click(object sender, EventArgs e) { UIClientDocumentSet ucds = new UIClientDocumentSet(); ucds.Show(); } private void dgvClientList_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); if (_callingForm != null) { _callingForm.Show(); _callingForm.Activate(); } } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { var answer = MessageBox.Show("Are you sure? Do you really want to delete the client?", "Delete Client", MessageBoxButtons.YesNo); if (answer == DialogResult.Yes) { Client client = new Client(HeaderInfo.Instance); client.UID = Utils.ClientID; var response = new BUSClient().ClientDelete(new ClientDeleteRequest() { clientUID = client.UID, headerInfo = HeaderInfo.Instance }); ListClient(); } } private void txtUID_TextChanged(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtUID.Text)) { pbxLogo.Enabled = false; } else { pbxLogo.Enabled = true; } } private void btnChangeLogo_Click(object sender, EventArgs e) { // Show file dialog var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; // Extract File Path string pathOnly = fullPathFileName.Replace(fileName, ""); // Get Company Logo // ReportMetadata rmd = new ReportMetadata(); rmd.ClientUID = Utils.ClientID; rmd.RecordType = FCMConstant.MetadataRecordType.CLIENT; rmd.FieldCode = "COMPANYLOGO"; rmd.Read(clientUID: Utils.ClientID, fieldCode: "COMPANYLOGO"); rmd.InformationType = MackkadoITFramework.Helper.Utils.InformationType.IMAGE; rmd.ClientType = ""; rmd.CompareWith = ""; rmd.Description = "Company"; // rmd.Condition = fullPathFileName; var logoFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.LOGOFOLDER); // rmd.Condition = logoFolder + fileName; // The intention is to save the reference path %XXX% // rmd.Condition = FCMConstant.SYSFOLDER.LOGOFOLDER + fileName; rmd.Save(); Bitmap MyImage; pbxLogo.SizeMode = PictureBoxSizeMode.StretchImage; if (rmd.Condition != null) { // MyImage = new Bitmap(rmd.Condition); MyImage = new Bitmap(logoFolder + fileName); pbxLogo.Image = (Image)MyImage; } } } private bool dataHasChanged() { bool UnsavedData; if (txtName.Text == original.Name && txtABN.Text == original.ABN && txtAddress.Text == original.Address && txtContactPerson.Text == original.MainContactPersonName && txtEmailAddress.Text == original.EmailAddress && txtFax.Text == original.Fax && txtPhone.Text == original.Phone) { UnsavedData = false; } else { UnsavedData = true; } return UnsavedData; } private void tsRefresh_Click( object sender, EventArgs e ) { ListClient(); // loadClientList( Utils.ClientID ); } private void dgvClientList_CellMouseDown( object sender, DataGridViewCellMouseEventArgs e ) { if( e.ColumnIndex >= 0 && e.RowIndex >= 0 ) { dgvClientList.CurrentCell = dgvClientList.Rows[e.RowIndex].Cells[ e.ColumnIndex ]; } } // ------------------------------------------------------ // IClientDetails implemented // ------------------------------------------------------ private void ListClient() { var clientList = new Client(HeaderInfo.Instance); // bindingSourceClient.DataSource = clientList; bsClient.DataSource = clientList; } /// <summary> /// Display message on client /// </summary> /// <param name="msg"></param> public void DisplayMessage(string msg) { MessageBox.Show(msg); return; } /// <summary> /// Add/ Update client /// </summary> /// <param name="client"></param> public void SaveClient() { if (string.IsNullOrEmpty(txtUID.Text)) client.UID = 0; else client.UID = Convert.ToInt32(txtUID.Text); client.ABN = txtABN.Text; client.Name = txtName.Text; client.Address = txtAddress.Text; client.Phone = txtPhone.Text; client.Fax = txtFax.Text; client.EmailAddress = txtEmailAddress.Text; client.MainContactPersonName = txtContactPerson.Text; client.FKUserID = comboUserID.Text; client.DocSetUIDDisplay = comboContractorSize.Text; if (string.IsNullOrEmpty(client.DocSetUIDDisplay )) { client.FKDocumentSetUID = 0; } else { string[] part = client.DocSetUIDDisplay.Split(';'); client.FKDocumentSetUID = Convert.ToInt32(part[0]); } client.DisplayLogo = checkDisplayLogo.Checked ? 'Y' : 'N'; // Check if it is to add / update if (client.UID <= 0) { string associateInitialSet = "N"; if (cbxAssociateInitialSet.Checked) associateInitialSet = "Y"; var response = new BUSClient().ClientAdd(new ClientAddRequest() { headerInfo = HeaderInfo.Instance, eventClient = client, linkInitialSet = associateInitialSet }); } else { var response = new BUSClient().ClientUpdate( new ClientUpdateRequest() { eventClient = client, headerInfo = HeaderInfo.Instance } ); ReplaceRowSelected(); } // Refresh client list // Utils.ClientID = client.UID; var responseClientList = new BUSClient().ClientList(HeaderInfo.Instance); Utils.ClientList = responseClientList.clientList; ListClient(); } /// <summary> /// Update UI grid by replacing row selected with updated details /// </summary> public void ReplaceRowSelected() { if (dgvClientList.SelectedRows.Count <= 0) return; var selectedRow = dgvClientList.SelectedRows; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.UID].Value = txtUID.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.ABN].Value = txtABN.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Name].Value = txtName.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Phone].Value = txtPhone.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Fax].Value = txtFax.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Address].Value = txtAddress.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.MainContactPersonName].Value = txtContactPerson.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.EmailAddress].Value = txtEmailAddress.Text; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.DisplayLogo].Value = checkDisplayLogo.Checked ? 'Y' : 'N'; selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.FKUserID].Value = comboUserID.Text; } /// <summary> /// Show Client Details /// </summary> public void ShowClientDetails() { if (dgvClientList.SelectedRows.Count <= 0) return; var selectedRow = dgvClientList.SelectedRows; txtUID.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.UID].Value.ToString(); txtABN.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.ABN].Value.ToString(); txtName.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Name].Value.ToString(); txtPhone.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Phone].Value.ToString(); txtFax.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Fax].Value.ToString(); txtAddress.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.Address].Value.ToString(); txtContactPerson.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.MainContactPersonName].Value.ToString(); txtEmailAddress.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.EmailAddress].Value.ToString(); comboUserID.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.FKUserID].Value.ToString(); comboContractorSize.Text = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.DocSetUIDDisplay].Value.ToString(); var dispLogo = selectedRow[0].Cells["dgv" + FCMDBFieldName.Client.DisplayLogo].Value.ToString(); checkDisplayLogo.Checked = dispLogo == "Y" ? true : false; // Store original client data // original.Name = txtName.Text; original.ABN = txtABN.Text; original.Address = txtAddress.Text; original.EmailAddress = txtEmailAddress.Text; original.Fax = txtFax.Text; original.MainContactPersonName = txtContactPerson.Name; original.Phone = txtPhone.Text; original.FKUserID = comboUserID.Text; original.DocSetUIDDisplay = comboContractorSize.Text; original.DisplayLogo = Convert.ToChar(dispLogo); Utils.ClientID = Convert.ToInt32(txtUID.Text); original.UID = Utils.ClientID; // Get Company Logo // string logoLocation = RepClient.GetClientLogoLocation(Utils.ClientID, HeaderInfo.Instance); Bitmap MyImage; MyImage = new Bitmap(logoLocation); pbxLogo.Image = (Image)MyImage; // Store selected client data // client.UID = Utils.ClientID; client.Name = txtName.Text; client.ABN = txtABN.Text; client.Address = txtAddress.Text; client.EmailAddress = txtEmailAddress.Text; client.Fax = txtFax.Text; client.MainContactPersonName = txtContactPerson.Name; client.Phone = txtPhone.Text; client.FKUserID = comboUserID.Text; client.DisplayLogo = Convert.ToChar(dispLogo); // List contracts ListClientContract(); } // ----------------------------------------------------------------- // Screen events // ----------------------------------------------------------------- private void btnContractEdit_Click(object sender, EventArgs e) { UIClientContract uicc = new UIClientContract(this, client); uicc.Show(); } /// <summary> /// Go to Employee List /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GoToEmployeeList(object sender, EventArgs e) { UIClientEmployee uce = new UIClientEmployee(client); uce.Show(); } // ----------------------------------------------------------------- // Interface IClientContract Implementation // ----------------------------------------------------------------- /// <summary> /// Reset screen from IClientContract /// </summary> public void ResetScreen() { // not implemented } private void groupBox1_Enter(object sender, EventArgs e) { } private void label11_Click(object sender, EventArgs e) { } private void label13_Click(object sender, EventArgs e) { } private void pbxLogo_Click(object sender, EventArgs e) { } // ----------------------------------------------------------------- // Handy methods // ----------------------------------------------------------------- } } <file_sep>using System.ServiceModel; using FCMMySQLBusinessLibrary.Service.SVCClient.Contract; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Interface { /// <summary> /// Interface for Client Contract Business Layer /// </summary> [ServiceContract] public interface IBUSClientContract { /// <summary> /// Add Client Contract /// </summary> /// <param name="clientAddRequest"></param> /// <returns></returns> [OperationContract] ClientContractAddResponse ClientContractAdd(ClientContractAddRequest clientAddRequest); /// <summary> /// Update Client Contract /// </summary> /// <param name="clientUpdateRequest"></param> /// <returns></returns> [OperationContract] ClientContractUpdateResponse ClientContractUpdate(ClientContractUpdateRequest clientUpdateRequest); } } <file_sep>using System; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelClientDocument { public class ClientDocumentVersion { public int UID; public int FKClientDocumentUID; public int FKClientUID; // public int ClientIssueNumber; // 03 - This is the version number of the client public int SourceIssueNumber; // 01 public string IssueNumberText; // 03 - This is the version number of the client in text public string Location; // %LOCATION%\TEST\TEST public string FileName; // POL-05-01-0001-01 FILENAME.DOC public string ComboIssueNumber; // POL-05-01-0002-03 public string DocumentCUID; // POL-05-01 // ----------------------------------------------------- // Get Client details // ----------------------------------------------------- public bool Read() { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT UID " + " ,FKClientDocumentUID " + " ,DocumentCUID " + " ,FKClientUID " + " ,IssueNumberText " + " ,ClientIssueNumber " + " ,SourceIssueNumber " + " ,Location " + " ,FileName " + " ,ComboIssueNumber " + " FROM ClientDocumentVersion" + " WHERE CUID = '{0}'", this.UID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32( reader["UID"].ToString()); this.FKClientDocumentUID = Convert.ToInt32(reader["FKClientDocumentUID"].ToString()); this.FKClientUID = Convert.ToInt32(reader["FKClientUID"].ToString()); this.IssueNumberText = reader["IssueNumberText"].ToString(); this.ClientIssueNumber = Convert.ToInt32(reader["ClientIssueNumber"].ToString()); this.SourceIssueNumber = Convert.ToInt32(reader["SourceIssueNumber"].ToString()); this.Location = reader["Location"].ToString(); this.FileName = reader["FileName"].ToString(); this.ComboIssueNumber = reader["ComboIssueNumber"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM ClientDocumentVersion"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Add new Issue // ----------------------------------------------------- public void Add() { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO ClientDocumentVersion " + " ( " + " UID " + ",FKClientDocumentUID " + ",FKClientUID " + ",IssueNumberText" + ",ComboIssueNumber" + ",ClientIssueNumber" + ",SourceIssueNumber" + ",Location" + ",FileName" + ")" + " VALUES " + " ( " + " @UID " + ", @FKClientDocumentUID " + ", @FKClientUID " + ", @IssueNumberText " + ", @ComboIssueNumber " + ", @ClientIssueNumber " + ", @SourceIssueNumber " + ", @Location " + ", @FileName " + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = _uid; command.Parameters.Add("@FKClientDocumentUID", MySqlDbType.Int32).Value = FKClientDocumentUID; command.Parameters.Add("@FKClientUID", MySqlDbType.Int32).Value = FKClientUID; command.Parameters.Add("@IssueNumberText", MySqlDbType.VarChar).Value = IssueNumberText; command.Parameters.Add("@ComboIssueNumber", MySqlDbType.VarChar).Value = ComboIssueNumber; command.Parameters.Add("@ClientIssueNumber", MySqlDbType.Decimal).Value = ClientIssueNumber; command.Parameters.Add("@SourceIssueNumber", MySqlDbType.VarChar).Value = SourceIssueNumber; command.Parameters.Add("@Location", MySqlDbType.VarChar).Value = Location; command.Parameters.Add("@FileName", MySqlDbType.VarChar).Value = FileName; connection.Open(); command.ExecuteNonQuery(); } } return; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; using System.Data; namespace FCMMySQLBusinessLibrary { public class ClientWorkHoursAllocation { public int UID { get; set; } public DateTime Date { get; set; } public int FKCompanyUID { get; set; } public int FKEmployeeUID { get; set; } public int FKTaskUID { get; set; } public int Hours { get; set; } public int FKClientWorkIsFor { get; set; } public int FKInvoiceUID { get; set; } public int FKInvoiceItemID { get; set; } private static string tableName = "ClientWorkHoursAllocation"; public enum FieldName { UID, Date, FKCompanyUID, FKEmployeeUID, FKTaskUID, Hours, FKClientWorkIsFor, FKInvoiceUID, FKInvoiceItemID } /// <summary> /// Add new Employee /// </summary> /// <returns></returns> public ResponseStatus Add() { var rs = new ResponseStatus(); rs.Message = "Client Added Successfully"; rs.ReturnCode = 1; rs.ReasonCode = 1; int _uid = 0; _uid = GetLastUID() + 1; this.UID = _uid; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO " + tableName + "( " + ListOfFields(separator:",",prefixLine1:"") + ")" + " VALUES " + "( " + ListOfFields(separator: ", @", prefixLine1: " @") + " )" ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command); connection.Open(); command.ExecuteNonQuery(); } } return rs; } /// <summary> /// Update Employee Details /// </summary> /// <returns></returns> public ResponseStatus Update() { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item updated successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE [Employee " + " SET " + FieldName.Date.ToString() + " = @" + FieldName.Date.ToString() + ", " + FieldName.FKClientWorkIsFor.ToString() + " = @" + FieldName.FKClientWorkIsFor.ToString() + ", " + FieldName.FKCompanyUID.ToString() + " = @" + FieldName.FKCompanyUID.ToString() + ", " + FieldName.FKEmployeeUID.ToString() + " = @" + FieldName.FKEmployeeUID.ToString() + ", " + FieldName.FKInvoiceItemID.ToString() + " = @" + FieldName.FKInvoiceItemID.ToString() + ", " + FieldName.FKInvoiceUID.ToString() + " = @" + FieldName.FKInvoiceUID.ToString() + ", " + FieldName.FKTaskUID.ToString() + " = @" + FieldName.FKTaskUID.ToString() + ", " + FieldName.Hours.ToString() + " = @" + FieldName.Hours.ToString() + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command); connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// Delete Employee /// </summary> /// <returns></returns> public ResponseStatus Delete() { var ret = new ResponseStatus(); ret.Message = "Deleted successfully"; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "DELETE " + tableName + " WHERE UID = @UID "; using (var command = new MySqlCommand(commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// List employees /// </summary> /// <param name="clientID"></param> public static List<ClientWorkHoursAllocation> List(int clientID) { var workAllocationList = new List<ClientWorkHoursAllocation>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + ListOfFields(",","") + " FROM " + tableName + " WHERE FKCompanyUID = {0}", clientID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { ClientWorkHoursAllocation clientWork = new ClientWorkHoursAllocation(); LoadObject(reader, clientWork); workAllocationList.Add(clientWork); } } } } return workAllocationList; } /// <summary> /// Retrieve last Employee UID /// </summary> /// <returns></returns> public int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM " + tableName; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Return a string with fields separated by supplied string /// </summary> /// <param name="separator"></param> /// <param name="prefixLine1"></param> /// <returns></returns> private static string ListOfFields(string separator, string prefixLine1) { return ( prefixLine1 + FieldName.UID.ToString() + separator + FieldName.Date.ToString() + separator + FieldName.FKClientWorkIsFor.ToString() + separator + FieldName.FKCompanyUID.ToString() + separator + FieldName.FKEmployeeUID.ToString() + separator + FieldName.FKInvoiceItemID.ToString() + separator + FieldName.FKInvoiceUID.ToString() + separator + FieldName.FKTaskUID.ToString() + separator + FieldName.Hours.ToString() ); } /// <summary> /// Add Employee parameters to the SQL Command. /// </summary> /// <param name="command"></param> private void AddSQLParameters(MySqlCommand command) { command.Parameters.Add(FieldName.UID.ToString(), MySqlDbType.Int32).Value = UID; command.Parameters.Add(FieldName.Date.ToString(), MySqlDbType.Date).Value = Date; command.Parameters.Add(FieldName.FKClientWorkIsFor.ToString(), MySqlDbType.Int32).Value = FKClientWorkIsFor; command.Parameters.Add(FieldName.FKCompanyUID.ToString(), MySqlDbType.Int32).Value = FKCompanyUID; command.Parameters.Add(FieldName.FKEmployeeUID.ToString(), MySqlDbType.Int32).Value = FKEmployeeUID; command.Parameters.Add(FieldName.FKInvoiceItemID.ToString(), MySqlDbType.Int32).Value = FKInvoiceItemID; command.Parameters.Add(FieldName.FKInvoiceUID.ToString(), MySqlDbType.Int32).Value = FKInvoiceUID; command.Parameters.Add(FieldName.FKTaskUID.ToString(), MySqlDbType.Int32).Value = FKTaskUID; command.Parameters.Add(FieldName.Hours.ToString(), MySqlDbType.Int32).Value = Hours; } /// <summary> /// This method loads the information from the sqlreader into the Employee object /// </summary> /// <param name="reader"></param> /// <param name="employee"></param> private static void LoadObject(MySqlDataReader reader, ClientWorkHoursAllocation clientWorkAllocation) { clientWorkAllocation.UID = Convert.ToInt32(reader[FieldName.UID.ToString()]); clientWorkAllocation.Date = Convert.ToDateTime(reader[FieldName.Date.ToString()]); clientWorkAllocation.FKClientWorkIsFor = Convert.ToInt32(reader[FieldName.FKClientWorkIsFor.ToString()]); clientWorkAllocation.FKCompanyUID = Convert.ToInt32(reader[FieldName.FKCompanyUID.ToString()]); clientWorkAllocation.FKEmployeeUID = Convert.ToInt32(reader[FieldName.FKEmployeeUID.ToString()]); clientWorkAllocation.FKInvoiceItemID = Convert.ToInt32(reader[FieldName.FKInvoiceItemID.ToString()]); clientWorkAllocation.FKInvoiceUID = Convert.ToInt32(reader[FieldName.FKInvoiceUID.ToString()]); clientWorkAllocation.FKTaskUID = Convert.ToInt32(reader[FieldName.FKTaskUID.ToString()]); clientWorkAllocation.Hours = Convert.ToInt32(reader[FieldName.Hours.ToString()]); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FCMMySQLBusinessLibrary.FCMUtils; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using MackkadoITFramework.ErrorHandling; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Repository.RepositoryClient { public class RepEmployee : Employee { /// <summary> /// Database fields /// </summary> public struct FieldName { public const string FKCompanyUID = "FKCompanyUID"; public const string UID = "UID"; public const string Name = "Name"; public const string RoleType = "RoleType"; public const string RoleDescription = "RoleDescription"; public const string Address = "Address"; public const string Phone = "Phone"; public const string Fax = "Fax"; public const string EmailAddress = "EmailAddress"; public const string IsAContact = "IsAContact"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; } //? Missing constructor /// <summary> /// Get Employee details /// </summary> private static string Read(int clientUID, string roleType) { Employee employee = new Employee(); // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = " SELECT " + EmployeeFieldsString() + " FROM Employee" + " WHERE FKCompanyUID = @FKCompanyUID " + " AND RoleType = @RoleType "; using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add( "@FKCompanyUID", MySqlDbType.Int32 ).Value = clientUID; command.Parameters.Add( "@RoleType", MySqlDbType.String ).Value = roleType; connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LoadEmployeeObject(reader, employee); } catch (Exception) { employee.UID = 0; } } } } return employee.Name; } public static ClientEmployee ReadEmployees(int clientUID) { ClientEmployee clientEmployee = new ClientEmployee(); clientEmployee.AdministrationPerson = Read( clientUID, FCMConstant.RoleTypeCode.AdministrationPerson ); clientEmployee.ManagingDirector = Read( clientUID, FCMConstant.RoleTypeCode.ManagingDirector ); clientEmployee.HealthAndSafetyRep = Read( clientUID, FCMConstant.RoleTypeCode.HealthAndSafetyRep ); clientEmployee.LeadingHand1 = Read( clientUID, FCMConstant.RoleTypeCode.LeadingHand1 ); clientEmployee.LeadingHand2 = Read( clientUID, FCMConstant.RoleTypeCode.LeadingHand2 ); clientEmployee.LeadingHand2 = Read( clientUID, FCMConstant.RoleTypeCode.LeadingHand2 ); clientEmployee.OHSEAuditor = Read( clientUID, FCMConstant.RoleTypeCode.OHSEAuditor ); clientEmployee.ProjectManager = Read( clientUID, FCMConstant.RoleTypeCode.ProjectManager ); clientEmployee.ProjectOHSRepresentative = Read( clientUID, FCMConstant.RoleTypeCode.ProjectOHSRepresentative ); clientEmployee.SiteManager = Read( clientUID, FCMConstant.RoleTypeCode.SiteManager ); clientEmployee.Supervisor = Read( clientUID, FCMConstant.RoleTypeCode.Supervisor ); clientEmployee.SystemsManager = Read( clientUID, FCMConstant.RoleTypeCode.SystemsManager ); clientEmployee.WorkersCompensationCoordinator = Read( clientUID, FCMConstant.RoleTypeCode.WorkersCompensationCoordinator ); return clientEmployee; } /// <summary> /// Retrieve last Employee UID /// </summary> /// <returns></returns> public int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM Employee "; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add new Employee /// </summary> /// <returns></returns> public ResponseStatus Insert() { var rs = new ResponseStatus(); rs.Message = "Client Added Successfully"; rs.ReturnCode = 1; rs.ReasonCode = 1; int _uid = 0; _uid = GetLastUID() + 1; this.UID = _uid; DateTime _now = DateTime.Today; this.CreationDateTime = _now; this.UpdateDateTime = _now; if (Name == null) Name = ""; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO Employee " + "( " + EmployeeFieldsString() + ")" + " VALUES " + "( " + " @" + FieldName.FKCompanyUID + ", @" + FieldName.UID + ", @" + FieldName.Name + ", @" + FieldName.RoleType + ", @" + FieldName.Address + ", @" + FieldName.Phone + ", @" + FieldName.Fax + ", @" + FieldName.EmailAddress + ", @" + FieldName.IsAContact + ", @" + FieldName.UserIdCreatedBy + ", @" + FieldName.UserIdUpdatedBy + ", @" + FieldName.CreationDateTime + ", @" + FieldName.UpdateDateTime + " )" ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command, "CREATE"); connection.Open(); command.ExecuteNonQuery(); } } return rs; } /// <summary> /// Update Employee Details /// </summary> /// <returns></returns> public ResponseStatus Update() { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item updated successfully"; if (Name == null) Name = ""; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "UPDATE Employee " + " SET " + FieldName.Name + " = @" + FieldName.Name + ", " + FieldName.RoleType + " = @" + FieldName.RoleType + ", " + FieldName.Fax + " = @" + FieldName.Fax + ", " + FieldName.Address + " = @" + FieldName.Address + ", " + FieldName.EmailAddress + " = @" + FieldName.EmailAddress + ", " + FieldName.IsAContact + " = @" + FieldName.IsAContact + ", " + FieldName.Phone + " = @" + FieldName.Phone + ", " + FieldName.UpdateDateTime + " = @" + FieldName.UpdateDateTime + ", " + FieldName.UserIdUpdatedBy + " = @" + FieldName.UserIdUpdatedBy + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { AddSQLParameters(command, "UPDATE"); connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// Delete Employee /// </summary> /// <returns></returns> public ResponseStatus Delete() { var ret = new ResponseStatus(); ret.Message = "Employee Deleted successfully"; if (Name == null) Name = ""; using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = ( "DELETE FROM Employee " + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection )) { command.Parameters.Add( "@UID", MySqlDbType.Int32 ).Value = UID; connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// List employees /// </summary> /// <param name="clientID"></param> public static List<Employee> List( int clientID ) { List<Employee> employeeList = new List<Employee>(); using (var connection = new MySqlConnection( ConnString.ConnectionString )) { var commandString = string.Format( " SELECT " + EmployeeFieldsString() + " FROM Employee " + " WHERE FKCompanyUID = {0}", clientID ); using (var command = new MySqlCommand( commandString, connection )) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Employee _employee = new Employee(); LoadEmployeeObject(reader, _employee); employeeList.Add( _employee ); } } } } return employeeList; } public static string EmployeeFieldsString() { return ( FieldName.FKCompanyUID + "," + FieldName.UID + "," + FieldName.Name + "," + FieldName.RoleType + "," + FieldName.Address + "," + FieldName.Phone + "," + FieldName.Fax + "," + FieldName.EmailAddress + "," + FieldName.IsAContact + "," + FieldName.UserIdUpdatedBy + "," + FieldName.UserIdCreatedBy + "," + FieldName.CreationDateTime + "," + FieldName.UpdateDateTime ); } /// <summary> /// Add Employee parameters to the SQL Command. /// </summary> /// <param name="command"></param> private void AddSQLParameters(MySqlCommand command, string action) { command.Parameters.Add(FieldName.FKCompanyUID, MySqlDbType.Int32).Value = FKCompanyUID; command.Parameters.Add(FieldName.UID, MySqlDbType.Int32).Value = UID; command.Parameters.Add(FieldName.Name, MySqlDbType.VarChar).Value = Name; command.Parameters.Add(FieldName.RoleType, MySqlDbType.VarChar).Value = RoleType; command.Parameters.Add(FieldName.Address, MySqlDbType.VarChar).Value = Address; command.Parameters.Add(FieldName.Phone, MySqlDbType.VarChar).Value = Phone; command.Parameters.Add(FieldName.Fax, MySqlDbType.VarChar).Value = Fax; command.Parameters.Add(FieldName.EmailAddress, MySqlDbType.VarChar).Value = EmailAddress; command.Parameters.Add(FieldName.IsAContact, MySqlDbType.VarChar).Value = IsAContact; command.Parameters.Add(FieldName.UserIdUpdatedBy, MySqlDbType.VarChar).Value = UserIdUpdatedBy; command.Parameters.Add(FieldName.UpdateDateTime, MySqlDbType.DateTime).Value = UpdateDateTime; if (action == "CREATE") { command.Parameters.Add(FieldName.UserIdCreatedBy, MySqlDbType.VarChar).Value = UserIdCreatedBy; command.Parameters.Add(FieldName.CreationDateTime, MySqlDbType.DateTime).Value = CreationDateTime; } } /// <summary> /// This method loads the information from the sqlreader into the Employee object /// </summary> /// <param name="reader"></param> /// <param name="employee"></param> private static void LoadEmployeeObject(MySqlDataReader reader, Employee employee) { employee.FKCompanyUID = Convert.ToInt32(reader[FieldName.FKCompanyUID]); employee.UID = Convert.ToInt32(reader[FieldName.UID].ToString()); employee.Name = reader[FieldName.Name].ToString(); employee.RoleType = reader[FieldName.RoleType].ToString(); employee.Address = reader[FieldName.Address].ToString(); employee.Phone = reader[FieldName.Phone].ToString(); employee.Fax = reader[FieldName.Fax].ToString(); employee.UserIdCreatedBy = reader[FieldName.UserIdCreatedBy].ToString(); employee.UserIdUpdatedBy = reader[FieldName.UserIdCreatedBy].ToString(); employee.RoleDescription = CodeValue.GetCodeValueDescription(MakConstant.CodeTypeString.RoleType, employee.RoleType); try { employee.IsAContact = Convert.ToChar(reader[FieldName.IsAContact].ToString()); } catch { employee.IsAContact = 'N'; } try { employee.EmailAddress = reader[FieldName.EmailAddress].ToString(); } catch { employee.EmailAddress = ""; } try { employee.UpdateDateTime = Convert.ToDateTime(reader[FieldName.UpdateDateTime].ToString()); } catch { employee.UpdateDateTime = DateTime.Now; } try { employee.CreationDateTime = Convert.ToDateTime(reader[FieldName.CreationDateTime].ToString()); } catch { employee.CreationDateTime = DateTime.Now; } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using FCMMySQLBusinessLibrary; using FCMMySQLBusinessLibrary.Model.ModelClientDocument; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClientDocument.Service; using MackkadoITFramework.APIDocument; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; namespace fcm.Windows { public partial class UIClientDocumentEdit : Form { public UIClientDocumentEdit() { InitializeComponent(); } public UIClientDocumentEdit(ClientDocument clientDocument) : this() { txtUID.Text = clientDocument.UID.ToString(); txtClientID.Text = clientDocument.FKClientUID.ToString(); txtClientDocumentSetID.Text = clientDocument.FKClientDocumentSetUID.ToString(); txtDocumentID.Text = clientDocument.FKDocumentUID.ToString(); txtIssueNumber.Text = clientDocument.SourceIssueNumber.ToString(); txtSourceLocation.Text = clientDocument.SourceLocation; txtSourceFileName.Text = clientDocument.SourceFileName; // Destination Location txtLocation.Text = clientDocument.Location; txtFileName.Text = clientDocument.FileName; txtSequenceNumber.Text = clientDocument.SequenceNumber.ToString(); txtClientDocumentVersionNumber.Text = clientDocument.ClientIssueNumber.ToString(); txtSourceDocumentVersionNumber.Text = clientDocument.SourceIssueNumber.ToString(); cbxIsProjectPlan.Checked = clientDocument.IsProjectPlan == "Y" ? true : false; cbxIsGenerated.Checked = clientDocument.Generated == 'Y' ? true : false; cbxIsRoot.Checked = clientDocument.IsRoot == 'Y' ? true : false; cbxIsFolder.Checked = clientDocument.IsFolder == 'Y' ? true : false; cbxIsVoid.Checked = clientDocument.IsVoid == 'Y' ? true : false; txtStatus.Text = "Not used"; txtParentUID.Text = clientDocument.ParentUID.ToString(); txtRecordType.Text = clientDocument.RecordType; txtDocumentType.Text = clientDocument.DocumentType; txtDocumentCUID.Text = clientDocument.DocumentCUID; if (!cbxIsGenerated.Checked) btnEdit.Enabled = false; } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnSave_Click(object sender, EventArgs e) { // Save details ClientDocument clientDocument = new ClientDocument(); clientDocument.UID = Convert.ToInt32(txtUID.Text); clientDocument.FKClientDocumentSetUID = Convert.ToInt32(txtClientDocumentSetID.Text); clientDocument.FKDocumentUID = Convert.ToInt32(txtDocumentID.Text); clientDocument.FKClientUID = Convert.ToInt32(txtClientID.Text); clientDocument.SourceLocation = txtSourceLocation.Text; clientDocument.SourceFileName = txtSourceFileName.Text; clientDocument.Location = txtLocation.Text; clientDocument.FileName = txtFileName.Text; if (!string.IsNullOrEmpty(txtSequenceNumber.Text)) { clientDocument.SequenceNumber = Convert.ToInt32(txtSequenceNumber.Text); } else { clientDocument.SequenceNumber = 0; } // clientDocument.Update(); BUSClientDocument.ClientDocumentUpdate( clientDocument ); MessageBox.Show("Client document updated successfully."); this.Close(); } private void btnSourceLocation_Click(object sender, EventArgs e) { // Separate the file name from the path // Store both in separate fields // // Get template folder var templateFolder = CodeValue.GetCodeValueExtended(FCMConstant.CodeTypeString.SYSTSET, FCMConstant.SYSFOLDER.TEMPLATEFOLDER); // Show file dialog var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; // Extract File Path string pathOnly = fullPathFileName.Replace(fileName, ""); txtSourceFileName.Text = fileName; txtSourceLocation.Text = pathOnly; // Get reference path // string refPath = Utils.getReferenceFilePathName(txtSourceLocation.Text); txtSourceLocation.Text = refPath; // If the source folder includes %TEMPLATEFOLDER% // keep the normal rules // otherwise, reset the path to %CLIENTFOLDER%\Unique // make file name the same if (txtSourceLocation.Text.Contains(FCMConstant.SYSFOLDER.TEMPLATEFOLDER)) { txtLocation.Text = Utils.getOppositePath(txtSourceLocation.Text); txtFileName.Text = txtSourceFileName.Text; } else { txtLocation.Text = FCMConstant.SYSFOLDER.CLIENTFOLDER; txtFileName.Text = txtSourceFileName.Text; } } } private void btnEdit_Click(object sender, EventArgs e) { string filePathName = Utils.getFilePathName(txtLocation.Text, txtFileName.Text); if (!File.Exists(filePathName)) { MessageBox.Show("Document not generated. " + filePathName); return; } WordDocumentTasks.OpenDocument(filePathName, vkReadOnly: false); } private void UIClientDocumentEdit_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using MackkadoITFramework; using FCMMySQLBusinessLibrary.FCMUtils; namespace fcm.UIHelper { public class ClientDocumentUIHelper { // ----------------------------------------------------- // Load documents in a tree // The list in tree expects that the list has been // called before to populate the instance // ----------------------------------------------------- public static void ListInTree(TreeView fileList, string listType, List<scClientDocSetDocLink> clientDocSetDocLink) { // listType = CLIENT // listType = FCM = default; string ListType = listType; if (ListType == null) ListType = "FCM"; foreach (var docLinkSet in clientDocSetDocLink) { // Check if folder has a parent string cdocumentUID = docLinkSet.clientDocument.UID.ToString(); string cparentIUID = docLinkSet.clientDocument.ParentUID.ToString(); TreeNode treeNode = new TreeNode(); int image = 0; int imageSelected = 0; docLinkSet.clientDocument.RecordType = docLinkSet.clientDocument.RecordType.Trim(); image = Utils.GetFileImage(docLinkSet.clientDocument.SourceFilePresent, docLinkSet.clientDocument.DestinationFilePresent, docLinkSet.clientDocument.DocumentType); imageSelected = image; //if (ListType == "CLIENT") // treeNode = new TreeNode(docLinkSet.clientDocument.FileName, image, imageSelected); //else // treeNode = new TreeNode(docLinkSet.document.Name, image, imageSelected); // string treenodename = docLinkSet.document.DisplayName; string treenodename = docLinkSet.document.FileName; if (string.IsNullOrEmpty(treenodename)) treenodename = docLinkSet.clientDocument.FileName; if (string.IsNullOrEmpty(treenodename)) treenodename = "Error: Name not found"; treeNode = new TreeNode(treenodename, image, imageSelected); if (docLinkSet.clientDocument.ParentUID == 0) { treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find(cparentIUID, true); if (node.Count() > 0) { treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; node[0].Nodes.Add(treeNode); } else { // Add Element to the root // treeNode.Tag = docLinkSet; treeNode.Name = cdocumentUID; fileList.Nodes.Add(treeNode); } } } } /// <summary> /// Document Name /// </summary> /// <param name="simpleFileName"></param> /// <param name="issueNumber"></param> /// <param name="CUID"></param> /// <returns></returns> public static string SetDocumentName( string simpleFileName, string issueNumber, string CUID, string recordtype, string filename ) { if ( string.IsNullOrEmpty( issueNumber ) ) { issueNumber = "0"; } int issue = Convert.ToInt32( issueNumber ); string issueS = issue.ToString( "00" ); if ( recordtype == "FOLDER") return filename; return String.Concat( CUID, "-", issueS, " ", simpleFileName ); } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryClientDocument; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.ProcessRequest; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public class BUSProcessRequest { /// <summary> /// Add Process Request /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static ResponseStatus Add(ProcessRequest processRequest) { ResponseStatus response = new ResponseStatus(); response = processRequest.Add(); return response; } /// <summary> /// Add Document Generation for Client /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static ResponseStatus GenerateDocumentClient( int clientUID, int clientSetID, string overrideDocuments, int clientDocumentUID = 0, string userID = "") { ResponseStatus response = new ResponseStatus(); ProcessRequest processRequest = new ProcessRequest(); processRequest.Description = "Document Generation For Client " + clientUID.ToString() + " Set " + clientSetID.ToString(); processRequest.Type = ProcessRequest.TypeValue.DOCUMENTGENERATION.ToString(); processRequest.FKClientUID = clientUID; processRequest.RequestedByUser = userID; response = processRequest.Add(); ProcessRequestArguments argument1 = new ProcessRequestArguments(); argument1.FKRequestUID = processRequest.UID; argument1.Code = ProcessRequestArguments.ProcessRequestCodeValues.CLIENTUID.ToString(); argument1.ValueType = ProcessRequestArguments.ValueTypeValue.NUMBER.ToString(); argument1.Value = clientUID.ToString(); argument1.Add(); ProcessRequestArguments argument2 = new ProcessRequestArguments(); argument2.FKRequestUID = processRequest.UID; argument2.Code = ProcessRequestArguments.ProcessRequestCodeValues.CLIENTSETID.ToString(); argument2.ValueType = ProcessRequestArguments.ValueTypeValue.NUMBER.ToString(); argument2.Value = clientSetID.ToString(); argument2.Add(); ProcessRequestArguments argument3 = new ProcessRequestArguments(); argument3.FKRequestUID = processRequest.UID; argument3.Code = ProcessRequestArguments.ProcessRequestCodeValues.OVERRIDE.ToString(); argument3.ValueType = ProcessRequestArguments.ValueTypeValue.STRING.ToString(); argument3.Value = overrideDocuments; argument3.Add(); // Generation for one specific document if ( clientDocumentUID > 0 ) { ProcessRequestArguments argument4 = new ProcessRequestArguments(); argument3.FKRequestUID = processRequest.UID; argument3.Code = ProcessRequestArguments.ProcessRequestCodeValues.CLIENTDOCUID.ToString(); argument3.ValueType = ProcessRequestArguments.ValueTypeValue.STRING.ToString(); argument3.Value = clientDocumentUID.ToString(); argument3.Add(); RepClientDocument.SetFlagToGenerationRequested( clientDocumentUID, Convert.ToInt32(response.Contents) ); } else { // Full set requested // Update requests. // var list = RepClientDocument.ListS( clientUID, clientSetID ); foreach ( var doco in list ) { // RepClientDocument.SetFlagToGenerationRequested( doco.clientDocument.UID ); RepClientDocument.SetFlagToGenerationRequested( doco.clientDocument.UID, Convert.ToInt32( response.Contents ) ); } } // Send email to requester // string emailGraham = "<EMAIL>"; string emailDaniel = "<EMAIL>"; string emailSubject = "<> REQUESTED <> " + DateTime.Now + " <> generation requested by: " + userID + " for client " + clientUID; string emailBody = "Generation has been requested on : " + DateTime.Now + " <> " + emailSubject + " -- "; if (userID.ToUpper() == "GC0001") { var resp1 = FCMEmail.SendEmailSimple( iRecipient: emailGraham, iSubject: emailSubject, iBody: emailBody); } var resp2 = FCMEmail.SendEmailSimple( iRecipient: emailDaniel, iSubject: emailSubject, iBody: emailBody); return response; } /// <summary> /// Add Document Generation for Client /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static ResponseStatus GenerateDocumentClient( int clientUID, int clientSetID, string overrideDocuments, List<int> listDocs, string userID = "") { ResponseStatus response = new ResponseStatus(); string emailGraham = "<EMAIL>"; string emailDaniel = "<EMAIL>"; string emailSubject = ""; string emailBody = ""; foreach ( var doc in listDocs ) { ProcessRequest processRequest = new ProcessRequest(); processRequest.Description = "Document Generation For Client " + clientUID.ToString() + " Set " + clientSetID.ToString(); processRequest.Type = ProcessRequest.TypeValue.DOCUMENTGENERATION.ToString(); processRequest.FKClientUID = clientUID; processRequest.RequestedByUser = userID; response = processRequest.Add(); ProcessRequestArguments argument1 = new ProcessRequestArguments(); argument1.FKRequestUID = processRequest.UID; argument1.Code = ProcessRequestArguments.ProcessRequestCodeValues.CLIENTUID.ToString(); argument1.ValueType = ProcessRequestArguments.ValueTypeValue.NUMBER.ToString(); argument1.Value = clientUID.ToString(); argument1.Add(); ProcessRequestArguments argument2 = new ProcessRequestArguments(); argument2.FKRequestUID = processRequest.UID; argument2.Code = ProcessRequestArguments.ProcessRequestCodeValues.CLIENTSETID.ToString(); argument2.ValueType = ProcessRequestArguments.ValueTypeValue.NUMBER.ToString(); argument2.Value = clientSetID.ToString(); argument2.Add(); ProcessRequestArguments argument3 = new ProcessRequestArguments(); argument3.FKRequestUID = processRequest.UID; argument3.Code = ProcessRequestArguments.ProcessRequestCodeValues.OVERRIDE.ToString(); argument3.ValueType = ProcessRequestArguments.ValueTypeValue.STRING.ToString(); argument3.Value = overrideDocuments; argument3.Add(); ProcessRequestArguments argument4 = new ProcessRequestArguments(); argument3.FKRequestUID = processRequest.UID; argument3.Code = ProcessRequestArguments.ProcessRequestCodeValues.CLIENTDOCUID.ToString(); argument3.ValueType = ProcessRequestArguments.ValueTypeValue.STRING.ToString(); argument3.Value = doc.ToString(); argument3.Add(); RepClientDocument.SetFlagToGenerationRequested( doc, Convert.ToInt32(response.Contents) ); // Send email to requester // emailGraham = "<EMAIL>"; emailDaniel = "<EMAIL>"; emailSubject = "<> REQUESTED <> " + DateTime.Now + " <> generation requested by: " + userID + " for client " + clientUID; emailBody = "Generation has been requested on : " + DateTime.Now + " <> " + emailSubject + " -- " + " It hasn't been started yet."; } try { if (userID.ToUpper() == "GC0001") { var resp1 = FCMEmail.SendEmailSimple( iRecipient: emailGraham, iSubject: emailSubject, iBody: emailBody); } var resp2 = FCMEmail.SendEmailSimple( iRecipient: emailDaniel, iSubject: emailSubject, iBody: emailBody); } catch (Exception ex) { LogFile.WriteToTodaysLogFile("Sending email from Generate selected documents error " + ex.ToString()); } return response; } /// <summary> /// Add Process Request Argument /// </summary> /// <param name="processRequestArgument"></param> /// <returns></returns> public static ResponseStatus AddArgument(ProcessRequestArguments processRequestArgument) { ResponseStatus response = new ResponseStatus(); response = processRequestArgument.Add(); return response; } /// <summary> /// Add process request results /// </summary> /// <param name="processRequestResults"></param> /// <returns></returns> public static ResponseStatus AddArgument(ProcessRequestResults processRequestResults) { ResponseStatus response = new ResponseStatus(); response = processRequestResults.Add(); return response; } /// <summary> /// List Active Process Requests /// </summary> /// <param name="processRequestResults"></param> /// <returns></returns> public static List<ProcessRequest> ListActiveRequests() { var statusIn = ProcessRequest.StatusValue.OPEN; List<ProcessRequest> response = ProcessRequest.List(statusIn); return response; } /// <summary> /// List Active Process Requests /// </summary> /// <param name="processRequestResults"></param> /// <returns></returns> public static List<ProcessRequest> ListUnfinishedRequests() { var statusIn = ProcessRequest.StatusValue.STARTED; List<ProcessRequest> response = ProcessRequest.List( statusIn ); return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using FCMMySQLBusinessLibrary.Model.ModelClient; using MackkadoITFramework.ErrorHandling; namespace FCMMySQLBusinessLibrary { public interface IEmployee { event EventHandler<EventArgs> EmployeeList; event EventHandler<EventArgs> EmployeeAdd; event EventHandler<EventArgs> EmployeeUpdate; event EventHandler<EventArgs> EmployeeDelete; void DisplayMessage(string message); void ResetScreen(); List<Employee> employeeList { get; set; } ResponseStatus response { get; set; } Employee employee { get; set; } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary.Repository.RepositoryDocument; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; using System.Windows.Forms; using System.Linq; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentList { public List<Document> documentList; // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public void ListProjectPlans() { List(" AND IsProjectPlan = 'Y' "); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public void List() { List(null); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- private void List(string Condition) { this.documentList = new List<Model.ModelDocument.Document>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " FROM Document DOC " + " WHERE DOC.SourceCode = 'FCM' " + " AND DOC.IsVoid = 'N' " + Condition + " ORDER BY PARENTUID ASC, SequenceNumber ASC " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Model.ModelDocument.Document _Document = new Model.ModelDocument.Document(); RepDocument.LoadDocumentFromReader(_Document, "DOC", reader); documentList.Add(_Document); } } } } } // ----------------------------------------------------- // List Documents for a Document Set // ----------------------------------------------------- public void ListDocSet( int documentSetUID ) { this.documentList = new List<Model.ModelDocument.Document>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT "+ RepDocument.SQLDocumentConcat("DOC") + " ,LNK.FKParentDocumentUID " + " ,LNK.FKParentDocumentSetUID " + " ,LNK.SequenceNumber " + " FROM Document DOC " + " ,DocumentSetDocument LNK" + " WHERE " + " LNK.FKDocumentUID = DOC.UID " + " AND DOC.SourceCode = 'FCM' " + " AND LNK.IsVoid = 'N' " + " AND DOC.IsVoid = 'N' " + " AND LNK.FKDocumentSetUID = {0} " + " ORDER BY LNK.FKParentDocumentUID ASC, LNK.SequenceNumber ", documentSetUID ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Model.ModelDocument.Document _Document = new Model.ModelDocument.Document(); RepDocument.LoadDocumentFromReader(_Document, "DOC", reader); // This is necessary because when the list comes from DocumentSet, the parent may change // _Document.ParentUID = Convert.ToInt32(reader["FKParentDocumentUID"].ToString()); this.documentList.Add(_Document); } } } } } // ----------------------------------------------------- // Load documents in a tree // ----------------------------------------------------- public static void ListInTree( TreeView fileList, DocumentList documentList, Model.ModelDocument.Document root) { // Find root folder // Model.ModelDocument.Document rootDocument = new Model.ModelDocument.Document(); rootDocument.CUID = root.CUID; rootDocument.RecordType = root.RecordType; rootDocument.UID = root.UID; // rootDocument.Read(); rootDocument = RepDocument.Read(false, root.UID); // Create root // var rootNode = new TreeNode(rootDocument.FileName, MakConstant.Image.Folder, MakConstant.Image.Folder); // Add root node to tree // fileList.Nodes.Add(rootNode); rootNode.Tag = rootDocument; rootNode.Name = rootDocument.Name; foreach (var document in documentList.documentList) { // Ignore root folder if (document.CUID == "ROOT") continue; // Check if folder has a parent string cdocumentUID = document.UID.ToString(); string cparentIUID = document.ParentUID.ToString(); int image = 0; int imageSelected = 0; document.RecordType = document.RecordType.Trim(); #region Image switch (document.DocumentType) { case Utils.DocumentType.WORD: image = MakConstant.Image.Word32; imageSelected = MakConstant.Image.Word32; // I have to think about this... // if (document.RecordType == Utils.RecordType.APPENDIX) { image = MakConstant.Image.Appendix; imageSelected = MakConstant.Image.Appendix; } break; case Utils.DocumentType.EXCEL: image = MakConstant.Image.Excel; imageSelected = MakConstant.Image.Excel; break; case Utils.DocumentType.FOLDER: image = MakConstant.Image.Folder; imageSelected = MakConstant.Image.Folder; break; case Utils.DocumentType.PDF: image = MakConstant.Image.PDF; imageSelected = MakConstant.Image.PDF; break; default: image = MakConstant.Image.Word32; imageSelected = MakConstant.Image.Word32; break; } #endregion Image if (document.ParentUID == 0) { var treeNode = new TreeNode( document.FileName, image, image ); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add(treeNode); } else { // Find the parent node // var node = fileList.Nodes.Find(cparentIUID, true); if (node.Count() > 0) { var treeNode = new TreeNode( document.FileName, image, imageSelected ); treeNode.Tag = document; treeNode.Name = cdocumentUID; node[0].Nodes.Add(treeNode); } else { // Add Element to the root // var treeNode = new TreeNode( document.FileName, image, imageSelected ); treeNode.Tag = document; treeNode.Name = cdocumentUID; rootNode.Nodes.Add(treeNode); } } } } // ----------------------------------------------------- // List Documents for a client // ----------------------------------------------------- public void ListClient(int clientUID) { this.documentList = new List<Model.ModelDocument.Document>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + RepDocument.SQLDocumentConcat("DOC") + " FROM Document DOC " + " WHERE SourceCode = 'CLIENT' " + " AND FKClientUID = {0} " + " AND IsVoid <> 'Y' " + " ORDER BY PARENTUID ASC, SequenceNumber ASC ", clientUID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Model.ModelDocument.Document _Document = new Model.ModelDocument.Document(); RepDocument.LoadDocumentFromReader(_Document, "DOC", reader); documentList.Add(_Document); } } } } } } } <file_sep>using System.Collections.Generic; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Security; using MackkadoITFramework.Utils; namespace FCMMySQLBusinessLibrary.Service.SVCClient.Service { public static class BUSReferenceData { /// <summary> /// Get List of screens of user /// </summary> /// <param name="userID"></param> /// <returns></returns> public static List<CodeValue> GetListScreensForUser(string userID) { var list = new List<CodeValue>(); var listOfRoles = new List<SecurityUserRole>(); SecurityUserRole userRole = new SecurityUserRole(HeaderInfo.Instance); var response = userRole.ListRoleForUser(userID, listOfRoles); foreach (var role in listOfRoles) { // get list of screen for role // var listOfScreen = SecurityRoleScreen.List(role.FK_Role); foreach (var cvScreen in listOfScreen) { var screenAsCodeValue = new CodeValue(); screenAsCodeValue.ID = cvScreen.FKScreenCode; screenAsCodeValue.Description = CodeValue.GetCodeValueDescription( FCMConstant.CodeTypeString.SCREENCODE, cvScreen.FKScreenCode); bool found = false; foreach (var alreadyInListScreen in list) { if (cvScreen.FKScreenCode == alreadyInListScreen.ID) { found = true; break; } } if (found) continue; list.Add(screenAsCodeValue); } } return list; } public static ResponseStatus DeleteRelatedCodeValue(RelatedCodeValue relatedCodeValue) { ResponseStatus response = new ResponseStatus(); relatedCodeValue.Delete(); return response; } public static ResponseStatus AddRelatedCodeValue(RelatedCodeValue relatedCodeValue) { ResponseStatus response = new ResponseStatus(); relatedCodeValue.Add(); return response; } public static ResponseStatus AddRelatedCodeType(RelatedCode relatedCode) { ResponseStatus response = new ResponseStatus(); relatedCode.Add(); return response; } /// <summary> /// List code value /// </summary> /// <param name="eventClient"></param> /// <returns></returns> public static List<RelatedCode> ListRelatedCode() { var listOfCodeValues = RelatedCode.List(); return listOfCodeValues; } /// <summary> /// List complete set of related code value. /// </summary> /// <param name="eventClient"></param> /// <returns></returns> public static List<RelatedCodeValue> ListRelatedCodeValue() { var listOfRelatedValues = RelatedCodeValue.ListAllS(); return listOfRelatedValues; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Text; using System.Data.SqlClient; namespace fcm { class Metadata { public string RecordType; public string FieldCode; public string InformationType; public string Table; public string Field; public string Condition; public string CompareWith; public string Get() { string ret = ""; string comp = ""; string select = ""; // Source Memory Information switch (this.CompareWith) { case "CLIENTUID": comp = Utils.ClientID.ToString(); break; } if (this.InformationType == "FIELD") { select = " SELECT " + this.Field + " FROM " + this.Table + " WHERE " + this.Condition + comp; } // // EA SQL database // using (var connection = new SqlConnection(ConnString.ConnectionString)) { var commandString = select; using (var command = new SqlCommand( commandString, connection)) { connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { ret = reader[Field].ToString(); } } } return ret; } } } <file_sep>using System; using System.Collections.Generic; using FCMMySQLBusinessLibrary; using MackkadoITFramework.ErrorHandling; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace MackkadoITFramework.ProcessRequest { public class ProcessRequest { #region Fields public int UID { get; set; } public string Description { get; set; } public int FKClientUID { get; set; } public string Type { get; set; } public string Status { get; set; } public string WhenToProcess { get; set; } public string RequestedByUser { get; set; } public DateTime CreationDateTime { get; set; } public DateTime StatusDateTime { get; set; } public DateTime PlannedDateTime { get; set; } public List<ProcessRequestArguments> argumentList { get; set; } #endregion Fields #region Fields Building Blocks /// <summary> /// Database fields /// </summary> public struct FieldName { public const string UID = "UID"; public const string Description = "Description"; public const string FKClientUID = "FKClientUID"; public const string Type = "Type"; public const string Status = "Status"; public const string WhenToProcess = "WhenToProcess"; public const string RequestedByUser = "RequestedByUser"; public const string CreationDateTime = "CreationDateTime"; public const string StatusDateTime = "StatusDateTime"; public const string PlannedDateTime = "PlannedDateTime"; } /// <summary> /// Document string of fields. /// </summary> /// <returns></returns> private static string FieldString() { return ( FieldName.UID + "," + FieldName.Description + "," + FieldName.FKClientUID + "," + FieldName.Type + "," + FieldName.Status + "," + FieldName.WhenToProcess + "," + FieldName.RequestedByUser + "," + FieldName.CreationDateTime + "," + FieldName.PlannedDateTime + "," + FieldName.StatusDateTime ); } /// <summary> /// Load from Reader /// </summary> /// <param name="processRequest"></param> /// <param name="tablePrefix"></param> /// <param name="reader"></param> public static void LoadFromReader( ProcessRequest processRequest, MySqlDataReader reader) { processRequest.UID = Convert.ToInt32(reader[FieldName.UID].ToString()); try { processRequest.FKClientUID = Convert.ToInt32(reader[FieldName.FKClientUID].ToString()); } catch(Exception ex) { processRequest.FKClientUID = 0; } processRequest.Description = reader[FieldName.Description].ToString(); processRequest.Status = reader[FieldName.Status].ToString(); processRequest.Type = reader[FieldName.Type].ToString(); processRequest.WhenToProcess = reader[FieldName.WhenToProcess].ToString(); processRequest.RequestedByUser = reader[FieldName.RequestedByUser].ToString(); processRequest.PlannedDateTime = Convert.ToDateTime(reader[FieldName.PlannedDateTime]); processRequest.CreationDateTime = Convert.ToDateTime(reader[FieldName.CreationDateTime]); processRequest.StatusDateTime = Convert.ToDateTime(reader[FieldName.StatusDateTime]); return; } #endregion Fields Building Blocks #region Permitted Values public enum StatusValue { OPEN, STARTED, COMPLETED, FAILED, ALL } public enum WhenToProcessValue { NOW, FUTURE } public enum TypeValue { DOCUMENTGENERATION } #endregion Permitted Values /// <summary> /// Constructor /// </summary> public ProcessRequest() { this.WhenToProcess = ProcessRequest.WhenToProcessValue.NOW.ToString(); this.Status = ProcessRequest.StatusValue.OPEN.ToString(); this.PlannedDateTime = System.DateTime.Now; this.CreationDateTime = System.DateTime.Now; this.StatusDateTime = System.DateTime.Now; this.RequestedByUser = Helper.Utils.UserID; } /// <summary> /// Retrieve Last UID /// </summary> /// <returns></returns> private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = "SELECT MAX(UID) LASTUID FROM ProcessRequest"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } /// <summary> /// Add New Process Request /// </summary> public ResponseStatus Add() { ResponseStatus response = new ResponseStatus(); int _uid = 0; _uid = GetLastUID() + 1; this.UID = _uid; DateTime _now = DateTime.Today; if (UID == null) { ResponseStatus responseError = new ResponseStatus(messageType: MessageType.Error); responseError.Message = "UID Not Supplied"; return responseError; } if (Description == null) { ResponseStatus responseError = new ResponseStatus(messageType: MessageType.Error); responseError.Message = "Description Not Supplied"; return responseError; } using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "INSERT INTO ProcessRequest " + "( " + FieldString() + ")" + " VALUES " + "( "+ " @" + FieldName.UID + ", @" + FieldName.Description + ", @" + FieldName.FKClientUID + ", @" + FieldName.Type + ", @" + FieldName.Status + ", @" + FieldName.WhenToProcess + ", @" + FieldName.RequestedByUser + ", @" + FieldName.CreationDateTime + ", @" + FieldName.PlannedDateTime + ", @" + FieldName.StatusDateTime + " )" ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@Description", MySqlDbType.VarChar).Value = Description; command.Parameters.Add("@FKClientUID", MySqlDbType.Int32).Value = FKClientUID; command.Parameters.Add("@Type", MySqlDbType.VarChar).Value = Type; command.Parameters.Add("@Status", MySqlDbType.VarChar).Value = Status; command.Parameters.Add("@WhenToProcess", MySqlDbType.VarChar).Value = WhenToProcess; command.Parameters.Add("@RequestedByUser", MySqlDbType.VarChar).Value = RequestedByUser; command.Parameters.Add("@CreationDateTime", MySqlDbType.DateTime).Value = CreationDateTime; command.Parameters.Add("@PlannedDateTime", MySqlDbType.DateTime).Value = PlannedDateTime; command.Parameters.Add("@StatusDateTime", MySqlDbType.DateTime).Value = StatusDateTime; connection.Open(); command.ExecuteNonQuery(); } } response.Contents = _uid; return response; } /// <summary> /// Update Status to Completed /// </summary> /// <returns></returns> public ResponseStatus SetStatusToCompleted() { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item updated successfully"; this.Status = ProcessRequest.StatusValue.COMPLETED.ToString(); this.Update(); return ret; } /// <summary> /// Update Status to Completed /// </summary> /// <returns></returns> public ResponseStatus SetStatusToStarted() { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item updated successfully"; this.Status = ProcessRequest.StatusValue.STARTED.ToString(); this.Update(); return ret; } /// <summary> /// Update Status /// </summary> /// <returns></returns> public ResponseStatus Update() { ResponseStatus ret = new ResponseStatus(); ret.Message = "Item updated successfully"; this.StatusDateTime = System.DateTime.Now; using (var connection = new MySqlConnection(ConnString.ConnectionStringFramework)) { var commandString = ( "UPDATE ProcessRequest " + " SET " + FieldName.Status + " = @" + FieldName.Status + ", " + FieldName.StatusDateTime + " = @" + FieldName.StatusDateTime + " WHERE UID = @UID " ); using (var command = new MySqlCommand( commandString, connection)) { command.Parameters.Add(FieldName.UID, MySqlDbType.VarChar).Value = UID; command.Parameters.Add(FieldName.Status, MySqlDbType.VarChar).Value = Status; command.Parameters.Add(FieldName.StatusDateTime, MySqlDbType.DateTime).Value = StatusDateTime; connection.Open(); command.ExecuteNonQuery(); } } return ret; } /// <summary> /// List requests /// </summary> /// <param name="StatusIn"></param> /// <returns></returns> public static List<ProcessRequest> List(ProcessRequest.StatusValue StatusIn) { var result = new List<ProcessRequest>(); var checktype = " WHERE Status = '" + StatusIn.ToString() + "'"; if (StatusIn == ProcessRequest.StatusValue.ALL) { checktype = ""; } using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + FieldString() + " FROM ProcessRequest " + checktype + " ORDER BY 1 DESC " ); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { var _ProcessRequest = new ProcessRequest(); ProcessRequest.LoadFromReader(_ProcessRequest, reader); // Load Arguments // _ProcessRequest.argumentList = ProcessRequestArguments.List(_ProcessRequest.UID); result.Add(_ProcessRequest); } } } } return result; } } } <file_sep>using System; using System.Collections.Generic; using MackkadoITFramework.Helper; using MackkadoITFramework.Utils; using MySql.Data.MySqlClient; namespace FCMMySQLBusinessLibrary.Model.ModelDocument { public class DocumentVersion { #region Properties public int UID { get { return _UID; } set { _UID = value; } } public int FKDocumentUID { get { return _FKDocumentUID; } set { _FKDocumentUID = value; } } public string FKDocumentCUID { get { return _FKDocumentCUID; } set { _FKDocumentCUID = value; } } public decimal IssueNumber { get { return _IssueNumber; } set { _IssueNumber = value; } } public string Location { get { return _Location; } set { _Location = value; } } public string FileName { get { return _FileName; } set { _FileName = value; } } public string UserIdCreatedBy { get { return _UserIdCreatedBy; } set { _UserIdCreatedBy = value; } } public string UserIdUpdatedBy { get { return _UserIdUpdatedBy; } set { _UserIdUpdatedBy = value; } } public DateTime CreationDateTime { get { return _CreationDateTime; } set { _CreationDateTime = value; } } public DateTime UpdateDateTime { get { return _UpdateDateTime; } set { _UpdateDateTime = value; } } #endregion Properties #region Attributes public int _UID; public int _FKDocumentUID; public string _FKDocumentCUID; public decimal _IssueNumber; public string _Location; public string _FileName; public DateTime _CreationDateTime; public DateTime _UpdateDateTime; public string _UserIdCreatedBy; public string _UserIdUpdatedBy; #endregion Attributes /// <summary> /// Database fields /// </summary> public struct FieldName { public const string UID = "UID"; public const string FKDocumentUID = "FKDocumentUID"; public const string FKDocumentCUID = "FKDocumentCUID"; public const string IssueNumber = "IssueNumber"; public const string Location = "Location"; public const string FileName = "FileName"; public const string UserIdCreatedBy = "UserIdCreatedBy"; public const string UserIdUpdatedBy = "UserIdUpdatedBy"; public const string CreationDateTime = "CreationDateTime"; public const string UpdateDateTime = "UpdateDateTime"; } public const string TableName = "DocumentVersion"; // ----------------------------------------------------- // Get Client details // ----------------------------------------------------- public bool Read() { // // EA SQL database // bool ret = false; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + DocumentVersionFieldString() + " FROM DocumentVersion" + " WHERE CUID = '{0}'", this.UID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { this.UID = Convert.ToInt32( reader["UID"].ToString()); this.FKDocumentUID = Convert.ToInt32( reader["FKDocumentUID"].ToString() ); this.FKDocumentCUID = reader["FKDocumentCUID"].ToString(); this.IssueNumber = Convert.ToInt32(reader["IssueNumber"].ToString()); this.Location = reader["Location"].ToString(); this.FileName = reader["FileName"].ToString(); ret = true; } catch (Exception) { UID = 0; } } } } return ret; } // ----------------------------------------------------- // Retrieve last Document Set id // ----------------------------------------------------- private int GetLastUID() { int LastUID = 0; // // EA SQL database // using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = "SELECT MAX(UID) LASTUID FROM DocumentVersion"; using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { try { LastUID = Convert.ToInt32(reader["LASTUID"]); } catch (Exception) { LastUID = 0; } } } } return LastUID; } // ----------------------------------------------------- // Add new Issue // ----------------------------------------------------- public void Add() { string ret = "Item updated successfully"; int _uid = 0; _uid = GetLastUID() + 1; using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = ( "INSERT INTO DocumentVersion " + " ( " + DocumentVersionFieldString() + ")" + " VALUES " + " ( " + " @UID " + ", @FKDocumentUID " + ", @FKDocumentCUID " + ", @IssueNumber " + ", @Location " + ", @FileName " + ", @CreationDateTime " + ", @UpdateDateTime " + ", @UserIdCreatedBy " + ", @UserIdUpdatedBy " + " ) " ); using (var command = new MySqlCommand( commandString, connection)) { this.UID = _uid; AddSQLParameters(command, MakConstant.SQLAction.CREATE); connection.Open(); command.ExecuteNonQuery(); } } return; } /// <summary> /// Add sql parameters /// </summary> /// <param name="command"></param> /// <param name="action"></param> private void AddSQLParameters(MySqlCommand command, string action) { command.Parameters.Add("@UID", MySqlDbType.Int32).Value = UID; command.Parameters.Add("@FKDocumentUID", MySqlDbType.Int32).Value = FKDocumentUID; command.Parameters.Add("@FKDocumentCUID", MySqlDbType.VarChar).Value = FKDocumentCUID; command.Parameters.Add("@IssueNumber", MySqlDbType.Decimal).Value = IssueNumber; command.Parameters.Add("@Location", MySqlDbType.VarChar).Value = Location; command.Parameters.Add("@FileName", MySqlDbType.VarChar).Value = FileName; command.Parameters.Add("@UpdateDateTime", MySqlDbType.DateTime, 8).Value = DateTime.Now; command.Parameters.Add("@UserIdUpdatedBy", MySqlDbType.VarChar).Value = Utils.UserID; if (action == MakConstant.SQLAction.CREATE) { command.Parameters.Add("@CreationDateTime", MySqlDbType.DateTime, 8).Value = DateTime.Now; command.Parameters.Add("@UserIdCreatedBy", MySqlDbType.VarChar).Value = Utils.UserID; } } /// <summary> /// Load reader information into object /// </summary> /// <param name="reader"></param> /// <param name="documentIssue"></param> private static void LoadObject(MySqlDataReader reader, DocumentVersion documentIssue) { documentIssue.UID = Convert.ToInt32(reader["UID"].ToString()); documentIssue.FKDocumentUID = Convert.ToInt32(reader["FKDocumentUID"].ToString()); documentIssue.FKDocumentCUID = reader["FKDocumentCUID"].ToString(); documentIssue.IssueNumber = Convert.ToInt32(reader["IssueNumber"].ToString()); documentIssue.Location = reader["Location"].ToString(); documentIssue.FileName = reader["FileName"].ToString(); } /// <summary> /// Client string of fields. /// </summary> /// <returns></returns> private static string DocumentVersionFieldString() { return ( FieldName.UID + "," + FieldName.FKDocumentUID + "," + FieldName.FKDocumentCUID + "," + FieldName.IssueNumber + "," + FieldName.Location + "," + FieldName.FileName + "," + FieldName.UpdateDateTime + "," + FieldName.CreationDateTime + "," + FieldName.UserIdCreatedBy + "," + FieldName.UserIdUpdatedBy ); } // ----------------------------------------------------- // List Documents // ----------------------------------------------------- public static List<DocumentVersion> List(Model.ModelDocument.Document document) { var documentIssueList = new List<DocumentVersion>(); using (var connection = new MySqlConnection(ConnString.ConnectionString)) { var commandString = string.Format( " SELECT " + DocumentVersionFieldString() + " FROM " + DocumentVersion.TableName + " WHERE FKDocumentUID = '{0}'", document.UID); using (var command = new MySqlCommand( commandString, connection)) { connection.Open(); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { DocumentVersion documentIssue = new DocumentVersion(); LoadObject(reader, documentIssue); documentIssueList.Add(documentIssue); } } } } return documentIssueList; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using FCMMySQLBusinessLibrary; using MackkadoITFramework.ReferenceData; namespace fcm.Components { public partial class UCCodeValue : UserControl { public List<CodeType> codeTypeList; private CodeValue codeValue; public UCCodeValue() { InitializeComponent(); codeValue = new CodeValue(); } public UCCodeValue(string iCodeType, string iCodeValue) { InitializeComponent(); this.ReadCodeValue(iCodeType, iCodeValue); } // // Set control fields // public void SetFKCodeType(string fkCodeType) { this.cbxCodeType.Text = fkCodeType; cbxCodeType.Enabled = false; } public void SetCodeID(string codeValueID) { this.txtCodeValueCode.Text = codeValueID; txtCodeValueCode.Enabled = false; } public void SetCodeDescription(string codeDescription) { this.txtCodeDescription.Text = codeDescription; } public void SetValueExtended(string valueExtended) { this.txtValueExtended.Text = valueExtended; } public void SetAbbreviation(string Abbreviation) { this.txtAbbreviation.Text = Abbreviation; } private void btnSave_Click(object sender, EventArgs e) { CodeValue cv = new CodeValue(); if (cbxCodeType.Text == null) { MessageBox.Show("Select Code Type."); return; } cv.FKCodeType = cbxCodeType.Text; cv.ID = txtCodeValueCode.Text; cv.Description = txtCodeDescription.Text; cv.Abbreviation = txtAbbreviation.Text; cv.ValueExtended = txtValueExtended.Text; cv.Save(); MessageBox.Show("Code Type Save Successfully."); ResetFields(); } private void UCCodeValue_Load(object sender, EventArgs e) { LoadCodeType(); } private void cbxCodeType_SelectedIndexChanged(object sender, EventArgs e) { string valueSelected = cbxCodeType.SelectedItem.ToString(); } private void UCCodeValue_Enter(object sender, EventArgs e) { var ctsel = cbxCodeType.SelectedItem; LoadCodeType(); cbxCodeType.SelectedItem = ctsel; } private void LoadCodeType() { codeTypeList = new List<CodeType>(); var codeType = new CodeType(); // Fill in the code type list // codeType.List(codeTypeList); cbxCodeType.Items.Clear(); foreach (CodeType c in codeTypeList) { cbxCodeType.Items.Add(c.Code); } } private void txtCodeValueCode_Leave(object sender, EventArgs e) { // string CodeType = cbxCodeType.SelectedItem.ToString(); string CodeType = cbxCodeType.Text; string CodeValue = txtCodeValueCode.Text; this.ReadCodeValue(CodeType, CodeValue); } private void ReadCodeValue(string iCodeType, string iCodeValue) { //CodeValue cv = new CodeValue(); //cv.FKCodeType = iCodeType; //cv.ID = iCodeValue; //cv.Read(false); codeValue.FKCodeType = iCodeType; codeValue.ID = iCodeValue; codeValue.Read(false); txtCodeDescription.Text = codeValue.Description; txtValueExtended.Text = codeValue.ValueExtended; txtAbbreviation.Text = codeValue.Abbreviation; } private void btnNew_Click(object sender, EventArgs e) { ResetFields(); } private void ResetFields() { txtCodeValueCode.Enabled = true; cbxCodeType.Enabled = true; txtCodeValueCode.Text = ""; txtCodeDescription.Text = ""; txtAbbreviation.Text = ""; txtValueExtended.Text = ""; txtCodeValueCode.Focus(); } private void btnSelectDestination_Click( object sender, EventArgs e ) { // Show file dialog // openFileDialog1.InitialDirectory = "C:\\Program Files\\Adobe\\Reader 9.0\\Reader\\"; openFileDialog1.Filter = "Executable files (*.exe)|*.exe"; //"Text files (*.txt)|*.txt|All files (*.*)|*.*" openFileDialog1.FileName = "*"; var file = openFileDialog1.ShowDialog(); if (file == DialogResult.OK) { // Only File Name string fileName = openFileDialog1.SafeFileName; // Full Path including file name string fullPathFileName = openFileDialog1.FileName; txtValueExtended.Text = fullPathFileName; } } } } <file_sep>using FCMMySQLBusinessLibrary; using MackkadoITFramework.ErrorHandling; namespace MackkadoITFramework.Security { public class BUSUserAccess { /// <summary> /// Add role /// </summary> /// <returns></returns> public static ResponseStatus Save(UserAccess inUser) { ResponseStatus response = new ResponseStatus(); UserAccess user = new UserAccess(); user.UserID = inUser.UserID; user.UserName = inUser.UserName; user.Salt = inUser.Salt; user.Password = <PASSWORD>; // We need to create a second occurrence. var userRead = new UserAccess(); var readuser = userRead.Read(inUser.UserID); // record found if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0001) { response = user.UpdateUser(); } // Not found if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0002) { response = user.AddUser(); } if (readuser.ReturnCode < 0000) { response = readuser; } return response; } /// <summary> /// Save password /// </summary> /// <returns></returns> public static ResponseStatus SavePassword(UserAccess inUser) { ResponseStatus response = new ResponseStatus(); UserAccess user = new UserAccess(); user.UserID = inUser.UserID; user.Salt = inUser.Salt; user.Password = <PASSWORD>; // Check if user exists // We need to create a second occurrence. UserAccess userRead = new UserAccess(); var readuser = userRead.Read(inUser.UserID); if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0001 ) { response = user.UpdatePassword(); return response; } if (readuser.ReturnCode == 0001 && readuser.ReasonCode == 0002) { response.ReturnCode = -0010; response.ReasonCode = 0001; response.Message = "User not found."; response.UniqueCode = ResponseStatus.MessageCode.Error.FCMERR00009999; return response; } if (readuser.ReturnCode < 0000 ) { response = readuser; } return response; } /// <summary> /// Add new role /// </summary> /// <param name="clientContract"></param> /// <returns></returns> public static ResponseStatus AddRole(SecurityRole inRole) { ResponseStatus response = new ResponseStatus(); var role = new SecurityRole(); role.Role = inRole.Role; role.Description = inRole.Description; response = role.Add(); response.Contents = role; return response; } /// <summary> /// Add new screen to role /// </summary> /// <param name="clientContract"></param> /// <returns></returns> public static ResponseStatus AddScreenToRole(SecurityRoleScreen inRole) { ResponseStatus response = new ResponseStatus(); var role = new SecurityRoleScreen(); role.FKRoleCode = inRole.FKRoleCode; role.FKScreenCode = inRole.FKScreenCode; response = role.Add(); response.Contents = role; return response; } public static ResponseStatus ListByRole(string inRole) { ResponseStatus response = new ResponseStatus(); var list = SecurityRoleScreen.List(inRole); response.Contents = list; return response; } } } <file_sep>using System; using System.Drawing; using System.ComponentModel; using System.Linq; using System.Windows.Forms; using fcm.Windows.Others; using FCMMySQLBusinessLibrary.Service.SVCClient.Service; using FCMMySQLBusinessLibrary.Service.SVCClient; using FCMMySQLBusinessLibrary.Model.ModelClient; using FCMMySQLBusinessLibrary.FCMUtils; using MackkadoITFramework.ReferenceData; using MackkadoITFramework.Utils; using fcm.Windows.Cache; using ConnString = MackkadoITFramework.Utils.ConnString; using HeaderInfo = MackkadoITFramework.Utils.HeaderInfo; using Utils = FCMMySQLBusinessLibrary.FCMUtils.Utils; using FCMMySQLBusinessLibrary.Model.ModelClient; namespace fcm.Windows { /// <summary> /// Summary description for Form1. /// </summary> public class UIfcm : Form { private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MainMenu mainMenu; private IContainer components; private System.Windows.Forms.OpenFileDialog openFileDialog; private MenuItem menuItem2; private MenuItem menuItem7; private string _userID; private MenuItem miReferenceData; private MenuItem miReportMetadata; private MenuItem miProposal; private MenuItem miDocumentSetList; private PictureBox pictureBox1; private MenuItem miDocumentList; private MenuItem menuItem8; private ToolStrip toolStrip1; private ToolStripButton toolStripExit; private ToolStripButton toolStripClient; private MenuItem menuItem3; private MenuItem miDocumentLink; private MenuItem menuItem11; private MenuItem miDocumentSetLink; private MenuItem miUsers; private MenuItem miUserSettings; private MenuItem miProcessRequest; private MenuItem miListNew; private StatusStrip statusStrip1; private ToolStripStatusLabel toolStripStatusLabel1; private MenuItem miRelatedReferenceCode; private ToolStripStatusLabel toolStripStatusLabel2; private ToolStripStatusLabel tslLoadedFrom; private MenuItem menuItem1; private MenuItem menuItem4; private MenuItem miImpacted; public UIfcm() { InitializeComponent(); HeaderInfo headerInfo; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UIfcm)); this.mainMenu = new System.Windows.Forms.MainMenu(this.components); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.miListNew = new System.Windows.Forms.MenuItem(); this.miProposal = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.miDocumentList = new System.Windows.Forms.MenuItem(); this.miDocumentLink = new System.Windows.Forms.MenuItem(); this.menuItem11 = new System.Windows.Forms.MenuItem(); this.miDocumentSetList = new System.Windows.Forms.MenuItem(); this.miDocumentSetLink = new System.Windows.Forms.MenuItem(); this.menuItem7 = new System.Windows.Forms.MenuItem(); this.miReferenceData = new System.Windows.Forms.MenuItem(); this.miReportMetadata = new System.Windows.Forms.MenuItem(); this.miUsers = new System.Windows.Forms.MenuItem(); this.miUserSettings = new System.Windows.Forms.MenuItem(); this.miRelatedReferenceCode = new System.Windows.Forms.MenuItem(); this.menuItem8 = new System.Windows.Forms.MenuItem(); this.miImpacted = new System.Windows.Forms.MenuItem(); this.miProcessRequest = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripExit = new System.Windows.Forms.ToolStripButton(); this.toolStripClient = new System.Windows.Forms.ToolStripButton(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.tslLoadedFrom = new System.Windows.Forms.ToolStripStatusLabel(); this.menuItem4 = new System.Windows.Forms.MenuItem(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.toolStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // mainMenu // this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem5, this.menuItem2, this.menuItem3, this.menuItem11, this.menuItem7, this.menuItem8}); // // menuItem5 // this.menuItem5.Index = 0; this.menuItem5.Text = "E&xit"; this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click); // // menuItem2 // this.menuItem2.Index = 1; this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miListNew, this.miProposal}); this.menuItem2.Text = "Client"; // // miListNew // this.miListNew.Index = 0; this.miListNew.Tag = "CLNTLIST"; this.miListNew.Text = "List"; this.miListNew.Click += new System.EventHandler(this.miListNew_Click); // // miProposal // this.miProposal.Index = 1; this.miProposal.Text = "Proposal"; this.miProposal.Click += new System.EventHandler(this.menuItem6_Click_1); // // menuItem3 // this.menuItem3.Index = 2; this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miDocumentList, this.miDocumentLink}); this.menuItem3.Text = "Document"; // // miDocumentList // this.miDocumentList.Index = 0; this.miDocumentList.Tag = "DOCLIST"; this.miDocumentList.Text = "List"; this.miDocumentList.Click += new System.EventHandler(this.menuItem1_Click); // // miDocumentLink // this.miDocumentLink.Index = 1; this.miDocumentLink.Tag = "DOCLINK"; this.miDocumentLink.Text = "Link"; this.miDocumentLink.Click += new System.EventHandler(this.menuItem12_Click); // // menuItem11 // this.menuItem11.Index = 3; this.menuItem11.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miDocumentSetList, this.miDocumentSetLink}); this.menuItem11.Text = "Document Set"; // // miDocumentSetList // this.miDocumentSetList.Index = 0; this.miDocumentSetList.Tag = "DOCSETLIST"; this.miDocumentSetList.Text = "List"; this.miDocumentSetList.Click += new System.EventHandler(this.menuItem9_Click); // // miDocumentSetLink // this.miDocumentSetLink.Index = 1; this.miDocumentSetLink.Tag = "DOCSETLINK"; this.miDocumentSetLink.Text = "Link"; this.miDocumentSetLink.Click += new System.EventHandler(this.menuItem13_Click); // // menuItem7 // this.menuItem7.Index = 4; this.menuItem7.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miReferenceData, this.miReportMetadata, this.miUsers, this.miUserSettings, this.miRelatedReferenceCode}); this.menuItem7.Text = "Maintenance"; // // miReferenceData // this.miReferenceData.Index = 0; this.miReferenceData.Tag = "REFERENCEDATA"; this.miReferenceData.Text = "Reference Data"; this.miReferenceData.Click += new System.EventHandler(this.miReferenceData_Click); // // miReportMetadata // this.miReportMetadata.Index = 1; this.miReportMetadata.Tag = "REPORTMETADATA"; this.miReportMetadata.Text = "Report Metadata"; this.miReportMetadata.Click += new System.EventHandler(this.menuItem4_Click); // // miUsers // this.miUsers.Index = 2; this.miUsers.Tag = "USERACCESS"; this.miUsers.Text = "Users Authorisation"; this.miUsers.Click += new System.EventHandler(this.miUsers_Click); // // miUserSettings // this.miUserSettings.Index = 3; this.miUserSettings.Tag = "USERSETTINGS"; this.miUserSettings.Text = "User Settings"; this.miUserSettings.Click += new System.EventHandler(this.menuItem14_Click); // // miRelatedReferenceCode // this.miRelatedReferenceCode.Index = 4; this.miRelatedReferenceCode.Text = "Related Reference Code"; this.miRelatedReferenceCode.Click += new System.EventHandler(this.miRelatedReferenceCode_Click); // // menuItem8 // this.menuItem8.Index = 5; this.menuItem8.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miImpacted, this.miProcessRequest, this.menuItem1, this.menuItem4}); this.menuItem8.Text = "Miscelaneous"; // // miImpacted // this.miImpacted.Index = 0; this.miImpacted.Tag = "DOCIMP"; this.miImpacted.Text = "Impacted Documents"; this.miImpacted.Click += new System.EventHandler(this.miImpactedDocuments); // // miProcessRequest // this.miProcessRequest.Index = 1; this.miProcessRequest.Tag = "PROCESSREQUEST"; this.miProcessRequest.Text = "Process Request"; this.miProcessRequest.Click += new System.EventHandler(this.miProcessRequest_Click); // // menuItem1 // this.menuItem1.Index = 2; this.menuItem1.Text = "Send Email"; this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click_1); // // openFileDialog // this.openFileDialog.Multiselect = true; this.openFileDialog.Title = "SAMS Parser.Net"; // // pictureBox1 // this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pictureBox1.Image = global::fcm.Properties.Resources.FCMLogo; this.pictureBox1.Location = new System.Drawing.Point(12, 929); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(236, 74); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripExit, this.toolStripClient}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(587, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked); // // toolStripExit // this.toolStripExit.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripExit.Image = ((System.Drawing.Image)(resources.GetObject("toolStripExit.Image"))); this.toolStripExit.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripExit.Name = "toolStripExit"; this.toolStripExit.Size = new System.Drawing.Size(23, 22); this.toolStripExit.Text = "Exit"; this.toolStripExit.Click += new System.EventHandler(this.menuItem5_Click); // // toolStripClient // this.toolStripClient.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripClient.Image = ((System.Drawing.Image)(resources.GetObject("toolStripClient.Image"))); this.toolStripClient.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripClient.Name = "toolStripClient"; this.toolStripClient.Size = new System.Drawing.Size(23, 22); this.toolStripClient.Text = "Client Details"; this.toolStripClient.Click += new System.EventHandler(this.miListNew_Click); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripStatusLabel2, this.tslLoadedFrom}); this.statusStrip1.Location = new System.Drawing.Point(0, 294); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(587, 22); this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(55, 17); this.toolStripStatusLabel1.Text = "Database"; // // toolStripStatusLabel2 // this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; this.toolStripStatusLabel2.Size = new System.Drawing.Size(46, 17); this.toolStripStatusLabel2.Text = "Version"; this.toolStripStatusLabel2.Click += new System.EventHandler(this.toolStripStatusLabel2_Click); // // tslLoadedFrom // this.tslLoadedFrom.Name = "tslLoadedFrom"; this.tslLoadedFrom.Size = new System.Drawing.Size(77, 17); this.tslLoadedFrom.Text = "Loaded From"; // // menuItem4 // this.menuItem4.Index = 3; this.menuItem4.Text = "Load Cache"; this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click_1); // // UIfcm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.ClientSize = new System.Drawing.Size(587, 316); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.pictureBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu; this.Name = "UIfcm"; this.ShowIcon = false; this.Tag = "C:\\\\ProgramFiles\\\\FCM"; this.Text = " "; this.Load += new System.EventHandler(this.frmParserMainUI_Load); this.Leave += new System.EventHandler(this.frmParserMainUI_Leave); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new UIfcm()); } private void menuItem5_Click(object sender, System.EventArgs e) { // Terminate the program LogFile.WriteToTodaysLogFile("User has logged off", Utils.UserID); this.Dispose(); } private void miClient_Click(object sender, EventArgs e) { UIClientDetails ClientDetails = new UIClientDetails(this); ClientDetails.Show(); } /// <summary> /// Load method /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void frmParserMainUI_Load(object sender, EventArgs e) { // Set current environment Utils.FCMenvironment = MackkadoITFramework.Helper.Utils.EnvironmentList.LOCAL; UILogon log = new UILogon(); log.ShowDialog(); if (log.connectedTo == "not connected" || string.IsNullOrEmpty(log.connectedTo)) Application.Exit(); if (log.connectedTo == "Local") toolStripStatusLabel1.BackColor = Color.Green; if (log.connectedTo == "Server") toolStripStatusLabel1.BackColor = Color.Red; // Utils.ClientList = Client.List(); int st = ConnString.ConnectionString.IndexOf("Data Source"); int en = ConnString.ConnectionString.IndexOf(";"); if (st > 0 && en > 0) { string s = ConnString.ConnectionString.Substring(st, en - st); toolStripStatusLabel1.Text = string.Format("({0}) {1}", log.connectedTo, s); } else { toolStripStatusLabel1.Text = string.Format("({0}) {1}", log.connectedTo, ConnString.ConnectionString.Substring(0,10)); } toolStripStatusLabel2.Text = @"Version: " + ControllerUtils.GetCurrentAssemblyVersion(); tslLoadedFrom.Text = this.Tag.ToString(); var responseCL = new BUSClient().ClientList(HeaderInfo.Instance); var responseClientList = responseCL.clientList; // Retrieve last client id // var lastClient = new CodeValue(); lastClient.FKCodeType = "LASTINFO"; lastClient.ID = "CLIENTID"; lastClient.Read(false); try { Utils.ClientID = Convert.ToInt32(lastClient.ValueExtended); } catch { Utils.ClientID = Utils.ClientList[0].UID; } // Load HeaderInfo HeaderInfo.Instance.UserID = Utils.UserID; HeaderInfo.Instance.CurrentDateTime = DateTime.Now; // Remove menu items // Get full list of screens var fullListOfScreens = CachedInfo.GetListOfCodeValue(FCMConstant.CodeTypeString.SCREENCODE); // var listOfScreen = BUSReferenceData.GetListScreensForUser(Utils.UserID); foreach (var screen in fullListOfScreens) { bool found = CachedInfo.ListOfScreensAllowedToUser.Any(allowedScreen => allowedScreen.ID == screen.ID); //foreach (var allowedScreen in CachedInfo.ListOfScreensAllowedToUser) //{ // if (allowedScreen.ID == screen.ID) // { // found = true; // break; // } //} if (found) continue; // find screen disallowed and hide switch (screen.ID) { case FCMConstant.ScreenCode.DocumentSetLink: miDocumentSetLink.Enabled = false; break; case FCMConstant.ScreenCode.DocumentSetList: miDocumentSetList.Enabled = false; break; case FCMConstant.ScreenCode.DocumentList: miDocumentList.Enabled = false; break; case FCMConstant.ScreenCode.DocumentLink: miDocumentLink.Enabled = false; break; case FCMConstant.ScreenCode.ClientList: toolStripClient.Enabled = false; miListNew.Enabled = false; break; case FCMConstant.ScreenCode.ReportMetadata: miReportMetadata.Enabled = false; break; case FCMConstant.ScreenCode.ReferenceData: miReferenceData.Enabled = false; break; //case FCMConstant.ScreenCode.UserAccess: // miUsers.Enabled = false; // break; case FCMConstant.ScreenCode.UserSettings: miUserSettings.Enabled = false; break; case FCMConstant.ScreenCode.ImpactedDocuments: miImpacted.Enabled = false; break; case FCMConstant.ScreenCode.ProcessRequest: miProcessRequest.Enabled = false; break; } } this.Activate(); // Utils.ClientIndex = 0; } private void miMaintainProjectDocuments_Click(object sender, EventArgs e) { } private void menuItem6_Click(object sender, EventArgs e) { UIReportMetadata generalMetadata = new UIReportMetadata(this); generalMetadata.Show(); } private void menuItem4_Click(object sender, EventArgs e) { UIReportMetadata gmd = new UIReportMetadata(this); gmd.Show(); } private void menuItem6_Click_1(object sender, EventArgs e) { UIProposal uip = new UIProposal(); uip.Show(); } private void menuItem9_Click(object sender, EventArgs e) { UIDocument utf = new UIDocument(); utf.Show(); } private void menuItem1_Click(object sender, EventArgs e) { UIDocumentList uid = new UIDocumentList(); uid.Show(); } private void frmParserMainUI_Leave(object sender, EventArgs e) { Application.Exit(); } private void miReferenceData_Click(object sender, EventArgs e) { UIReferenceData referenceData = new UIReferenceData(this); referenceData.Show(); } private void miImpactedDocuments(object sender, EventArgs e) { UIImpactedDocuments uiimpactedDocuments = new UIImpactedDocuments(); uiimpactedDocuments.Show(); } private void miProjectPlan_Click(object sender, EventArgs e) { UIProjectPlan uipp = new UIProjectPlan(); uipp.Show(); } private void menuItem3_Click(object sender, EventArgs e) { UIDocumentLink uidl = new UIDocumentLink(); uidl.Show(); } private void menuItem13_Click(object sender, EventArgs e) { UIDocumentSetDocumentLink uidosdl = new UIDocumentSetDocumentLink(); uidosdl.ShowDialog(); } private void menuItem12_Click(object sender, EventArgs e) { UIDocumentLink uidl = new UIDocumentLink(); uidl.Show(); } private void miUsers_Click(object sender, EventArgs e) { UIUserAccess uiua = new UIUserAccess(); uiua.Show(); } private void menuItem14_Click(object sender, EventArgs e) { UIUserSettings uius = new UIUserSettings(); uius.Show(); } private void miProcessRequest_Click(object sender, EventArgs e) { UIProcessRequest upr = new UIProcessRequest(); upr.Show(); } private void miListNew_Click(object sender, EventArgs e) { UIClientList uicl = new UIClientList(this); uicl.Show(); } private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void miRelatedReferenceCode_Click(object sender, EventArgs e) { UIRelatedReferenceData uirr = new UIRelatedReferenceData(); uirr.Show(); } private void toolStripStatusLabel2_Click(object sender, EventArgs e) { } private void menuItem1_Click_1(object sender, EventArgs e) { UISendEmail usemail = new UISendEmail(); usemail.Show(); } private void menuItem4_Click_1(object sender, EventArgs e) { CodeType ct = new CodeType(); ct.Redis_StoreCodeTypes(); } } }
f71c19960e87fb7f6737564cbcf5adf81f1884e8
[ "C#", "SQL", "INI" ]
167
C#
DR2010/FCMGitY
73412f8a17597413d9e9bd88616ccd82b496848f
2f717c8e00d2babe3b83c8f63691acf4e17bd9ec
refs/heads/master
<repo_name>PlumpMath/blockchain-samples<file_sep>/OSIsoft.Blockchain/OSIsoft.Blockchain/Block.cs // // // <copyright file="Block.cs" company="OSIsoft, LLC"> // // // Copyright (c) 2017 OSIsoft, LLC. All rights reserved. // // // // // // THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF // // // OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT // // // THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. // // // // // // RESTRICTED RIGHTS LEGEND // // // Use, duplication, or disclosure by the Government is subject to restrictions // // // as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and // // // Computer Software clause at DFARS 252.227.7013 // // // // // // OSIsoft, LLC // // // 1600 Alvarado Street. San Leandro, CA 94577 USA // // // </copyright> using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace OSIsoft.Blockchain { /// <summary> /// Represents a block in the blockchain. Contains data, a reference to the previous block and can compute the hash for /// this block /// </summary> public class Block { /// <summary> /// Used to create SHA256 hashes /// </summary> private static readonly SHA256Managed sha256 = new SHA256Managed(); /// <summary> /// Constructor. Can only create a new block with an ancestor (except for the genesis block) /// </summary> /// <param name="previousBlock"></param> public Block(Block previousBlock) { this.PreviousBlock = previousBlock; } /// <summary> /// Reference to the previous (ancestor) block /// </summary> public Block PreviousBlock { get; } /// <summary> /// The sequence of this block in the chain /// </summary> public int BlockNumber { get; set; } /// <summary> /// The nonce. A value that can be changed by the miner to get a sha256 hash that reprents the difficulty level for /// this block /// </summary> public int Nonce { get; set; } /// <summary> /// The difficulty level for this block. The sha256 hash for this block has to lead with n 0 bytes /// (note, when converted to string is represented by 00 (1 byte = max 265 values (0 to 255) = 00 to FF), so a hash /// with difficulty = 1 will look like 00........ and with difficulty level 2 will look like 0000.... /// </summary> public int Difficulty { get; set; } /// <summary> /// The data for this block /// </summary> public byte[] Data { get; set; } = {0x00}; /// <summary> /// A reference to the sha256 hash of the previous block. The genesis block does not have a previous block so the hash /// = 0x0 /// </summary> public byte[] PreviousBlockHash => this.PreviousBlock?.Hash ?? new byte[0]; /// <summary> /// The sha256 hash for this block /// </summary> public byte[] Hash => this.ComputeHash(); /// <summary> /// Print out the contents and information for this block /// </summary> /// <returns></returns> public override string ToString() { var builder = new StringBuilder(); builder.AppendLine(); builder.AppendLine($"Block #: \t {this.BlockNumber}"); builder.AppendLine($"Nonce: \t\t {this.Nonce}"); builder.AppendLine($"Data: \t\t {Encoding.UTF8.GetString(this.Data)}"); builder.AppendLine( $"Prev hash: \t {(this.PreviousBlockHash != null ? this.PreviousBlockHash.HashToString() : string.Empty)}"); builder.AppendLine($"Hash: \t\t {this.Hash.HashToString()}"); builder.AppendLine($"Is valid: \t {this.IsValid()}"); builder.AppendLine(); return builder.ToString(); } /// <summary> /// Gets the 'internal contents' of this block that is used to compute the hash. /// </summary> /// <returns>byte array containing the previous block hash + the nonce + the data</returns> public byte[] GetInternalContents() { //The contents are [ previousblockhash (byte[32] + nonce (int = byte[4]) + data (byte[n]) ], [ 32 bytes + 4 bytes + data.length] //Create the new byte array with the specified length var contents = new byte[32 + 4 + this.Data.Length]; //Copy the hash of the previous block in the new array this.PreviousBlockHash.CopyTo(contents, 0); //Convert the nonce to a byte array var nonce = BitConverter.GetBytes(this.Nonce); //Copy the nonce to the new array nonce.CopyTo(contents, 32); //Copy the data to the new array this.Data.CopyTo(contents, 36); return contents; } public byte[] ComputeHash() { //Get the internal contents for this block ([prevousblockhash+nonce+data] var contents = this.GetInternalContents(); //Calculate the hash var hash = sha256.ComputeHash(contents); return hash; } public bool IsValid() { //Check if the calculated hash conforms to the difficulty level. It should start with n number of 0 bytes return this.Hash.Take(this.Difficulty).All(b => b == new byte()); } } }<file_sep>/OSIsoft.Blockchain/OSIsoft.Blockchain/BlockChain.cs // // // <copyright file="BlockChain.cs" company="OSIsoft, LLC"> // // // Copyright (c) 2017 OSIsoft, LLC. All rights reserved. // // // // // // THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF // // // OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT // // // THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. // // // // // // RESTRICTED RIGHTS LEGEND // // // Use, duplication, or disclosure by the Government is subject to restrictions // // // as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and // // // Computer Software clause at DFARS 252.227.7013 // // // // // // OSIsoft, LLC // // // 1600 Alvarado Street. San Leandro, CA 94577 USA // // // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OSIsoft.Blockchain { /// <summary> /// Ordered list of blocks. /// </summary> public class BlockChain : List<Block> { /// <summary> /// Retrieve the first (genesis) block in the chain /// </summary> public Block GenesisBlock => this.First(); /// <summary> /// Retrieve the last block /// </summary> public Block LastBlock => this.Last(); /// <summary> /// Checks if the whole chain is valid /// </summary> public bool IsValid => this.LastBlock.IsValid(); /// <summary> /// Prints out the status of all blocks in the chain /// </summary> /// <returns>string</returns> public override string ToString() { var builder = new StringBuilder(); builder.AppendLine(new string('-', Console.WindowWidth - 1)); foreach (var kv in this) builder.AppendLine(kv.ToString()); builder.AppendLine(new string('-', Console.WindowWidth - 1)); builder.AppendLine($"Is Valid: {this.IsValid}"); return builder.ToString(); } } }<file_sep>/OSIsoft.Blockchain/OSIsoft.Blockchain/Program.cs // // // <copyright file="Program.cs" company="OSIsoft, LLC"> // // // Copyright (c) 2017 OSIsoft, LLC. All rights reserved. // // // // // // THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF // // // OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT // // // THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. // // // // // // RESTRICTED RIGHTS LEGEND // // // Use, duplication, or disclosure by the Government is subject to restrictions // // // as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and // // // Computer Software clause at DFARS 252.227.7013 // // // // // // OSIsoft, LLC // // // 1600 Alvarado Street. San Leandro, CA 94577 USA // // // </copyright> using System; using System.Text; namespace OSIsoft.Blockchain { /// <summary> /// Very simple demonstration of a simplified blockchain data structure. Demonstrates the fact that the whole /// blockchain becomes invalid when a single block becomes invalid when it is mutated and not remined. /// Demonstrates a very simple Proof Of Work algorithm. /// </summary> internal class Program { /// <summary> /// The miner being used to mine our blocks /// </summary> private static Miner miner; /// <summary> /// The blockchain itself. Basically an ordered list of linked blocks /// </summary> private static BlockChain blockChain; /// <summary> /// Main application entry point /// </summary> /// <param name="args"></param> private static void Main(string[] args) { blockChain = new BlockChain(); miner = new Miner(); //First we have to create a genesis block. This is the only block without an ancestor. //We can pass in the difficulty of the genesis block and all subsequent blocks //Try setting the difficulty level higher to make mutations to the chain more difficult to recompute (more tamper proof) //In the real world, and with a large chain and a high difficulty this can take many hundreds of thousands of computing hours, making it very expensive to tamper with blocks. var genesisBlock = new GenesisBlock(2); //Mine the genesis block. This is not strictly necessary as the right nonce could already be hardcoded. miner.Mine(genesisBlock); //Add the genesis block to the blockchain as the first block blockChain.Add(genesisBlock); //Create a couple of blocks and add them to the blockchain for (var i = 0; i < 10; i++) AddBlock("Hello OSIsoft!. I am block #" + i, blockChain.LastBlock); //Write out the whole (valid) blockchain Console.WriteLine("Valid chain"); Console.WriteLine(blockChain); //Wait for the user to examine the valid blockchain Console.WriteLine("Press enter to tamper with the chain"); Console.ReadLine(); //Tamper with the data of a specific block. This should invalidate the hash and cause all subsequent blocks to have invalid hashes as well. blockChain[3].Data = Encoding.UTF8.GetBytes("I have been tampered with"); //Write out the whole (now invalid) block. All blocks starting with index 3 should now be invalid, even though their data has not changed (but their hash has, because the previous block's hash changed). Console.WriteLine("Invalid chain"); Console.WriteLine(blockChain); //Wait for the user to examine the invalid chain Console.WriteLine("Press enter to re-mine the blocks"); Console.ReadLine(); for (int i = 3; i < blockChain.Count; i++) { miner.Mine(blockChain[i]); } //Print out the re-mined (now valid again) blockchain Console.WriteLine(blockChain); //Wait for the user to examine the now valid blockchain Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } /// <summary> /// Helper method to add a block to the blockchain /// </summary> /// <param name="text">The text to appear in the 'data' section of the block</param> /// <param name="previousBlock">The </param> private static void AddBlock(string text, Block previousBlock) { //Encode the string var data = Encoding.UTF8.GetBytes(text); //Mine the new block var block = miner.Mine(data, previousBlock); //Add the block to the blockchain blockChain.Add(block); } } }<file_sep>/README.md # blockchain-samples Provides simple samples from my blockchain research. # OSIsoft.Blockchain Very simple blockchain data structure implementation in C# to demonstrate Proof Of Work <file_sep>/OSIsoft.Blockchain/OSIsoft.Blockchain/Miner.cs // // // <copyright file="Miner.cs" company="OSIsoft, LLC"> // // // Copyright (c) 2017 OSIsoft, LLC. All rights reserved. // // // // // // THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF // // // OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT // // // THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. // // // // // // RESTRICTED RIGHTS LEGEND // // // Use, duplication, or disclosure by the Government is subject to restrictions // // // as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and // // // Computer Software clause at DFARS 252.227.7013 // // // // // // OSIsoft, LLC // // // 1600 Alvarado Street. San Leandro, CA 94577 USA // // // </copyright> namespace OSIsoft.Blockchain { /// <summary> /// Simplified miner. /// </summary> public class Miner { /// <summary> /// Will create a new block using the specified data and the specified ancestor block. Will mine the block. /// </summary> /// <param name="data"></param> /// <param name="lastBlock"></param> /// <returns></returns> public Block Mine(byte[] data, Block lastBlock) { var block = new Block(lastBlock) { BlockNumber = lastBlock.BlockNumber + 1, Data = data, Difficulty = lastBlock.Difficulty }; this.Mine(block); return block; } /// <summary> /// Mine a block. Will increment the nonce of the block until the block is valid (the desired difficulty level has been /// reached) /// </summary> /// <param name="block"></param> public void Mine(Block block) { do { block.Nonce++; } while (!block.IsValid()); } } }<file_sep>/OSIsoft.Blockchain/OSIsoft.Blockchain/GenesisBlock.cs // // // <copyright file="GenesisBlock.cs" company="OSIsoft, LLC"> // // // Copyright (c) 2017 OSIsoft, LLC. All rights reserved. // // // // // // THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF // // // OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT // // // THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. // // // // // // RESTRICTED RIGHTS LEGEND // // // Use, duplication, or disclosure by the Government is subject to restrictions // // // as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and // // // Computer Software clause at DFARS 252.227.7013 // // // // // // OSIsoft, LLC // // // 1600 Alvarado Street. San Leandro, CA 94577 USA // // // </copyright> namespace OSIsoft.Blockchain { /// <summary> /// Helper class for a genesis block. Sets the blocknumber to 0 and will set the desired difficulty level for the /// descendant blocks. /// </summary> public class GenesisBlock : Block { public GenesisBlock(int difficulty, byte[] data = null) : base(null) { this.BlockNumber = 0; this.Nonce = 0; this.Data = data ?? new byte[0]; this.Difficulty = difficulty; } } }<file_sep>/OSIsoft.Blockchain/OSIsoft.Blockchain/Extensions.cs // // // <copyright file="Extensions.cs" company="OSIsoft, LLC"> // // // Copyright (c) 2017 OSIsoft, LLC. All rights reserved. // // // // // // THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF // // // OSIsoft, LLC. USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT // // // THE PRIOR EXPRESS WRITTEN PERMISSION OF OSIsoft, LLC. // // // // // // RESTRICTED RIGHTS LEGEND // // // Use, duplication, or disclosure by the Government is subject to restrictions // // // as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and // // // Computer Software clause at DFARS 252.227.7013 // // // // // // OSIsoft, LLC // // // 1600 Alvarado Street. San Leandro, CA 94577 USA // // // </copyright> using System.Linq; namespace OSIsoft.Blockchain { /// <summary> /// Extension helper methods /// </summary> public static class Extensions { /// <summary> /// Helper method to print out a hash to a readable string format (hex) /// </summary> /// <param name="hash"></param> /// <returns></returns> public static string HashToString(this byte[] hash) { return string.Join("", hash.Select(b => b.ToString("x2"))); } } }
7e880b260570ee1a3ce4855b67ea86f995da842a
[ "Markdown", "C#" ]
7
C#
PlumpMath/blockchain-samples
fc8cffda3f6086192cf30ab93b3ee4d7b158aa08
00d0f35b1d15df5f6251f6427d0819628f3e6cf6
refs/heads/master
<repo_name>seacamjen/favorite-things<file_sep>/js/scripts.js $(document).ready(function(){ $("#formOne").submit(function(){ event.preventDefault(); var array = []; array.push($("#question1").val()); array.push($("#question2").val()); array.push($("#question3").val()); array.push($("#question4").val()); array.push($("#question5").val()); console.log(array); var array2 = [array[1], array[0], array[2]]; console.log(array2); $("#outputHeader").show(); $("#outputList").show(); $("#outputList").append("<li>" + array2[0] + "</li>"); $("#outputList").append("<li>" + array2[1] + "</li>"); $("#outputList").append("<li>" + array2[2] + "</li>"); }) })
d67b13869b764a15c6404963da4ae21f0456ba9e
[ "JavaScript" ]
1
JavaScript
seacamjen/favorite-things
89b14e9e5c2ce1f2e63b3ccd53692765094790b9
4e6b8d1c722a5948e6a2702976c363f1ae5b87c7
refs/heads/master
<file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\Regions; use DigitalOcean\Tests\TestCase; use DigitalOcean\Regions\Regions; /** * @author <NAME> <<EMAIL>> */ class RegionsTest extends TestCase { /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/droplets/?client_id=foo&api_key=bar */ public function testProcessQuery() { $regions = new Regions($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $regions->getAll(); } public function testGetAllUrl() { $regions = new Regions($this->getMockCredentials(), $this->getMockAdapter($this->never())); $method = new \ReflectionMethod( $regions, 'buildQuery' ); $method->setAccessible(true); $this->assertEquals( 'https://api.digitalocean.com/regions/?client_id=foo&api_key=bar', $method->invoke($regions) ); } public function testGetAll() { $response = <<<JSON {"status":"OK","regions":[{"id":1,"name":"New York 1"},{"id":2,"name":"Amsterdam 1"}]} JSON ; $regions = new Regions($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $regions = $regions->getAll(); $this->assertTrue(is_object($regions)); $this->assertEquals('OK', $regions->status); $this->assertCount(2, $regions->regions); $region1 = $regions->regions[0]; $this->assertSame(1, $region1->id); $this->assertSame('New York 1', $region1->name); $region2 = $regions->regions[1]; $this->assertSame(2, $region2->id); $this->assertSame('Amsterdam 1', $region2->name); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\Domains; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Domains\ShowCommand; /** * @author <NAME> <<EMAIL>> */ class ShowCommandTest extends TestCase { protected $application; protected $command; protected $commandTester; protected function setUp() { $this->application = new Application(); $result = (object) array( 'domain' => (object) array( 'id' => 1, 'name' => 'foo.org', 'ttl' => 1800, 'live_zone_file' => '$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.foo.org. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n', 'error' => null, 'zone_file_with_error' => null, ) ); $ShowCommand = $this->getMock('\DigitalOcean\CLI\Domains\ShowCommand', array('getDigitalOcean')); $ShowCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('domains', $this->getMockDomains('show', $result)))); $this->application->add($ShowCommand); $this->command = $this->application->find('domains:show'); $this->commandTester = new CommandTester($this->command); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not enough arguments. */ public function testExecuteNotEnoughArguments() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); } public function testExecute() { $this->commandTester->execute(array( 'command' => $this->command->getName(), 'id' => 123, )); $expected = <<<'EOT' +----+---------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+----------------------+ | ID | Name | TTL | Live Zone File | Error | Zone File With Error | +----+---------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+----------------------+ | 1 | foo.org | 1800 | $TTL\t600\n@\t\tIN\tSOA\tNS1.DIGITALOCEAN.COM.\thostmaster.foo.org. (\n\t\t\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\n\t\t\t3600 ; refresh\n\t\t\t900 ; retry\n\t\t\t1209600 ; expire\n\t\t\t10800 ; 3 hours ttl\n\t\t\t)\n IN NS NS1.DIGITALOCEAN.COM.\n @\tIN A\t8.8.8.8\n | | | +----+---------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+----------------------+ EOT ; $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertSame($expected, $this->commandTester->getDisplay()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\Domains; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Domains\AddCommand; /** * @author <NAME> <<EMAIL>> */ class AddCommandTest extends TestCase { protected $application; protected $command; protected $commandTester; protected function setUp() { $this->application = new Application(); $result = (object) array( 'status' => 'OK', 'domain' => (object) array( 'id' => 123, 'name' => 'foo.org', ), ); $AddCommand = $this->getMock('\DigitalOcean\CLI\Domains\AddCommand', array('getDigitalOcean')); $AddCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('domains', $this->getMockDomains('add', $result)))); $this->application->add($AddCommand); $this->command = $this->application->find('domains:add'); $this->commandTester = new CommandTester($this->command); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not enough arguments. */ public function testExecuteNotEnoughArguments() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not enough arguments. */ public function testExecuteNotEnoughArgumentsWithoutName() { $this->commandTester->execute(array( 'command' => $this->command->getName(), 'ip_address' => '127.0.0.1', )); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not enough arguments. */ public function testExecuteNotEnoughArgumentsWithoutIpaddress() { $this->commandTester->execute(array( 'command' => $this->command->getName(), 'name' => 'foo.org', )); } public function testExecute() { $this->commandTester->execute(array( 'command' => $this->command->getName(), 'name' => 'foo.org', 'ip_address' => '127.0.0.1', )); $expected = <<<EOT +--------+-----+---------+ | Status | ID | Name | +--------+-----+---------+ | OK | 123 | foo.org | +--------+-----+---------+ EOT ; $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertSame($expected, $this->commandTester->getDisplay()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\Droplets; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Droplets\CreateInteractiveCommand; /** * @author <NAME> <<EMAIL>> */ class CreateInteractiveCommandTest extends TestCase { protected $application; protected function setUp() { $this->application = new Application(); } public function testExecuteWithoutDropletName() { $CreateInteractiveCommand = $this->getMock('\DigitalOcean\CLI\Droplets\CreateInteractiveCommand', array('getDigitalOcean')); $CreateInteractiveCommand ->expects($this->once()) ->method('getDigitalOcean') ->will($this->returnValue( $this->getMockDigitalOcean('droplets', $this->getMockDroplets('create', null)) )); $this->application->add($CreateInteractiveCommand); $command = $this->application->find('droplets:create-interactively'); $command->getHelperSet()->set($this->getDialogAsk(null), 'dialog'); $commandTester = new CommandTester($command); $commandTester->execute(array( 'command' => $command->getName(), )); $this->assertTrue(is_string($commandTester->getDisplay())); $this->assertRegExp('/Aborted!/', $commandTester->getDisplay()); } public function testExecuteWithDropletName() { $this->markTestIncomplete('Make a test with a droplet name'); } public function testGetSizes() { $sizes = (object) array( 'sizes' => array( (object) array('id' => 1, 'name' => 'foo'), (object) array('id' => 2, 'name' => 'bar'), ) ); $digitalOcean = $this->getMockDigitalOcean('sizes', $this->getMockSizes($sizes)); $CreateInteractiveCommand = new CreateInteractiveCommand(); $method = new \ReflectionMethod( $CreateInteractiveCommand, 'getSizes' ); $method->setAccessible(true); $results = $method->invoke($CreateInteractiveCommand, $digitalOcean); $this->assertTrue(is_array($results)); $this->assertCount(2, $results); $this->assertSame('foo', $results[1]); $this->assertSame('bar', $results[2]); } public function testGetRegions() { $regions = (object) array( 'regions' => array( (object) array('id' => 1, 'name' => 'foo 1'), (object) array('id' => 2, 'name' => 'bar 2'), ) ); $digitalOcean = $this->getMockDigitalOcean('regions', $this->getMockRegions($regions)); $CreateInteractiveCommand = new CreateInteractiveCommand(); $method = new \ReflectionMethod( $CreateInteractiveCommand, 'getRegions' ); $method->setAccessible(true); $results = $method->invoke($CreateInteractiveCommand, $digitalOcean); $this->assertTrue(is_array($results)); $this->assertCount(2, $results); $this->assertSame('foo 1', $results[1]); $this->assertSame('bar 2', $results[2]); } public function testGetGlobalImages() { $images = (object) array( 'images' => array( (object) array('id' => 1, 'name' => 'foo', 'distribution' => 'foobar dist'), (object) array('id' => 2, 'name' => 'bar', 'distribution' => 'barqmx dist'), ) ); $digitalOcean = $this->getMockDigitalOcean('images', $this->getMockImages('getGlobal', $images)); $CreateInteractiveCommand = new CreateInteractiveCommand(); $method = new \ReflectionMethod( $CreateInteractiveCommand, 'getImages' ); $method->setAccessible(true); $results = $method->invoke($CreateInteractiveCommand, $digitalOcean, 0); $this->assertTrue(is_array($results)); $this->assertCount(2, $results); $this->assertSame('foo, foobar dist', $results[1]); $this->assertSame('bar, barqmx dist', $results[2]); } public function testGetMyImages() { $images = (object) array( 'images' => array( (object) array('id' => 1, 'name' => 'foo', 'distribution' => 'foobar dist'), (object) array('id' => 2, 'name' => 'bar', 'distribution' => 'barqmx dist'), ) ); $digitalOcean = $this->getMockDigitalOcean('images', $this->getMockImages('getMyImages', $images)); $CreateInteractiveCommand = new CreateInteractiveCommand(); $method = new \ReflectionMethod( $CreateInteractiveCommand, 'getImages' ); $method->setAccessible(true); $results = $method->invoke($CreateInteractiveCommand, $digitalOcean, 1); $this->assertTrue(is_array($results)); $this->assertCount(2, $results); $this->assertSame('foo, foobar dist', $results[1]); $this->assertSame('bar, barqmx dist', $results[2]); } public function testGetAllImages() { $images = (object) array( 'images' => array( (object) array('id' => 1, 'name' => 'foo', 'distribution' => 'foobar dist'), (object) array('id' => 2, 'name' => 'bar', 'distribution' => 'barqmx dist'), ) ); $digitalOcean = $this->getMockDigitalOcean('images', $this->getMockImages('getAll', $images)); $CreateInteractiveCommand = new CreateInteractiveCommand(); $method = new \ReflectionMethod( $CreateInteractiveCommand, 'getImages' ); $method->setAccessible(true); $results = $method->invoke($CreateInteractiveCommand, $digitalOcean, 2); $this->assertTrue(is_array($results)); $this->assertCount(2, $results); $this->assertSame('foo, foobar dist', $results[1]); $this->assertSame('bar, barqmx dist', $results[2]); } public function testGetSshKays() { $sshKeys = (object) array( 'ssh_keys' => array( (object) array('id' => 123, 'name' => 'office-imac'), (object) array('id' => 456, 'name' => 'macbook-pro'), ) ); $digitalOcean = $this->getMockDigitalOcean('sshkeys', $this->getMockSSHKeys('getAll', $sshKeys)); $CreateInteractiveCommand = new CreateInteractiveCommand(); $method = new \ReflectionMethod( $CreateInteractiveCommand, 'getSshKeys' ); $method->setAccessible(true); $results = $method->invoke($CreateInteractiveCommand, $digitalOcean); $this->assertTrue(is_array($results)); $this->assertCount(3, $results); $this->assertSame('None (default)', $results[0]); $this->assertSame('office-imac', $results[123]); $this->assertSame('macbook-pro', $results[456]); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests; use DigitalOcean\Credentials; /** * @author <NAME> <<EMAIL>> */ class CrendentialsTest extends TestCase { protected $clientId; protected $apiKey; protected $credentials; protected function setUp() { $this->clientId = 'foo'; $this->apiKey = 'bar'; $this->credentials = new Credentials($this->clientId, $this->apiKey); } public function testGetClientId() { $this->assertSame($this->clientId, $this->credentials->getClientId()); } public function testGetApiKey() { $this->assertSame($this->apiKey, $this->credentials->getApiKey()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\SSHKeys; use DigitalOcean\Tests\TestCase; use DigitalOcean\SSHKeys\SSHKeys; use DigitalOcean\SSHKeys\SSHKeysActions; /** * @author <NAME> <<EMAIL>> */ class SSHKeysTest extends TestCase { protected $sshKeyId; protected $sshKeys; protected $sshKeysBuildQueryMethod; protected function setUp() { $this->sshKeyId = 123; $this->sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapter($this->never())); $this->sshKeysBuildQueryMethod = new \ReflectionMethod( $this->sshKeys, 'buildQuery' ); $this->sshKeysBuildQueryMethod->setAccessible(true); } /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/droplets/?client_id=foo&api_key=bar */ public function testProcessQuery() { $sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $sshKeys->getAll(); } public function testGetAllUrl() { $this->assertEquals( 'https://api.digitalocean.com/ssh_keys/?client_id=foo&api_key=bar', $this->sshKeysBuildQueryMethod->invoke($this->sshKeys) ); } public function testGetAll() { $response = <<<JSON {"status":"OK","ssh_keys":[{"id":10,"name":"office-imac"},{"id":11,"name":"macbook-air"}]} JSON ; $sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $sshKeys = $sshKeys->getAll(); $this->assertTrue(is_object($sshKeys)); $this->assertEquals('OK', $sshKeys->status); $this->assertCount(2, $sshKeys->ssh_keys); $key1 = $sshKeys->ssh_keys[0]; $this->assertSame(10, $key1->id); $this->assertSame('office-imac', $key1->name); $key2 = $sshKeys->ssh_keys[1]; $this->assertSame(11, $key2->id); $this->assertSame('macbook-air', $key2->name); } public function testShowUrl() { $this->assertEquals( 'https://api.digitalocean.com/ssh_keys/123/?client_id=foo&api_key=bar', $this->sshKeysBuildQueryMethod->invoke($this->sshKeys, $this->sshKeyId) ); } public function testShow() { $response = <<<JSON {"status":"OK","ssh_key":{"id":10,"name":"office-imac","ssh_pub_key":"ssh-dss <KEY>Ow== me@office-imac"}} JSON ; $sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $sshKey = $sshKeys->show($this->sshKeyId); $this->assertTrue(is_object($sshKey)); $this->assertEquals('OK', $sshKey->status); $this->assertSame(10, $sshKey->ssh_key->id); $this->assertSame('office-imac', $sshKey->ssh_key->name); $this->assertSame('ssh-dss AHJ<KEY> me@office-imac', $sshKey->ssh_key->ssh_pub_key); } public function testAddUrl() { $newSshKey = array( 'name' => 'office-imac', 'ssh_key_pub' => '<KEY>n+jSZflFD684gdLsW1+gjVoFBk0MZWuGSXEQyIwlBRq/8jAAAAFQDrxI/h35BewJUmVjid8Qk1NprMvQAAAIAspspAelh4bW5ncO5+CedFZPZn86ZCqk02NX3BTcMV4YI2IEzb6R2vzZkjCTuZVy6dcH3ag6JlEfju67euWT5yMnT1I0Ow== me@office-imac', ); $this->assertEquals( 'https://api.digitalocean.com/ssh_keys/new/?name=office-imac&ssh_key_pub=<KEY>%2<KEY>GmyL4%2F<KEY>y<KEY>4YqGiob48KzCT%2FNT6L6VoD5n%2BjSZvQAAAIAspspAelh4bW5ncO5%2BCedFZPZn86ZCqk02NX3BTcMV4YIaSCO43Y%2BghI2of4%2BE1TDJ1R9Znk9XJsald%2FU0u0uXwtyHXP2sommNWuAGtzp4QGmyL4%2Fsebg8Vnusytv93cA2PsXOxvbU0CdebDn0XUbbmVrAq4YqGiob48KzCT%2FNT6L6VoD5n%2BjSZflFD684gdLsW1%2BgjVoFBk0MZWuGSXEQyIwlBRq%2F8jAAAAFQDrxI%2Fh35BewJUmVjid8Qk1NprMvQAAAIAspspAelh4bW5ncO5%2BCedFZPZn86ZCqk02NX3BTcMV4YI2IEzb6R2vzZkjCTuZVy6dcH3ag6JlEfju67euWT5yMnT1I0Ow%3D%3D+me%40office-imac&client_id=foo&api_key=bar', $this->sshKeysBuildQueryMethod->invoke($this->sshKeys, null, SSHKeysActions::ACTION_ADD, $newSshKey) ); } public function testAdd() { $response = <<<JSON {"status":"OK","ssh_key":{"id":47,"name":"my_key","ssh_pub_key":"<KEY>QNcBekhmHp5Z0sHthXCm1XqnFbkRCdFlX02NpgtNs7Oc<KEY>Wt3fExrL2ZLX5XD2tiotugSkwZJMW5Bv0mtjr<KEY>ZjNNTag2c= user@host"}} JSON ; $sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $sshKey = $sshKeys->add(array('name' => 'foo', 'ssh_pub_key' => 'bar')); $this->assertTrue(is_object($sshKey)); $this->assertEquals('OK', $sshKey->status); $this->assertSame(47, $sshKey->ssh_key->id); $this->assertSame('my_key', $sshKey->ssh_key->name); $this->assertSame('ssh-dss A<KEY>//klu9hIkFAAQ/AZfGTw+696EjFBg4F5tN6MGMA6KrTQVLXeuYcZeRXwE5t5lwAAAIEAl2xYh098bozJUANQ82DiZznjHc5FW76Xm1apEqsZtVRFuh3V9nc7QNcBekhmHp5Z0sHthXCm1XqnFbkRCdFlX02NpgtNs7OcKpaJP47N8C+C/Yrf8qK/Wt3fExrL2ZLX5XD2tiotugSkwZJMW5Bv0mtjrNt0Q7P45rZjNNTag2c= user@host', $sshKey->ssh_key->ssh_pub_key); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the name of the SSH Key. */ public function testAddThrowsNameInvalidArgumentException() { $this->sshKeys->add(array()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the SSH key. */ public function testAddThrowsSSHKeyPubInvalidArgumentException() { $this->sshKeys->add(array('name' => 'my-new-ssh-key')); } public function testEditUrl() { $this->assertEquals( 'https://api.digitalocean.com/ssh_keys/123/?client_id=foo&api_key=bar', $this->sshKeysBuildQueryMethod->invoke($this->sshKeys, $this->sshKeyId) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the new public SSH Key. */ public function testEditThrowsSSHKeyPubInvalidArgumentException() { $this->sshKeys->edit($this->sshKeyId, array()); } public function testEdit() { $response = <<<JSON {"status":"OK","ssh_key":{"id":47,"name":"new_ssh_pub_key","ssh_pub_key":"<KEY>= user@host"}} JSON ; $sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $sshKey = $sshKeys->edit($this->sshKeyId, array('ssh_pub_key' => 'new_ssh_pub_key')); $this->assertTrue(is_object($sshKey)); $this->assertEquals('OK', $sshKey->status); $this->assertSame(47, $sshKey->ssh_key->id); $this->assertSame('new_ssh_pub_key', $sshKey->ssh_key->name); $this->assertSame('ssh-dss AAAAB3NzaC1kc3MAAACBAK5uLwicCrFEpaVKBzkWxC7RQn+smg5ZQb5keh9RQKo8AszFTol5npgUAr0JWmqKIH<KEY> user@host', $sshKey->ssh_key->ssh_pub_key); } public function testDestroyUrl() { $this->assertEquals( 'https://api.digitalocean.com/ssh_keys/123/destroy/?client_id=foo&api_key=bar', $this->sshKeysBuildQueryMethod->invoke($this->sshKeys, $this->sshKeyId, SSHKeysActions::ACTION_DESTROY) ); } public function testDestroy() { $response = <<<JSON {"status":"OK"} JSON ; $sshKeys = new SSHKeys($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $destroy = $sshKeys->destroy($this->sshKeyId); $this->assertTrue(is_object($destroy)); $this->assertEquals('OK', $destroy->status); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Command; /** * @author <NAME> <<EMAIL>> */ class CommandTest extends TestCase { protected $distFile; protected $command; protected function setUp() { $this->distFile = 'credentials.yml.dist'; $this->command = new Command('foo'); } public function testGetDigitalOcean() { $digitalOcean = $this->command->getDigitalOcean($this->distFile); $this->assertTrue(is_object($digitalOcean)); $this->assertInstanceOf('\\DigitalOcean\\DigitalOcean', $digitalOcean); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Impossible to get credentials informations in ./foo/bar */ public function testGetDigitalOceanThrowsRuntimeException() { $this->command->getDigitalOcean('./foo/bar'); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\Droplets; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Droplets\ShowAllActiveCommand; /** * @author <NAME> <<EMAIL>> */ class ShowAllActiveCommandTest extends TestCase { protected $application; protected $command; protected $commandTester; protected function setUp() { $this->application = new Application(); $result = (object) array( 'droplets' => array( (object) array( 'id' => 123, 'name' => 'foo', 'image_id' => 98, 'size_id' => 76, 'region_id' => 54, 'backups_active' => 1, 'ip_address' => '127.0.0.1', 'private_ip_address' => null, 'status' => 'active', 'locked' => false, 'created_at' => '2013-01-01T09:30:00Z', ), (object) array( 'id' => 456, 'name' => 'bar', 'image_id' => 34, 'size_id' => 56, 'region_id' => 78, 'backups_active' => 0, 'ip_address' => '127.0.0.1', 'private_ip_address' => '127.0.0.1', 'status' => 'active', 'locked' => false, 'created_at' => '2013-01-01T09:30:00Z', ), ) ); $ShowAllActiveCommand = $this->getMock('\DigitalOcean\CLI\Droplets\ShowAllActiveCommand', array('getDigitalOcean')); $ShowAllActiveCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('droplets', $this->getMockDroplets('showAllActive', $result)))); $this->application->add($ShowAllActiveCommand); $this->command = $this->application->find('droplets:show-all-active'); $this->commandTester = new CommandTester($this->command); } public function testExecuteFirstDroplet() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertRegExp('/\| 123 \| foo \| 98 \| 76 \| 54 \| 1 \| 127\.0\.0\.1 \| \| active \| \| 2013\-01\-01T09\:30\:00Z \|/', $this->commandTester->getDisplay()); } public function testExecuteSecondDroplet() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertRegExp('/\| 456 \| bar \| 34 \| 56 \| 78 \| 0 \| 127\.0\.0\.1 \| 127\.0\.0\.1 \| active \| \| 2013\-01\-01T09\:30:00Z \|/', $this->commandTester->getDisplay()); } public function testReturnsNoDroplets() { $result = (object) array( 'droplets' => array() ); $ShowAllActiveCommand = $this->getMock('\DigitalOcean\CLI\Droplets\ShowAllActiveCommand', array('getDigitalOcean')); $ShowAllActiveCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('droplets', $this->getMockDroplets('showAllActive', $result)))); $this->application->add($ShowAllActiveCommand); $this->command = $this->application->find('droplets:show-all-active'); $this->commandTester = new CommandTester($this->command); $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $expected = <<<EOT +----+------+----------+---------+-----------+----------------+------------+--------------------+--------+--------+------------+ | ID | Name | Image ID | Size ID | Region ID | Backups Active | IP Address | Private IP Address | Status | Locked | Created At | +----+------+----------+---------+-----------+----------------+------------+--------------------+--------+--------+------------+ EOT ; $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertTrue($expected === $this->commandTester->getDisplay()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests; /** * @author <NAME> <<EMAIL>> */ class TestCase extends \PHPUnit_Framework_TestCase { /** * @return HttpAdapterInterface */ protected function getMockAdapter($expects = null) { if (null === $expects) { $expects = $this->once(); } $mock = $this->getMock('\HttpAdapter\HttpAdapterInterface'); $mock ->expects($expects) ->method('getContent') ->will($this->returnArgument(0)); return $mock; } /** * @return HttpAdapterInterface */ protected function getMockAdapterReturns($returnValue) { $mock = $this->getMock('\HttpAdapter\HttpAdapterInterface'); $mock ->expects($this->once()) ->method('getContent') ->will($this->returnValue($returnValue)); return $mock; } /** * @return Crendentials */ protected function getMockCredentials($expects = null) { if (null === $expects) { $expects = $this->atLeastOnce(); } $mock = $this ->getMockBuilder('\DigitalOcean\Credentials') ->disableOriginalConstructor() ->getMock(); $mock ->expects($expects) ->method('getClientId') ->will($this->returnValue('foo')); $mock ->expects($expects) ->method('getApiKey') ->will($this->returnValue('bar')); return $mock; } /** * @return DigitalOcean */ protected function getMockDigitalOcean($method, $returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\DigitalOcean') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->any()) ->method($method) ->will($this->returnValue($returnValue)); return $mock; } /** * @return Droplets */ protected function getMockDroplets($method, $returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\Droplets\Droplets') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->any()) ->method($method) ->will($this->returnValue($returnValue)); return $mock; } /** * @return Images */ protected function getMockImages($method, $returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\Images\Images') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->any()) ->method($method) ->will($this->returnValue($returnValue)); return $mock; } /** * @return Regions */ protected function getMockRegions($returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\Regions\Regions') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->once()) ->method('getAll') ->will($this->returnValue($returnValue)); return $mock; } /** * @return Sizes */ protected function getMockSizes($returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\Sizes\Sizes') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->once()) ->method('getAll') ->will($this->returnValue($returnValue)); return $mock; } /** * @return SSHKeys */ protected function getMockSSHKeys($method, $returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\SSHKeys\SSHKeys') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->any()) ->method($method) ->will($this->returnValue($returnValue)); return $mock; } /** * @return Domains */ protected function getMockDomains($method, $returnValue) { $mock = $this->getMockBuilder('\DigitalOcean\Domains\Domains') ->disableOriginalConstructor() ->getMock(); $mock ->expects($this->any()) ->method($method) ->will($this->returnValue($returnValue)); return $mock; } /** * @return DialogHelper */ protected function getDialogAskConfirmation($returnValue) { $mock = $this->getMock('\Symfony\Component\Console\Helper\DialogHelper', array('askConfirmation')); $mock ->expects($this->at(0)) ->method('askConfirmation') ->will($this->returnValue($returnValue)); return $mock; } /** * @return DialogHelper */ protected function getDialogAsk($returnValue) { $mock = $this->getMock('\Symfony\Component\Console\Helper\DialogHelper', array('ask')); $mock ->expects($this->once()) ->method('ask') ->will($this->returnValue($returnValue)); return $mock; } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\Droplets; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Droplets\ShowCommand; /** * @author <NAME> <<EMAIL>> */ class ShowCommandTest extends TestCase { protected $application; protected $command; protected $commandTester; protected function setUp() { $this->application = new Application(); $result = (object) array( 'droplet' => (object) array( 'id' => 123, 'name' => 'foo', 'image_id' => 98, 'size_id' => 76, 'region_id' => 54, 'backups_active' => 1, 'ip_address' => '127.0.0.1', 'private_ip_address' => null, 'status' => 'active', 'locked' => false, 'created_at' => '2013-01-01T09:30:00Z', 'backups' => array(0, 1, 2, 3, 4, 5, 6), 'snapshots' => array(0), ) ); $ShowCommand = $this->getMock('\DigitalOcean\CLI\Droplets\ShowCommand', array('getDigitalOcean')); $ShowCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('droplets', $this->getMockDroplets('show', $result)))); $this->application->add($ShowCommand); $this->command = $this->application->find('droplets:show'); $this->commandTester = new CommandTester($this->command); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not enough arguments. */ public function testExecuteNotEnoughArguments() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); } public function testExecute() { $this->commandTester->execute(array( 'command' => $this->command->getName(), 'id' => 123, )); $expected = <<<EOT +-----+------+----------+---------+-----------+----------------+---------+-----------+------------+--------------------+--------+--------+----------------------+ | ID | Name | Image ID | Size ID | Region ID | Backups Active | Backups | Snapshots | IP Address | Private IP Address | Status | Locked | Created At | +-----+------+----------+---------+-----------+----------------+---------+-----------+------------+--------------------+--------+--------+----------------------+ | 123 | foo | 98 | 76 | 54 | 1 | 7 | 1 | 127.0.0.1 | | active | | 2013-01-01T09:30:00Z | +-----+------+----------+---------+-----------+----------------+---------+-----------+------------+--------------------+--------+--------+----------------------+ EOT ; $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertSame($expected, $this->commandTester->getDisplay()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\SSHKeys; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\SSHKeys\GetAllCommand; /** * @author <NAME> <<EMAIL>> */ class GetAllCommandTest extends TestCase { protected $application; protected $command; protected $commandTester; protected function setUp() { $this->application = new Application(); $result = (object) array( 'ssh_keys' => array( (object) array('id' => 123, 'name' => 'office-imac'), (object) array('id' => 456, 'name' => 'macbook-pro'), ) ); $GetAllCommand = $this->getMock('\DigitalOcean\CLI\SSHKeys\GetAllCommand', array('getDigitalOcean')); $GetAllCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('sshkeys', $this->getMockSSHKeys('getAll', $result)))); $this->application->add($GetAllCommand); $this->command = $this->application->find('ssh-keys:all'); $this->commandTester = new CommandTester($this->command); } public function testExecuteFirstSshKey() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertRegExp('/\| 123 \| office\-imac \|/', $this->commandTester->getDisplay()); } public function testExecuteSecondSshKey() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertRegExp('/\| 456 \| macbook\-pro \|/', $this->commandTester->getDisplay()); } public function testReturnsNoKeys() { $result = (object) array( 'ssh_keys' => array() ); $GetAllCommand = $this->getMock('\DigitalOcean\CLI\SSHKeys\GetAllCommand', array('getDigitalOcean')); $GetAllCommand ->expects($this->any()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('sshkeys', $this->getMockSSHKeys('getAll', $result)))); $this->application->add($GetAllCommand); $this->command = $this->application->find('ssh-keys:all'); $this->commandTester = new CommandTester($this->command); $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $expected = <<<EOT +----+------+ | ID | Name | +----+------+ EOT ; $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertTrue($expected === $this->commandTester->getDisplay()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\Droplets; use DigitalOcean\Tests\TestCase; use DigitalOcean\Droplets\Droplets; use DigitalOcean\Droplets\DropletsActions; /** * @author <NAME> <<EMAIL>> */ class DropletsTest extends TestCase { protected $dropletId; protected $droplets; protected $dropletBuildQueryMethod; protected function setUp() { $this->dropletId = 123; $this->droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapter($this->never())); $this->dropletBuildQueryMethod = new \ReflectionMethod( $this->droplets, 'buildQuery' ); $this->dropletBuildQueryMethod->setAccessible(true); } /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/droplets/?client_id=foo&api_key=bar */ public function testProcessQuery() { $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $droplets->showAllActive(); } public function testShowAllActiveUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke($this->droplets) ); } public function testShowAllActive() { $response = <<<JSON {"status":"OK","droplets":[{"backups_active":null,"id":123,"image_id":420,"name":"test123","region_id":1,"size_id":33,"status":"active","ip_address":"127.0.0.1","locked":false,"created_at":"2013-01-01T09:30:00Z"},{"backups_active":1,"id":456,"image_id":420,"name":"test456","region_id":1,"size_id":33,"status":"active","ip_address":"127.0.0.1","locked":false,"created_at":"2013-01-01T09:30:00Z"}]} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplets = $droplets->showAllActive(); $this->assertTrue(is_object($droplets)); $this->assertEquals('OK', $droplets->status); $this->assertCount(2, $droplets->droplets); $droplet1 = $droplets->droplets[0]; $this->assertNull($droplet1->backups_active); $this->assertSame(123, $droplet1->id); $this->assertSame(420, $droplet1->image_id); $this->assertSame('test123', $droplet1->name); $this->assertSame(1, $droplet1->region_id); $this->assertSame(33, $droplet1->size_id); $this->assertSame('active', $droplet1->status); $this->assertSame('127.0.0.1', $droplet1->ip_address); $this->assertSame(false, $droplet1->locked); $this->assertSame('2013-01-01T09:30:00Z', $droplet1->created_at); $droplet1 = $droplets->droplets[1]; $this->assertSame(1, $droplet1->backups_active); $this->assertSame(456, $droplet1->id); $this->assertSame(420, $droplet1->image_id); $this->assertSame('test456', $droplet1->name); $this->assertSame(1, $droplet1->region_id); $this->assertSame(33, $droplet1->size_id); $this->assertSame('active', $droplet1->status); $this->assertSame('127.0.0.1', $droplet1->ip_address); $this->assertSame(false, $droplet1->locked); $this->assertSame('2013-01-01T09:30:00Z', $droplet1->created_at); } public function testShowAllActiveWithCredentials() { if (!isset($_SERVER['CLIENT_ID']) || !isset($_SERVER['API_KEY'])) { $this->markTestSkipped('You need to configure the CLIENT_ID and API_KEY values in phpunit.xml'); } $droplets = new Droplets( new \DigitalOcean\Credentials($_SERVER['CLIENT_ID'], $_SERVER['API_KEY']), new \HttpAdapter\CurlHttpAdapter() ); $droplets = $droplets->showAllActive(); $this->assertTrue(is_object($droplets)); $this->assertEquals('OK', $droplets->status); $this->assertCount(count($droplets->droplets), $droplets->droplets); $firstDroplet = $droplets->droplets[0]; $this->assertObjectHasAttribute('id', $firstDroplet); $this->assertObjectHasAttribute('name', $firstDroplet); $this->assertObjectHasAttribute('image_id', $firstDroplet); $this->assertObjectHasAttribute('size_id', $firstDroplet); $this->assertObjectHasAttribute('region_id', $firstDroplet); $this->assertObjectHasAttribute('backups_active', $firstDroplet); $this->assertObjectHasAttribute('ip_address', $firstDroplet); $this->assertObjectHasAttribute('status', $firstDroplet); } public function testShowUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke($this->droplets, $this->dropletId) ); } public function testShow() { $response = <<<JSON {"status":"OK","droplets":[{"backups_active":1,"id":123,"image_id":420,"name":"test123","region_id":1,"size_id":33,"status":"active","ip_address":"127.0.0.1"}]} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->show($this->dropletId)->droplets[0]; $this->assertSame(1, $droplet->backups_active); $this->assertSame($this->dropletId, $droplet->id); $this->assertSame(420, $droplet->image_id); $this->assertSame('test123', $droplet->name); $this->assertSame(1, $droplet->region_id); $this->assertSame(33, $droplet->size_id); $this->assertSame('active', $droplet->status); $this->assertSame('127.0.0.1', $droplet->ip_address); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not Found: https://api.digitalocean.com/droplets/123/?client_id=foo&api_key=bar */ public function testShowThrowsRuntimeException() { $response = <<<JSON {"status":"ERROR","message":"Not Found"} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplets->show($this->dropletId); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not Droplets Found: https://api.digitalocean.com/droplets/123/?client_id=foo&api_key=bar */ public function testShowThrowsRuntimeExceptionWithOldErrorResponse() { $response = <<<JSON {"status":"ERROR","error_message":"Not Droplets Found"} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplets->show($this->dropletId); } public function testCreateUrl() { $newDroplet = array( 'name' => 'MyNewDroplet', 'size_id' => 111, 'image_id' => 222, 'region_id' => 333, 'ssh_key_ids' => 'MySshKeyId1,MySshKeyId2', ); $this->assertEquals( 'https://api.digitalocean.com/droplets/new/?name=MyNewDroplet&size_id=111&image_id=222&region_id=333&ssh_key_ids=MySshKeyId1%2CMySshKeyId2&client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke($this->droplets, null, DropletsActions::ACTION_NEW, $newDroplet) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage A new droplet must have a string "name". */ public function testCreateThrowsNameInvalidArgumentException() { $this->droplets->create(array()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage A new droplet must have an integer "size_id". */ public function testCreateThrowsSizeIdInvalidArgumentException() { $this->droplets->create(array( 'name' => 'MyNewDroplet', )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage A new droplet must have an integer "image_id". */ public function testCreateThrowsImageIdInvalidArgumentException() { $this->droplets->create(array( 'name' => 'MyNewDroplet', 'size_id' => 123, )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage A new droplet must have an integer "region_id". */ public function testCreateThrowsRegionIdInvalidArgumentException() { $this->droplets->create(array( 'name' => 'MyNewDroplet', 'size_id' => 123, 'image_id' => 456, )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide an list of "ssh_key_ids" comma separeted. */ public function testCreateThrowsSshKeyIdsInvalidArgumentException() { $this->droplets->create(array( 'name' => 'MyNewDroplet', 'size_id' => 123, 'image_id' => 456, 'region_id' => 789, 'ssh_key_ids' => array(), )); } public function testCreate() { $response = <<<JSON {"status":"OK","droplet":{"id":100824,"name":"MyNewDroplet","image_id":222,"size_id":111,"region_id":333,"event_id":7499}} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $createdDroplet = $droplets->create(array( 'name' => 'MyNewDroplet', 'size_id' => 111, 'image_id' => 222, 'region_id' => 333, )); $this->assertTrue(is_object($createdDroplet)); $this->assertEquals('OK', $createdDroplet->status); $createdDroplet = $createdDroplet->droplet; $this->assertSame(100824, $createdDroplet->id); $this->assertSame('MyNewDroplet', $createdDroplet->name); $this->assertSame(111, $createdDroplet->size_id); $this->assertSame(222, $createdDroplet->image_id); $this->assertSame(333, $createdDroplet->region_id); $this->assertSame(7499, $createdDroplet->event_id); } public function testRebootUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/reboot/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_REBOOT ) ); } public function testReboot() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->reboot($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testPowerCycleUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/power_cycle/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_POWER_CYCLE ) ); } public function testPowerCycle() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->powerCycle($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testShutdownUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/shutdown/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_SHUTDOWN ) ); } public function testShutdown() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->shutdown($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testPowerOnUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/power_on/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_POWER_ON ) ); } public function testPowerOn() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->powerOn($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testPowerOffUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/power_off/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_POWER_OFF ) ); } public function testPowerOff() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->powerOff($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testResetRootPasswordUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/password_reset/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_RESET_ROOT_PASSWORD ) ); } public function testResetRootPassword() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->resetRootPassword($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testResizeUrl() { $newSize = array( 'size_id' => 111, ); $this->assertEquals( 'https://api.digitalocean.com/droplets/123/resize/?size_id=111&client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_RESIZE, $newSize ) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide an integer "size_id". */ public function testResizeThrowsSizeIdInvalidArgumentException() { $this->droplets->resize($this->dropletId, array()); } public function testResize() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->resize($this->dropletId, array('size_id' => 123)); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testSnapshotUrlWithoutName() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/snapshot/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_SNAPSHOT ) ); } public function testSnapshotUrlWithName() { $newSnapshot = array( 'name' => 'MySnapshotName' ); $this->assertEquals( 'https://api.digitalocean.com/droplets/123/snapshot/?name=MySnapshotName&client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_SNAPSHOT, $newSnapshot ) ); } public function testSnapshot() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->snapshot($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testRestoreUrl() { $imageToRestore = array( 'image_id' => 1111, ); $this->assertEquals( 'https://api.digitalocean.com/droplets/123/restore/?image_id=1111&client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_RESTORE, $imageToRestore ) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the "image_id" to restore. */ public function testRestoreUrlThrowsSizeIdInvalidArgumentException() { $this->droplets->restore($this->dropletId, array()); } public function testRestore() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->restore($this->dropletId, array('image_id' => 1111)); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testRebuildUrl() { $imageToRebuild = array( 'image_id' => 1111, ); $this->assertEquals( 'https://api.digitalocean.com/droplets/123/rebuild/?image_id=1111&client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_REBUILD, $imageToRebuild ) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the "image_id" to rebuild. */ public function testRebuildThrowsSizeIdInvalidArgumentException() { $this->droplets->rebuild($this->dropletId, array()); } public function testRebuild() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->rebuild($this->dropletId, array('image_id' => 1111)); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } public function testRenameUrl() { $newName = array( 'name' => 'foobar', ); $this->assertEquals( 'https://api.digitalocean.com/droplets/123/rename/?name=foobar&client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_RENAME, $newName ) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide a string "name". */ public function testRenameThrowsNameInvalidArgumentException() { $this->droplets->rename($this->dropletId, array()); } public function testRename() { $response = <<<JSON {"status":"OK","event_id":4435823} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->rename($this->dropletId, array('name' => 'foobar')); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(4435823, $droplet->event_id); } public function testDestroyUrl() { $this->assertEquals( 'https://api.digitalocean.com/droplets/123/destroy/?client_id=foo&api_key=bar', $this->dropletBuildQueryMethod->invoke( $this->droplets, $this->dropletId, DropletsActions::ACTION_DESTROY ) ); } public function testDestroy() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $droplets = new Droplets($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $droplet = $droplets->destroy($this->dropletId); $this->assertTrue(is_object($droplet)); $this->assertEquals('OK', $droplet->status); $this->assertSame(7501, $droplet->event_id); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\Domains; use DigitalOcean\Tests\TestCase; use DigitalOcean\Domains\Domains; use DigitalOcean\Domains\DomainsActions; use DigitalOcean\Domains\RecordsActions; /** * @author <NAME> <<EMAIL>> */ class DomainsTest extends TestCase { protected $domainId; protected $domainName; protected $recordId; protected $domains; protected $domainsBuildQueryMethod; protected function setUp() { $this->domainId = 123; $this->domainName = 'foo.org'; $this->recordId = 456; $this->domains = new Domains($this->getMockCredentials(), $this->getMockAdapter($this->never())); $this->domainsBuildQueryMethod = new \ReflectionMethod( $this->domains, 'buildQuery' ); $this->domainsBuildQueryMethod->setAccessible(true); $this->recordsBuildQueryMethod = new \ReflectionMethod( $this->domains, 'buildRecordsQuery' ); $this->recordsBuildQueryMethod->setAccessible(true); } /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/domains/?client_id=foo&api_key=bar */ public function testProcessQuery() { $sshKeys = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $sshKeys->getAll(); } public function testGetAllUrl() { $this->assertEquals( 'https://api.digitalocean.com/domains/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains) ); } public function testGetAllReturnsNoDomains() { $response = <<<JSON {"status":"OK","domains":[]} JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $domains = $domains->getAll(); $this->assertTrue(is_object($domains)); $this->assertEquals('OK', $domains->status); $this->assertEmpty($domains->domains); } public function testGetAll() { $response = <<<'JSON' { "status": "OK", "domains": [ { "id": 100, "name": "example.com", "ttl": 1800, "live_zone_file": "$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.example.com. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n", "error": null, "zone_file_with_error": null } ] } JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $domains = $domains->getAll(); $this->assertTrue(is_object($domains)); $this->assertEquals('OK', $domains->status); $this->assertTrue(is_array($domains->domains)); $domains = $domains->domains[0]; $this->assertTrue(is_object($domains)); $this->assertSame(100, $domains->id); $this->assertSame('example.com', $domains->name); $this->assertSame(1800, $domains->ttl); $this->assertSame('$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.example.com. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n', $domains->live_zone_file); $this->assertNull($domains->error); $this->assertNull($domains->zone_file_with_error); } public function testShowUrlWithDomainId() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, $this->domainId) ); } public function testShowUrlWithDomainName() { $this->assertEquals( 'https://api.digitalocean.com/domains/foo.org/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, $this->domainName) ); } public function testShow() { $response = <<<'JSON' { "status": "OK", "domain": { "id": 100, "name": "example.com", "ttl": 1800, "live_zone_file": "$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.example.com. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n", "error": null, "zone_file_with_error": null } } JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $domain = $domains->show($this->domainId); $this->assertTrue(is_object($domain)); $this->assertEquals('OK', $domain->status); $domain = $domain->domain; $this->assertTrue(is_object($domain)); $this->assertSame(100, $domain->id); $this->assertSame('example.com', $domain->name); $this->assertSame(1800, $domain->ttl); $this->assertSame('$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.example.com. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n', $domain->live_zone_file); $this->assertNull($domain->error); $this->assertNull($domain->zone_file_with_error); } public function testAddUrl() { $newDomain = array( 'name' => 'bar.org', 'ip_address' => '127.0.0.1', ); $this->assertEquals( 'https://api.digitalocean.com/domains/new/?name=bar.org&ip_address=127.0.0.1&client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, null, DomainsActions::ACTION_ADD, $newDomain) ); } public function testAdd() { $response = <<<JSON { "status": "OK", "domain": { "id": 101, "name": "newdomain.com" } } JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $domains = $domains->add(array('name' => 'newdomain.com', 'ip_address' => '127.0.0.1')); $this->assertTrue(is_object($domains)); $this->assertEquals('OK', $domains->status); $this->assertTrue(is_object($domains->domain)); $this->assertSame(101, $domains->domain->id); $this->assertSame('newdomain.com', $domains->domain->name); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the name of the domain. */ public function testAddThrowsNameInvalidArgumentException() { $this->domains->add(array()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the IP address for the domain's initial A record. */ public function testAddThrowsIpAddressInvalidArgumentException() { $this->domains->add(array('name' => 'bar.org')); } public function testDestroyUrlWithDomainId() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/destroy/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, $this->domainId, DomainsActions::ACTION_DESTROY) ); } public function testDestroyUrlWithDomainName() { $this->assertEquals( 'https://api.digitalocean.com/domains/foo.org/destroy/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, $this->domainName, DomainsActions::ACTION_DESTROY) ); } public function testDestroy() { $response = <<<JSON {"status":"OK"} JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $destroy = $domains->destroy($this->domainId); $this->assertTrue(is_object($destroy)); $this->assertEquals('OK', $destroy->status); } public function testGetRecordsUrlWithDomaineId() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/records/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, $this->domainId, DomainsActions::ACTION_RECORDS) ); } public function testGetRecordsUrlWithDomaineName() { $this->assertEquals( 'https://api.digitalocean.com/domains/foo.org/records/?client_id=foo&api_key=bar', $this->domainsBuildQueryMethod->invoke($this->domains, $this->domainName, DomainsActions::ACTION_RECORDS) ); } public function testGetRecords() { $response = <<<JSON { "status": "OK", "records": [ { "id": 49, "domain_id": "100", "record_type": "A", "name": "example.com", "data": "8.8.8.8", "priority": null, "port": null, "weight": null }, { "id": 50, "domain_id": "100", "record_type": "CNAME", "name": "www", "data": "@", "priority": null, "port": null, "weight": null } ] } JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $records = $domains->getRecords($this->domainId); $this->assertTrue(is_object($records)); $this->assertEquals('OK', $records->status); $this->assertTrue(is_array($records->records)); $record1 = $records->records[0]; $this->assertTrue(is_object($record1)); $this->assertSame(49, $record1->id); $this->assertSame('100', $record1->domain_id); $this->assertSame('A', $record1->record_type); $this->assertSame('example.com', $record1->name); $this->assertSame('8.8.8.8', $record1->data); $this->assertNull($record1->priority); $this->assertNull($record1->port); $this->assertNull($record1->weight); $record2 = $records->records[1]; $this->assertSame(50, $record2->id); $this->assertSame('100', $record2->domain_id); $this->assertSame('CNAME', $record2->record_type); $this->assertSame('www', $record2->name); $this->assertSame('@', $record2->data); $this->assertNull($record2->priority); $this->assertNull($record2->port); $this->assertNull($record2->weight); } public function testNewRecordUrlWithDomaineId() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/records/new/?client_id=foo&api_key=bar', $this->recordsBuildQueryMethod->invoke($this->domains, $this->domainId, RecordsActions::ACTION_ADD) ); } public function testNewRecordUrlWithDomaineName() { $this->assertEquals( 'https://api.digitalocean.com/domains/foo.org/records/new/?client_id=foo&api_key=bar', $this->recordsBuildQueryMethod->invoke($this->domains, $this->domainName, RecordsActions::ACTION_ADD) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the record_type. */ public function testNewRecordWithEmptyArray() { $this->domains->newRecord($this->domainId, array()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The record_type can only be A, CNAME, NS, TXT, MX or SRV */ public function testNewRecordWithWrongRecordTypeValueType() { $this->domains->newRecord($this->domainId, array( 'record_type' => null, )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the data value of the record. */ public function testNewRecordWithCorrectRecordTypeValue() { $this->domains->newRecord($this->domainId, array( 'record_type' => 'A', )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the data value of the record. */ public function testNewRecordWithWrongDataAndWrongDataType() { $this->domains->newRecord($this->domainId, array( 'record_type' => 'A', 'data' => null )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the name string if the record_type is A, CNAME, TXT or SRV. */ public function testNewRecordTypeAWithoutNameString() { $this->domains->newRecord($this->domainId, array( 'record_type' => 'A', 'data' => 'data', )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the priority integer if the record_type is SRV or MX. */ public function testNewRecordTypeSRVWithoutPriorityNumber() { $this->domains->newRecord($this->domainId, array( 'record_type' => 'SRV', 'data' => 'data', 'name' => 'foo', )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the port integer if the record_type is SRV. */ public function testNewRecordTypeSRVWithoutPortNumber() { $this->domains->newRecord($this->domainId, array( 'record_type' => 'SRV', 'data' => 'data', 'name' => 'foo', 'priority' => 1, )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide the weight integer if the record_type is SRV. */ public function testNewRecordTypeSRVWithoutWeightNumber() { $this->domains->newRecord($this->domainId, array( 'record_type' => 'SRV', 'data' => 'data', 'name' => 'foo', 'priority' => 1, 'port' => 2, )); } public function testNewRecordTypeA() { $response = <<<JSON {"status":"OK","domain_record":{"id": 51,"domain_id":"100","record_type":"A","name":"foo","data":"data","priority":null,"port":null,"weight":null}} JSON ; $parameters = array( 'record_type' => 'A', 'data' => 'data', 'name' => 'foo', ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $newRecord = $domains->newRecord($this->domainId, $parameters); $this->assertTrue(is_object($newRecord)); $this->assertEquals('OK', $newRecord->status); $record = $newRecord->domain_record; $this->assertTrue(is_object($record)); $this->assertSame(51, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('A', $record->record_type); $this->assertSame('foo', $record->name); $this->assertSame('data', $record->data); $this->assertNull($record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } public function testNewRecordTypeCNAME() { $response = <<<JSON {"status":"OK","domain_record":{"id": 52,"domain_id":"100","record_type":"CNAME","name":"foo","data":"data","priority":null,"port":null,"weight":null}} JSON ; $parameters = array( 'record_type' => 'CNAME', 'data' => 'data', 'name' => 'foo', ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $newRecord = $domains->newRecord($this->domainId, $parameters); $this->assertTrue(is_object($newRecord)); $this->assertEquals('OK', $newRecord->status); $record = $newRecord->domain_record; $this->assertTrue(is_object($record)); $this->assertSame(52, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('CNAME', $record->record_type); $this->assertSame('foo', $record->name); $this->assertSame('data', $record->data); $this->assertNull($record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } public function testNewRecordTypeNS() { $response = <<<JSON {"status":"OK","domain_record":{"id": 53,"domain_id":"100","record_type":"NS","name":"bar","data":"data","priority":null,"port":null,"weight":null}} JSON ; $parameters = array( 'record_type' => 'NS', 'data' => 'data', ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $newRecord = $domains->newRecord($this->domainId, $parameters); $this->assertTrue(is_object($newRecord)); $this->assertEquals('OK', $newRecord->status); $record = $newRecord->domain_record; $this->assertTrue(is_object($record)); $this->assertSame(53, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('NS', $record->record_type); $this->assertSame('bar', $record->name); $this->assertSame('data', $record->data); $this->assertNull($record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } public function testNewRecordTypeTXT() { $response = <<<JSON {"status":"OK","domain_record":{"id": 54,"domain_id":"100","record_type":"TXT","name":"foo","data":"data","priority":null,"port":null,"weight":null}} JSON ; $parameters = array( 'record_type' => 'TXT', 'data' => 'data', 'name' => 'foo' ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $newRecord = $domains->newRecord($this->domainId, $parameters); $this->assertTrue(is_object($newRecord)); $this->assertEquals('OK', $newRecord->status); $record = $newRecord->domain_record; $this->assertTrue(is_object($record)); $this->assertSame(54, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('TXT', $record->record_type); $this->assertSame('foo', $record->name); $this->assertSame('data', $record->data); $this->assertNull($record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } public function testNewRecordTypeMX() { $response = <<<JSON {"status":"OK","domain_record":{"id": 55,"domain_id":"100","record_type":"MX","name":"baz","data":"data","priority":1,"port":null,"weight":null}} JSON ; $parameters = array( 'record_type' => 'MX', 'data' => 'data', 'priority' => 1, ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $newRecord = $domains->newRecord($this->domainId, $parameters); $this->assertTrue(is_object($newRecord)); $this->assertEquals('OK', $newRecord->status); $record = $newRecord->domain_record; $this->assertTrue(is_object($record)); $this->assertSame(55, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('MX', $record->record_type); $this->assertSame('baz', $record->name); $this->assertSame('data', $record->data); $this->assertSame(1, $record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } public function testNewRecordTypeSRV() { $response = <<<JSON {"status":"OK","domain_record":{"id": 56,"domain_id":"100","record_type":"SRV","name":"foo","data":"data","priority":1,"port":88,"weight":2}} JSON ; $parameters = array( 'record_type' => 'SRV', 'data' => 'data', 'name' => 'foo', 'priority' => 1, 'port' => 88, 'weight' => 2, ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $newRecord = $domains->newRecord($this->domainId, $parameters); $this->assertTrue(is_object($newRecord)); $this->assertEquals('OK', $newRecord->status); $record = $newRecord->domain_record; $this->assertTrue(is_object($record)); $this->assertSame(56, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('SRV', $record->record_type); $this->assertSame('foo', $record->name); $this->assertSame('data', $record->data); $this->assertSame(1, $record->priority); $this->assertSame(88, $record->port); $this->assertSame(2, $record->weight); } public function testGetRecordUrl() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/records/456/?client_id=foo&api_key=bar', $this->recordsBuildQueryMethod->invoke($this->domains, $this->domainId, $this->recordId) ); } public function testGetRecord() { $response = <<<JSON {"status":"OK","record":{"id":456,"domain_id":"123","record_type":"CNAME","name":"www","data":"@","priority":null,"port":null,"weight":null}} JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $record = $domains->getRecord($this->domainId, $this->recordId); $this->assertTrue(is_object($record)); $this->assertEquals('OK', $record->status); $record = $record->record; $this->assertTrue(is_object($record)); $this->assertSame(456, $record->id); $this->assertSame('123', $record->domain_id); $this->assertSame('CNAME', $record->record_type); $this->assertSame('www', $record->name); $this->assertSame('@', $record->data); $this->assertNull($record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } public function testEditRecordUrl() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/records/456/edit/?client_id=foo&api_key=bar', $this->recordsBuildQueryMethod->invoke($this->domains, $this->domainId, $this->recordId, RecordsActions::ACTION_EDIT) ); } public function testEditRecord() { $response = <<<JSON {"status":"OK","record":{"id":50,"domain_id":"100","record_type":"CNAME","name":"www2","data":"@","priority":null,"port":null,"weight":null}} JSON ; $parameters = array( 'record_type' => 'CNAME', 'data' => '@', 'name' => 'www2' ); $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $editedRecord = $domains->editRecord($this->domainId, $this->recordId, $parameters); $this->assertTrue(is_object($editedRecord)); $this->assertEquals('OK', $editedRecord->status); $record = $editedRecord->record; $this->assertTrue(is_object($record)); $this->assertSame(50, $record->id); $this->assertSame('100', $record->domain_id); $this->assertSame('CNAME', $record->record_type); $this->assertSame('www2', $record->name); $this->assertSame('@', $record->data); $this->assertNull($record->priority); $this->assertNull($record->port); $this->assertNull($record->weight); } // testEditRecord* are close to testNewRecord* because we use the protected method // Domains::checkParameters in both Domains::newRecord and Domains::editRecord. public function testDestroyRecordUrl() { $this->assertEquals( 'https://api.digitalocean.com/domains/123/records/456/destroy/?client_id=foo&api_key=bar', $this->recordsBuildQueryMethod->invoke($this->domains, $this->domainId, $this->recordId, RecordsActions::ACTION_DESTROY) ); } public function testDestroyRecord() { $response = <<<JSON {"status":"OK"} JSON ; $domains = new Domains($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $destroy = $domains->destroyRecord($this->domainId, $this->recordId); $this->assertTrue(is_object($destroy)); $this->assertEquals('OK', $destroy->status); } } <file_sep>CHANGELOG ========= 1.4.3 (xxxx-xx-xx) ------------------ n/a 1.4.2 (2014-01-14) ------------------ * Updated doc * Removeed enable and disable backup to droplets (removed from the API) * Updated CLI droplet show command shows backups and snapshots numbers * Added private_ip_address property to droplets * [BC break] Renamed 'TransfertCommand' to 'TransferCommand' (@geevcookie) * Updated CLI outputs with TableHelper (@geevcookie) * Added hhvm to travis-ci * Added SensioLabsInsight badge 1.4.1 (2013-11-03) ------------------ * SansioLabsInsight compliant 1.4.0 (2013-09-26) ------------------ * Updated doc with events examples * Added events to CLI + tests - fix #29 * Added events + tests - fix #28 * Updated doc with symfony2 integration * Updated doc with laravel integration 1.3.1 (2013-08-18) ------------------ * Added: possibility to set an adapter to instantiated object * Fixed: droplet api changes + CLI + tests + doc * Updated: doc - add integration with frameworks 1.3.0 (2013-08-18) ------------------ * Fixed: Domain test * Updated: doc * Added: CLI domains:records:destroy + tests * Added: CLI domains:records:edit + tests * Added: CLI domains:record:show + tests * Added: CLI domains:records:add + tests * Added: CLI domains:records:all + tests * Fixed: Domains new record test - domain id is already in the api url * Added: CLI domains:destroy + tests * Added: CLI domains:add + tests * Fixed: DigitalOcean's API url in doc * Fixed: Domains::show test * Added: CLI domains:show + tests * Added: CLI domains:all + tests * Added: domains and records + tests - fix #23 * Fixed: SSH key destroy test 1.2.1 (2013-08-15) ------------------ * Fixed: CLI when you do not have images + test * Fixed: CLI where there is no droplets + test * Fixed: CLI when there is no ssh keys + test * Fixed: catch errors when the API returns an old error object response - fix #27 1.2.0 (2013-08-06) ------------------ * Updated: composer.json * Updated: sshkey edit test * Added: typehint to id variables * Fixed: mock call in images destroy test * Added: images transfert to CLI + tests * Added: images transfert + tests - fix #24 * Added: droplets rename to CLI - tests * Added: droplets rename action + tests - fix #25 * Added: ssh edit in CLI + test * Added: ssh key edit + test - fix #12 * Fixed: query procesing * Added: poser.pugx.org badges * Removed: stillmaintained.com 1.1.3 (2013-04-26) ------------------ * Added: HttpAdapter library * Fixed: socket test * Updated: socket user-agent * Updated: add command help text in CLI * Fixed: travis-ci * Added: bitdeli.com * Added: coveralls.io * Updated: Contribution doc * Fixed: digitalocean abstract class 1.1.2 (2013-03-22) ------------------ * Added: droplet create interactively test * Fixed: creating a new ssh key is more verbose * Fixed: ssh key argument name to ssh_pub_key 1.1.1 (2013-03-22) ------------------ * Added: terminal screencast about create-interactively command * Fixed: tests * Fixed: droplet create command * Fixed: images and ssh keys destroy command * Added: create interactively a new droplet in CLI 1.1.0 (2013-03-21) ------------------ * Added: distribution credential file as a constant * Added: edit command to CLI - fix #13 * Added: ask confirmation on droplet reboot command - fix #21 * Added: ask confirmation on droplet rebuild command - fix #20 * Added: ask confirmation on droplet reset root password command - fix #19 * Added: ask confirmation on droplet resize command - fix #18 * Added: ask confirmation on droplet restore command - fix #17 * Added: ask confirmation on droplet shutdown command - fix #16 * Added: ask confirmation on ssh key destroy command - fix #14 * Added: ask confirmation on image destroy command - fix #14 * Added: ask confirmation on droplet destroy command - fix #14 * Fixed: doc about credential file and removed screenshot 1.0.0 (2013-03-19) ------------------ * Added: tests to ssh keys and command CLI * Added: tests to images CLI * Added: tests to droplets CLI * Added: tests to regions and sizes CLI * Updated: doc with credentials option * Updated: doc about CLI * Added: CLI 0.2.0 (2013-03-18) ------------------ * Fixed: tests * Added: Credential class + test [BC break] * Added: cURL adapter is the default one * Updated: doc with exemples - fix #11 * Added: check when adding ssh keys to new droplets 0.1.1 (2013-03-15) ------------------ * Fixed: class names more consistant [BC break] * Fixed: adapter test filenames * Fixed: credits * Updated: composer.json and doc * Added: SocketAdapter + test - fix #9 * Added: ZendAdapter + test - fix #10 * Added: GuzzleAdapter + test - fix #7 * Added: BuzzAdapter + test - fix #8 0.1.0 (2013-03-15) ------------------ * Updated: doc with exemples * Refactored: api url construction * Refactored: tests * Updated: composer.json keywords * Added: SSH Keys API + test - fix #3 * Fixed: Size alias * Added: Sizes API + test - fix #4 * Added: Images API + test - fix #2 * Updated: regions() method to all() * Refactored: use ReflectionMethod() in tests * Added: Regions API + test - fix #1 * Refactored: constructor, buildQuery and processQuery * Refactored: droplet actions * Fixed: composer.json name convention * Added: travis-ci and stillmaintained * Initial import <file_sep>DigitalOcean ============ The *version 2* of the API will be available soon ! Please visit [DigitalOceanV2](https://github.com/toin0u/DigitalOceanV2) and contribute :) This PHP 5.3+ library helps you to interact with the [DigitalOcean](https://www.digitalocean.com/) [API](https://api.digitalocean.com/) via PHP or [CLI](#cli). [![Build Status](https://secure.travis-ci.org/toin0u/DigitalOcean.png)](http://travis-ci.org/toin0u/DigitalOcean) [![Coverage Status](https://coveralls.io/repos/toin0u/DigitalOcean/badge.png?branch=master)](https://coveralls.io/r/toin0u/DigitalOcean) [![Latest Stable Version](https://poser.pugx.org/toin0u/DigitalOcean/v/stable.png)](https://packagist.org/packages/toin0u/DigitalOcean) [![Total Downloads](https://poser.pugx.org/toin0u/DigitalOcean/downloads.png)](https://packagist.org/packages/toin0u/DigitalOcean) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/1c38ce22-9430-4b47-9bc4-841226d2149f/mini.png)](https://insight.sensiolabs.com/projects/1c38ce22-9430-4b47-9bc4-841226d2149f) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/toin0u/DigitalOcean/badges/quality-score.png?s=5a08820b316c384543c53357899b8a18e6625b8a)](https://scrutinizer-ci.com/g/toin0u/DigitalOcean/) > DigitalOcean is **built for Developers**, helps to **get things done faster** and to > **deploy an SSD cloud server** in less than 55 seconds with a **dedicated IP** and **root access**. > [Read more](https://www.digitalocean.com/features). Installation ------------ This library can be found on [Packagist](https://packagist.org/packages/toin0u/digitalocean). The recommended way to install this is through [composer](http://getcomposer.org). Run these commands to install composer, the library and its dependencies: ```bash $ curl -sS https://getcomposer.org/installer | php $ php composer.phar require toin0u/digitalocean:@stable ``` Or edit `composer.json` and add: ```json { "require": { "toin0u/digitalocean": "~1.0" } } ``` And install dependencies: ```bash $ curl -sS https://getcomposer.org/installer | php $ php composer.phar install ``` Now you can add the autoloader, and you will have access to the library: ```php <?php require 'vendor/autoload.php'; ``` If you don't use neither **Composer** nor a _ClassLoader_ in your application, just require the provided autoloader: ```php <?php require_once 'src/autoload.php'; ``` Usage ----- You need an `HttpAdapter` which is responsible to get data from DigitalOcean's RESTfull API. You can provide your own adapter by implementing `HttpAdapter\HttpAdapterInterface`. [Read more about HttpAdapter](https://github.com/toin0u/HttpAdapter) ```php <?php require 'vendor/autoload.php'; use DigitalOcean\DigitalOcean; use DigitalOcean\Credentials; // Set up your credentials. $credentials = new Credentials('YOUR_CLIENT_ID', 'YOUR_API_KEY') // Use the default adapter, CurlHttpAdapter. $digitalOcean = new DigitalOcean($credentials); // Or use BuzzHttpAdapter. $digitalOcean = new DigitalOcean($credentials, new \HttpAdapter\BuzzHttpAdapter()); // Or $digitalOcean->setAdapter(new \HttpAdapter\BuzzHttpAdapter()); ``` API --- ### Droplets ### ```php // ... $droplets = $digitalOcean->droplets(); // alias to Droplets class. try { // Returns all active droplets that are currently running in your account. $allActive = $droplets->showAllActive(); printf("%s\n", $allActive->status); // OK $firstDroplet = $allActive->droplets[0]; printf("%s\n", $firstDroplet->id); // 12345 printf("%s\n", $firstDroplet->name); // foobar printf("%s\n", $firstDroplet->image_id); // 56789 printf("%s\n", $firstDroplet->size_id); // 66 printf("%s\n", $firstDroplet->region_id); // 2 printf("%s\n", $firstDroplet->backups_active); // true printf("%s\n", $firstDroplet->ip_address); // 127.0.0.1 printf("%s\n", $firstDroplet->private_ip_address); // null printf("%s\n", $firstDroplet->locked); // false printf("%s\n", $firstDroplet->status); // active printf("%s\n", $firstDroplet->created_at); // 2013-01-01T09:30:00Z // Returns full information for a specific droplet. printf("%s\n", $droplets->show(12345)->droplet->name); // foobar // Creates a new droplet. The argument should be an array with 4 required keys: // name, sized_id, image_id and region_id. ssh_key_ids key is optional but if any it should be a string. $createDroplet = $droplets->create(array( 'name' => 'my_new_droplet', 'size_id' => 123, 'image_id' => 456, 'region_id' => 789, 'ssh_key_ids' => '12,34,56', // 3 ssh keys 'private_networking' => true, 'backups_enabled' => true, )); printf("%s\n", $createDroplet->status); // OK printf("%s\n", $createDroplet->droplet->event_id); // 78908 // Reboots a droplet. $rebootDroplet = $droplets->reboot(12345); printf("%s, %s\n", $rebootDroplet->status, $rebootDroplet->event_id); // Power cycles a droplet. $powerCycleDroplet = $droplets->powerCycle(12345); printf("%s, %s\n", $powerCycleDroplet->status, $powerCycleDroplet->event_id); // Shutdowns a running droplet. $shutdownDroplet = $droplets->shutdown(12345); printf("%s, %s\n", $shutdownDroplet->status, $shutdownDroplet->event_id); // Powerons a powered off droplet. $powerOnDroplet = $droplets->powerOn(12345); printf("%s, %s\n", $powerOnDroplet->status, $powerOnDroplet->event_id); // Poweroffs a running droplet. $powerOffDroplet = $droplets->powerOff(12345); printf("%s, %s\n", $powerOffDroplet->status, $powerOffDroplet->event_id); // Resets the root password for a droplet. $resetRootPasswordDroplet = $droplets->resetRootPassword(12345); printf("%s, %s\n", $resetRootPasswordDroplet->status, $resetRootPasswordDroplet->event_id); // Resizes a specific droplet to a different size. The argument should be an array with size_id key. $resizeDroplet = $droplets->resize(12345, array('size_id' => 123)); printf("%s, %s\n", $resizeDroplet->status, $resizeDroplet->event_id); // Takes a snapshot of the running droplet, which can later be restored or used to create a new droplet // from the same image. The argument can be an empty array or an array with name key. $snapshotDroplet = $droplets->snapshot(12345, array('name' => 'my_snapshot')); printf("%s, %s\n", $snapshotDroplet->status, $snapshotDroplet->event_id); // Restores a droplet with a previous image or snapshot. The argument should be an array with image_id key. $restoreDroplet = $droplets->restore(12345, array('image_id' => 123)); printf("%s, %s\n", $restoreDroplet->status, $restoreDroplet->event_id); // Reinstalls a droplet with a default image. The argument should be an array with image_id key. $rebuildDroplet = $droplets->rebuild(12345, array('image_id' => 123)); printf("%s, %s\n", $rebuildDroplet->status, $rebuildDroplet->event_id); // Enables automatic backups which run in the background daily to backup your droplet's data. $enableBackupsDroplet = $droplets->enableAutomaticBackups(12345); printf("%s, %s\n", $enableBackupsDroplet->status, $enableBackupsDroplet->event_id); // Disables automatic backups from running to backup your droplet's data. $disableBackupsDroplet = $droplets->disableAutomaticBackups(12345); printf("%s, %s\n", $disableBackupsDroplet->status, $disableBackupsDroplet->event_id); // Renames a specific droplet to a different name. The argument should be an array with name key. $renameDroplet = $droplets->rename(12345, array('name' => 'new_name')); printf("%s, %s\n", $renameDroplet->status, $renameDroplet->event_id); // Destroys one of your droplets - this is irreversible ! $destroyDroplet = $droplets->destroy(12345); printf("%s, %s\n", $destroyDroplet->status, $destroyDroplet->event_id); } catch (Exception $e) { die($e->getMessage()); } ``` ### Regions ### ```php // ... $regions = $digitalOcean->regions(); // alias to Regions class. try { // Returns all the available regions within the Digital Ocean cloud. $allRegions = $regions->getAll(); printf("%s\n", $allRegions->status); // OK $region1 = $allRegions->regions[0]; printf("%s, %s\n", $region1->id, $region1->name); // 1, New York 1 $region2 = $allRegions->regions[1]; printf("%s, %s\n", $region2->id, $region2->name); // 2, Amsterdam 1 } catch (Exception $e) { die($e->getMessage()); } ``` ### Images ### ```php // ... $images = $digitalOcean->images(); // alias to Images class. try { // Returns all the available images that can be accessed by your client ID. You will have access // to all public images by default, and any snapshots or backups that you have created in your own account. $allImages = $images->getAll(); printf("%s\n", $allImages->status); // OK $firstImage = $allImages->images[0]; printf("%s\n", $firstImage->id); // 12345 printf("%s\n", $firstImage->name); // alec snapshot printf("%s\n", $firstImage->distribution); // Ubuntu // ... $otherImage = $allImages->images[36]; printf("%s\n", $otherImage->id); // 32399 printf("%s\n", $otherImage->name); // Fedora 17 x32 Desktop printf("%s\n", $otherImage->distribution); // Fedora // Returns all your images. $myImages = $images->getMyImages(); printf("%s\n", $myImages->status); // OK $firstImage = $myImages->images[0]; printf("%s\n", $firstImage->id); // 12345 printf("%s\n", $firstImage->name); // my_image 2013-02-01 printf("%s\n", $firstImage->distribution); // Ubuntu // Returns all global images. $globalImages = $images->getGlobal(); printf("%s\n", $globalImages->status); // OK $anImage = $globalImages->images[9]; printf("%s\n", $anImage->id); // 12573 printf("%s\n", $anImage->name); // Debian 6.0 x64 printf("%s\n", $anImage->distribution); // Debian // Displays the attributes of an image. printf("%s\n", $images->show(12574)->image->distribution); // CentOS // Destroys an image. There is no way to restore a deleted image so be careful and ensure // your data is properly backed up. $destroyImage = $images->destroy(12345); printf("%s\n", $destroyImage->status); // OK // Transferts a specific image to a specified region id. The argument should be an array with region_id key. $transfertImage = $images->transfert(12345, array('region_id' => 67890)); printf("%s\n", $transfertImage->status); // OK } catch (Exception $e) { die($e->getMessage()); } ``` ### SSH Keys ### ```php // ... $sshKeys = $digitalOcean->sshKeys(); // alias to SSHKeys class. try { // Returns all the available public SSH keys in your account that can be added to a droplet. $allSshKeys = $sshKeys->getAll(); printf("%s\n", $allSshKeys->status); // OK $firstSshKey = $allSshKeys->ssh_keys[0]; printf("%s\n", $firstSshKey->id); // 10 printf("%s\n", $firstSshKey->name); // office-imac $otherSshKey = $allSshKeys->ssh_keys[1]; printf("%s\n", $otherSshKey->id); // 11 printf("%s\n", $otherSshKey->name); // macbook-air // Shows a specific public SSH key in your account that can be added to a droplet. $sshKey = $sshKeys->show(10); printf("%s\n", $sshKey->status); // OK printf("%s\n", $sshKey->ssh_key->id); // 10 printf("%s\n", $sshKey->ssh_key->name); // office-imac printf("%s\n", $sshKey->ssh_key->ssh_pub_key); // ssh-dss AHJASDBVY6723bgB...I0Ow== me@office-imac // Adds a new public SSH key to your account. The argument should be an array with name and ssh_pub_key keys. $addSshKey = $sshKeys->add(array( 'name' => 'macbook_pro', 'ssh_pub_key' => 'ssh-dss AHJASDBVY6723bgB...I0Ow== me@macbook_pro', )); printf("%s\n", $addSshKey->status); // OK printf("%s\n", $addSshKey->ssh_key->id); // 12 printf("%s\n", $addSshKey->ssh_key->name); // macbook_pro printf("%s\n", $addSshKey->ssh_key->ssh_pub_key); // ssh-dss AHJASDBVY6723bgB...I0Ow== me@macbook_pro // Edits an existing public SSH key in your account. The argument should be an array with ssh_pub_key key. $editSshKey = $sshKeys->edit(12, array( 'ssh_pub_key' => 'ssh-dss fdSDlfDFdsfRF893...jidfs8Q== me@new_macbook_pro', )); printf("%s\n", $editSshKey->status); // OK printf("%s\n", $editSshKey->ssh_key->id); // 12 printf("%s\n", $editSshKey->ssh_key->name); // macbook_pro printf("%s\n", $editSshKey->ssh_key->ssh_pub_key); // ssh-dss fdSDlfDFdsfRF893...jidfs8Q== me@new_macbook_pro // Deletes the SSH key from your account. $destroySshKey = $sshKeys->destroy(12); printf("%s\n", $destroySshKey->status); // OK } catch (Exception $e) { die($e->getMessage()); } ``` ### Sizes ### ```php // ... $sizes = $digitalOcean->sizes(); // alias to Sizes class. try { // Returns all the available sizes that can be used to create a droplet. $allSizes = $sizes->getAll(); printf("%s\n", $allSizes->status); // OK $size1 = $allSizes->sizes[0]; printf("%s, %s\n", $size1->id, $size1->name); // 33, 512MB // ... $size6 = $allSizes->sizes[5]; printf("%s, %s\n", $size1->id, $size1->name); // 38, 16GB } catch (Exception $e) { die($e->getMessage()); } ``` ### Domains ### ```php // ... $domains = $digitalOcean->domains(); // alias to Domains class. try { // Returns all of your current domains. $allDomains = $domains->getAll(); printf("%s\n", $allDomains->status); // OK $domain1 = $allDomains->domains[0]; printf( "%s, %s, %s, %s, %s, %s\n", $domain1->id, $domain1->name, $domain1->ttl, $domain1->live_zone_file, $domain1->error, $domain1->zone_file_with_error ); // 100, foo.org, 1800, $TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM...., null, null // ... $domain5 = $allDomains->domains[4]; // ... // Show a specific domain id or domain name. $domain = $domains->show(123); printf( "%s, %s, %s, %s, %s, %s\n", $domain->id, $domain->name, $domain->ttl, $domain->live_zone_file, $domain->error, $domain->zone_file_with_error ); // 101, bar.org, 1800, $TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM...., null, null // Adds a new domain with an A record for the specified IP address. // The argument should be an array with name and ip_address keys. $addDomain = $domains->add(array( 'name' => 'baz.org', 'ip_address' => '127.0.0.1', )); printf("%s\n", $addDomain->status); // OK printf("%s\n", $addDomain->domain->id); // 12 printf("%s\n", $addDomain->domain->name); // macbook_pro // Deletes the specified domain id or domaine name. $deleteDomaine = $domains->destroy(123); printf("%s\n", $deleteDomaine->status); // OK // Returns all of your current domain records. $records = $domains->getRecords(123); printf("%s\n", $records->status); // OK $record1 = $records->records[0]; printf("%s\n", $record1->id); // 33 printf("%s\n", $record1->domain_id); // 100 printf("%s\n", $record1->record_type); // A printf("%s\n", $record1->name); // foo.org printf("%s\n", $record1->data); // 8.8.8.8 printf("%s\n", $record1->priority); // null printf("%s\n", $record1->port); // null printf("%s\n", $record1->weight); // null $record2 = $records->records[1]; // ... // Adds a new record to a specific domain id or domain name. // The argument should be an array with record_type and data keys. // - record_type can be only 'A', 'CNAME', 'NS', 'TXT', 'MX' or 'SRV'. // - data is a string, the value of the record. // // Special cases: // - name is a required string if the record_type is 'A', 'CNAME', 'TXT' or 'SRV'. // - priority is an required integer if the record_type is 'SRV' or 'MX'. // - port is an required integer if the record_type is 'SRV'. // - weight is an required integer if the record_type is 'SRV'. $Addrecord = $domains->newRecord('foo.org', array( 'record_type' => 'SRV', 'data' => 'data', 'name' => 'bar', 'priority' => 1, 'port' => 88, 'weight' => 2, )); printf("%s\n", $Addrecord->status); // OK printf("%s\n", $Addrecord->domain_record->id); // 34 printf("%s\n", $Addrecord->domain_record->domain_id); // 100 printf("%s\n", $Addrecord->domain_record->record_type); // SRV printf("%s\n", $Addrecord->domain_record->name); // bar printf("%s\n", $Addrecord->domain_record->data); // data printf("%s\n", $Addrecord->domain_record->priority); // 1 printf("%s\n", $Addrecord->domain_record->port); // 88 printf("%s\n", $Addrecord->domain_record->weight); // 2 // Returns the specified domain record. $record = $domains->getRecord(123, 456); printf("%s\n", $record->status); // OK printf("%s\n", $record->record->id); // 456 printf("%s\n", $record->record->domain_id); // 123 printf("%s\n", $record->record->record_type); // CNAME printf("%s\n", $record->record->name); // bar.org printf("%s\n", $record->record->data); // 8.8.8.8 printf("%s\n", $record->record->priority); // null printf("%s\n", $record->record->port); // null printf("%s\n", $record->record->weight); // null // Edits a record to a specific domain. Look at Domains::newRecord parameters. $editRecord = $domains->editRecord(123, 456, array( 'record_type' => 'SRV', 'data' => '127.0.0.1', 'name' => 'baz.org', 'priority' => 1, 'port' => 8888, 'weight' => 20, )); printf("%s\n", $editRecord->status); // OK printf("%s\n", $editRecord->record->id); // 456 printf("%s\n", $editRecord->record->domain_id); // 123 printf("%s\n", $editRecord->record->record_type); // SRV printf("%s\n", $editRecord->record->name); // baz.org printf("%s\n", $editRecord->record->data); // 127.0.0.1 printf("%s\n", $editRecord->record->priority); // 1 printf("%s\n", $editRecord->record->port); // 8888 printf("%s\n", $editRecord->record->weight); // 20 // Deletes the specified domain record. $deleteRecord = $domains->destroyRecord(123); printf("%s\n", $deleteRecord->status); // OK } catch (Exception $e) { die($e->getMessage()); } ``` ### Events ### ```php // ... $events = $digitalOcean->events(); // alias to Events class. try { // Returns the event details nr. 123 $event = $events->show(123); printf("%s\n", $event->status); // OK printf("%s\n", $event->event->id); // 123 printf("%s\n", $event->event->action_status); // done printf("%s\n", $event->event->droplet_id); // 100824 printf("%s\n", $event->event->event_type_id); // 1 printf("%s\n", $event->event->percentage); // 100 } catch (Exception $e) { die($e->getMessage()); } ``` ### CLI ### To use the [Command-Line Interface]((http://i.imgur.com/Zhvk5yr.png)), you need to copy and rename the `credentials.yml.dist` file to `credentials.yml` in your project directory, then add your own Client ID and API key: ```yml CLIENT_ID: <YOUR_CLIENT_ID> API_KEY: <YOUR_API_KEY> ``` If you want to use another credential file just add the option `--credentials="/path/to/file"` to commands below. Commands for `Droplets`: ```bash $ php digitalocean list droplets $ php digitalocean droplets:show-all-active +----+---------+----------+---------+-----------+----------------+------------+--------------------+--------+--------+----------------------+ | ID | Name | Image ID | Size ID | Region ID | Backups Active | IP Address | Private IP Address | Status | Locked | Created At | +----+---------+----------+---------+-----------+----------------+------------+--------------------+--------+--------+----------------------+ | 1 | my_drop | 54321 | 66 | 2 | 1 | 127.0.0.1 | | active | | 2013-01-01T09:30:00Z | +----+---------+----------+---------+-----------+----------------+------------+--------------------+--------+--------+----------------------+ $ php digitalocean droplets:show 12345 +-------+---------+----------+---------+-----------+----------------+---------+-----------+------------+--------------------+--------+--------+----------------------+ | ID | Name | Image ID | Size ID | Region ID | Backups Active | Backups | Snapshots | IP Address | Private IP Address | Status | Locked | Created At | +-------+---------+----------+---------+-----------+----------------+---------+-----------+------------+--------------------+--------+--------+----------------------+ | 12345 | my_drop | 54321 | 66 | 2 | 1 | 7 | 1 | 127.0.0.1 | 10.10.10.10 | active | | 2013-01-01T09:30:00Z | +-------+---------+----------+---------+-----------+----------------+---------+-----------+------------+--------------------+--------+--------+----------------------+ $ php digitalocean droplets:create my_new_droplet 66 1601 2 // Creates a new droplet named "my_new_droplet" with 512MB and CentOS 5.8 x64 in Amsterdam without any SSH keys. $ php digitalocean droplets:create test_droplet 65 43462 1 "5555,5556" // Creates a new droplet named "test_droplet" with 8BG and Ubuntu 11.04x32 Desktop in New York with 2 SSH keys. +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6895 | +--------+----------+ $ php digitalocean droplets:create-interactively // see: http://shelr.tv/records/514c2ba796608075f800005a $ php digitalocean droplets:reboot 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6896 | +--------+----------+ $ php digitalocean droplets:power-cycle 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6897 | +--------+----------+ $ php digitalocean droplets:shutdown 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6898 | +--------+----------+ $ php digitalocean droplets:power-on 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6899 | +--------+----------+ $ php digitalocean droplets:power-off 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6900 | +--------+----------+ $ php digitalocean droplets:reset-root-password <PASSWORD> +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6901 | +--------+----------+ $ php digitalocean droplets:resize 12345 62 // resizes to 2GB +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6902 | +--------+----------+ $ php digitalocean droplets:snapshot 12345 my_new_snapshot // the name is optional +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6903 | +--------+----------+ $ php digitalocean droplets:restore 12345 46964 // restores to "LAMP on Ubuntu 12.04" image +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6904 | +--------+----------+ $ php digitalocean droplets:rebuild 12345 1601 // rebuilds to "CentOS 5.8 x64" image +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6905 | +--------+----------+ $ php digitalocean droplets:enable-automatic-backups 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6906 | +--------+----------+ $ php digitalocean droplets:disable-automatic-backups 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6907 | +--------+----------+ $ php digitalocean droplets:rename 12345 new_name +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6908 | +--------+----------+ $ php digitalocean droplets:destroy 12345 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 6909 | +--------+----------+ ``` Commands for `Images`: ```bash $ php digitalocean list images $ php digitalocean images:all +--------+----------+--------------+ | ID | Name | Distribution | +--------+----------+--------------+ | 13245 | my_image | Ubuntu | | 21345 | my_image | Ubuntu | +--------+----------+--------------+ $ php digitalocean images:mines +--------+----------+--------------+ | ID | Name | Distribution | +--------+----------+--------------+ | 13245 | my_image | Ubuntu | +--------+----------+--------------+ $ php digitalocean images:global +--------+-------------------------+--------------+ | ID | Name | Distribution | +--------+-------------------------+--------------+ | 1601 | CentOS 5.8 x64 | CentOS | | 1602 | CentOS 5.8 x32 | CentOS | | 43462 | Ubuntu 11.04x32 Desktop | Ubuntu | +--------+-------------------------+--------------+ $ php digitalocean images:show 46964 +--------+----------------------+--------------+ | ID | Name | Distribution | +--------+----------------------+--------------+ | 46964 | LAMP on Ubuntu 12.04 | Ubuntu | +--------+----------------------+--------------+ $ php digitalocean images:destroy 12345 +--------+ | Status | +--------+ | OK | +--------+ $ php digitalocean images:transfert 12345 67890 +--------+----------+ | Status | Event ID | +--------+----------+ | OK | 32654 | +--------+----------+ ``` Commands for `Regions`: ```bash $ php digitalocean list regions $ php digitalocean regions:all +----+-------------+ | ID | Name | +----+-------------+ | 1 | New York 1 | | 2 | Amsterdam 1 | +----+-------------+ ``` Commands for `Sizes`: ```bash $ php digitalocean list sizes $ php digitalocean sizes:all +----+-------+ | ID | Name | +----+-------+ | 1 | 512MB | | 2 | 1GB | | 3 | 2GB | | 4 | 4GB | | 5 | 8GB | | 6 | 16GB | | 7 | 21GB | | 8 | 48GB | | 9 | 64GB | | 10 | 96GB | +----+-------+ ``` Commands for `SSH Keys`: ```bash $ php digitalocean list ssh-keys $ php digitalocean ssh-keys:all +------+----------------+ | ID | Name | +------+----------------+ | 5555 | my_pub_ssh_key | +------+----------------+ $ php digitalocean ssh-keys:show 5555 +------+----------------+----------------------------------------------------+ | ID | Name | Pub Key | +------+----------------+----------------------------------------------------+ | 5555 | my_pub_ssh_key | ssh-dss | | | | AHJASDBVY6723bgBVhusadkih238723kjLKFnbkjGFklaslkhf | | | | .... ZkjCTuZVy6dcH3ag6JlEfju67euWT5yMnT1I0Ow== | | | | dev@my_pub_ssh_key | +------+----------------+----------------------------------------------------+ $ php digitalocean ssh-keys:add my_new_ssh_key "ssh-dss DFDSFSDFC1.......FDSFewf987fdsf= dev@my_new_ssh_key" +------+----------------+----------------------------------------------------+ | ID | Name | Pub Key | +------+----------------+----------------------------------------------------+ | 5556 | my_new_ssh_key | ssh-dss | | | | DFDSFSDFC1723bgBVhusadkih238723kjLKFnbkjGFklaslkhf | | | | .... ZkjCTuZVy6dcH3ag6JlEfju67FDSFewf987fdsf== | | | | dev@my_new_ssh_key | +------+----------------+----------------------------------------------------+ $ php digitalocean ssh-keys:edit 5556 "ssh-dss fdSDlfDFdsfRF893...jidfs8Q== me@new_macbook_pro" +------+----------------+----------------------------------------------------+ | ID | Name | Pub Key | +------+----------------+----------------------------------------------------+ | 5556 | my_new_ssh_key | ssh-dss | | | | <KEY>kjGFklaslkhf | | | | .... ZkjCTuZVy6dcH3ag6JlEfju67FDSFewfjidfs8Q== | | | | me@new_macbook_pro | +------+----------------+----------------------------------------------------+ $ php digitalocean ssh-keys:destroy 5556 +--------+ | Status | +--------+ | OK | +--------+ ``` Commands for `Domains`: ```bash $ php digitalocean list domains $ php digitalocean domains:all +-----+---------+------+----------------+-------+----------------------+ | ID | Name | TTL | Live Zone File | Error | Zone File With Error | +-----+---------+------+----------------+-------+----------------------+ | 245 | foo.com | 6800 | ... | | ... | | 678 | foo.org | 1800 | ... | | ... | +-----+---------+------+----------------+-------+----------------------+ $ php digitalocean domains:show 678 +-----+---------+------+----------------+-------+----------------------+ | ID | Name | TTL | Live Zone File | Error | Zone File With Error | +-----+---------+------+----------------+-------+----------------------+ | 678 | foo.org | 1800 | ... | | ... | +-----+---------+------+----------------+-------+----------------------+ $ php digitalocean domains:add bar.org 127.0.0.1 +--------+-----+---------+ | Status | ID | Name | +--------+-----+---------+ | OK | 679 | bar.org | +--------+-----+---------+ $ php digitalocean domains:destroy 679 +--------+ | Status | +--------+ | OK | +--------+ $ php digitalocean domains:records:all +----+-----------+-------+-------------+---------+----------+------+--------+ | ID | Domain ID | Type | Name | Data | Priority | Port | Weight | +----+-----------+-------+-------------+---------+----------+------+--------+ | 49 | 678 | A | example.com | 8.8.8.8 | | | | | 50 | 678 | CNAME | www | @ | | | | +----+-----------+-------+-------------+---------+----------+------+--------+ $ php digitalocean domains:records:add 678 SRV @ foo 1 2 3 +--------+----+-----------+------+------+------+----------+------+--------+ | Status | ID | Domain ID | Type | Name | Data | Priority | Port | Weight | +--------+----+-----------+------+------+------+----------+------+--------+ | OK | 7 | 678 | SRV | foo | @ | 1 | 2 | 3 | +--------+----+-----------+------+------+------+----------+------+--------+ $ php digitalocean domains:records:show 678 7 +--------+----+-----------+------+------+------+----------+------+--------+ | Status | ID | Domain ID | Type | Name | Data | Priority | Port | Weight | +--------+----+-----------+------+------+------+----------+------+--------+ | OK | 7 | 678 | SRV | foo | @ | 1 | 2 | 3 | +--------+----+-----------+------+------+------+----------+------+--------+ $ php digitalocean domains:records:edit 678 7 SRV new_data new_name 5 8888 10 +--------+----+-----------+------+-----------+-------------+----------+------+--------+ | Status | ID | Domain ID | Type | Name | Data | Priority | Port | Weight | +--------+----+-----------+------+-----------+-------------+----------+------+--------+ | OK | 7 | 678 | SRV | new_name | new_data | 5 | 8888 | 10 | +--------+----+-----------+------+-----------+-------------+----------+------+--------+ $ php digitalocean domains:records:destroy 678 7 +--------+ | Status | +--------+ | OK | +--------+ ``` Commands for `Events`: ```bash $ php digitalocean events:show 123 +----+--------+------------+---------------+------------+ | ID | Status | Droplet ID | Event Type ID | Percentage | +----+--------+------------+---------------+------------+ | 1 | done | 100824 | 1 | 100 | +----+--------+------------+---------------+------------+ ``` Integration with Frameworks --------------------------- * [Silex](https://github.com/toin0u/DigitalOcean-silex) * [Laravel](https://github.com/toin0u/DigitalOcean-laravel) * [Symfony2](https://github.com/toin0u/Toin0uDigitalOceanBundle) * ... Unit Tests ---------- To run unit tests, you'll need the `cURL` extension and a set of dependencies, you can install them using Composer: ```bash $ php composer.phar install --dev ``` Once installed, just launch the following command: ```bash $ phpunit --coverage-text ``` You'll obtain some skipped unit tests due to the need of API keys. Rename the `phpunit.xml.dist` file to `phpunit.xml`, then uncomment the following lines and add your own Client ID and API key: ```xml <php> <!-- <server name="CLIENT_ID" value="YOUR_CLIENT_ID" /> --> <!-- <server name="API_KEY" value="YOUR_API_KEY" /> --> </php> ``` Contributing ------------ Please see [CONTRIBUTING](https://github.com/toin0u/DigitalOcean/blob/master/CONTRIBUTING.md) for details. Credits ------- * [<NAME>](https://twitter.com/toin0u) * [All contributors](https://github.com/toin0u/DigitalOcean/contributors) Acknowledgments --------------- * [Symfony Console Component](https://packagist.org/packages/symfony/console) * [Symfony Yaml Component](https://packagist.org/packages/symfony/yaml) Changelog --------- [See the changelog file](https://github.com/toin0u/DigitalOcean/blob/master/CHANGELOG.md) Support ------- [Please open an issues in github](https://github.com/toin0u/DigitalOcean/issues) Contributor Code of Conduct --------------------------- As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) License ------- DigitalOcean is released under the MIT License. See the bundled [LICENSE](https://github.com/toin0u/DigitalOcean/blob/master/LICENSE) file for details. [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/toin0u/DigitalOcean/trend.png)](https://bitdeli.com/free "Bitdeli Badge") <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\Sizes; use DigitalOcean\Tests\TestCase; use DigitalOcean\Sizes\Sizes; /** * @author <NAME> <<EMAIL>> */ class SizesTest extends TestCase { /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/droplets/?client_id=foo&api_key=bar */ public function testProcessQuery() { $sizes = new Sizes($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $sizes->getAll(); } public function testGetAllUrl() { $sizes = new Sizes($this->getMockCredentials(), $this->getMockAdapter($this->never())); $method = new \ReflectionMethod( $sizes, 'buildQuery' ); $method->setAccessible(true); $this->assertEquals( 'https://api.digitalocean.com/sizes/?client_id=foo&api_key=bar', $method->invoke($sizes) ); } public function testGetAll() { $response = <<<JSON {"status":"OK","sizes":[{"id":33,"name":"512MB"},{"id":34,"name":"1GB"},{"id":35,"name":"2GB"},{"id":36,"name":"4GB"},{"id":37,"name":"8GB"},{"id":38,"name":"16GB"}]} JSON ; $sizes = new Sizes($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $sizes = $sizes->getAll(); $this->assertTrue(is_object($sizes)); $this->assertEquals('OK', $sizes->status); $this->assertCount(6, $sizes->sizes); $size1 = $sizes->sizes[0]; $this->assertSame(33, $size1->id); $this->assertSame('512MB', $size1->name); $size2 = $sizes->sizes[1]; $this->assertSame(34, $size2->id); $this->assertSame('1GB', $size2->name); $size6 = $sizes->sizes[5]; $this->assertSame(38, $size6->id); $this->assertSame('16GB', $size6->name); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\CLI\Domains; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use DigitalOcean\Tests\TestCase; use DigitalOcean\CLI\Domains\GetAllCommand; /** * @author <NAME> <<EMAIL>> */ class GetAllCommandTest extends TestCase { protected $application; protected $command; protected $commandTester; protected function setUp() { $this->application = new Application(); $result = (object) array( 'domains' => array( (object) array( 'id' => 1, 'name' => 'foo.org', 'ttl' => 1800, 'live_zone_file' => '$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.foo.org. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n', 'error' => null, 'zone_file_with_error' => null, ), (object) array( 'id' => 2, 'name' => 'bar.org', 'ttl' => 1800, 'live_zone_file' => '$TTL\\t600\\n@\\t\\tIN\\tSOA\\tNS1.DIGITALOCEAN.COM.\\thostmaster.bar.org. (\\n\\t\\t\\t1369261882 ; last update: 2013-05-22 22:31:22 UTC\\n\\t\\t\\t3600 ; refresh\\n\\t\\t\\t900 ; retry\\n\\t\\t\\t1209600 ; expire\\n\\t\\t\\t10800 ; 3 hours ttl\\n\\t\\t\\t)\\n IN NS NS1.DIGITALOCEAN.COM.\\n @\\tIN A\\t8.8.8.8\\n', 'error' => null, 'zone_file_with_error' => null, ), ) ); $GetAllCommand = $this->getMock('\DigitalOcean\CLI\Domains\GetAllCommand', array('getDigitalOcean')); $GetAllCommand ->expects($this->once()) ->method('getDigitalOcean') ->will($this->returnValue($this->getMockDigitalOcean('domains', $this->getMockDomains('getAll', $result)))); $this->application->add($GetAllCommand); $this->command = $this->application->find('domains:all'); $this->commandTester = new CommandTester($this->command); } public function testExecute() { $this->commandTester->execute(array( 'command' => $this->command->getName(), )); $this->assertTrue(is_string($this->commandTester->getDisplay())); $this->assertRegExp('/\| 1 \| foo\.org \|/', $this->commandTester->getDisplay()); $this->assertRegExp('/\| 2 \| bar\.org \|/', $this->commandTester->getDisplay()); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests; use DigitalOcean\DigitalOcean; /** * @author <NAME> <<EMAIL>> */ class DigitalOceanTest extends TestCase { public function testConstructorWithoutAdapterShouldUseCurlHttpAdapter() { $digitalOcean = new MockDigitalOcean($this->getMockCredentials($this->never())); $this->assertTrue(is_object($digitalOcean->getAdapter())); $this->assertInstanceOf('\\HttpAdapter\\CurlHttpAdapter', $digitalOcean->getAdapter()); } public function testSetAdapterWithoutAdapterShouldUseCurlHttpAdapter() { $digitalOcean = new MockDigitalOcean($this->getMockCredentials($this->never())); $digitalOcean->setAdapter(); $this->assertTrue(is_object($digitalOcean->getAdapter())); $this->assertInstanceOf('\\HttpAdapter\\CurlHttpAdapter', $digitalOcean->getAdapter()); } public function testReturnsDropletInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $droplets = $digitalOcean->droplets(); $this->assertTrue(is_object($droplets)); $this->assertInstanceOf('\\DigitalOcean\\Droplets\\Droplets', $droplets); } public function testReturnsRegionInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $regions = $digitalOcean->regions(); $this->assertTrue(is_object($regions)); $this->assertInstanceOf('\\DigitalOcean\\Regions\\Regions', $regions); } public function testReturnsImageInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $images = $digitalOcean->images(); $this->assertTrue(is_object($images)); $this->assertInstanceOf('\\DigitalOcean\\Images\\Images', $images); } public function testReturnsSizeInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $sizes = $digitalOcean->sizes(); $this->assertTrue(is_object($sizes)); $this->assertInstanceOf('\\DigitalOcean\\Sizes\\Sizes', $sizes); } public function testReturnsSSHKeysInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $sshKeys = $digitalOcean->sshKeys(); $this->assertTrue(is_object($sshKeys)); $this->assertInstanceOf('\\DigitalOcean\\SSHKeys\\SSHKeys', $sshKeys); } public function testReturnsDomainsInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $domains = $digitalOcean->domains(); $this->assertTrue(is_object($domains)); $this->assertInstanceOf('\\DigitalOcean\\Domains\\Domains', $domains); } public function testReturnsEventsInstance() { $digitalOcean = new DigitalOcean($this->getMockCredentials(), $this->getMockAdapter($this->never())); $events = $digitalOcean->events(); $this->assertTrue(is_object($events)); $this->assertInstanceOf('\\DigitalOcean\\Events\\Events', $events); } } class MockDigitalOcean extends DigitalOcean { public function getAdapter() { return $this->adapter; } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\Events; use DigitalOcean\Tests\TestCase; use DigitalOcean\Events\Events; /** * @author <NAME> <<EMAIL>> */ class EventsTest extends TestCase { protected $eventId; protected function setUp() { $this->eventId = 123; } /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/events/123/?client_id=foo&api_key=bar */ public function testProcessQuery() { $events = new Events($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $events->show($this->eventId); } public function testShowUrl() { $events = new Events($this->getMockCredentials(), $this->getMockAdapter($this->never())); $method = new \ReflectionMethod( $events, 'buildQuery' ); $method->setAccessible(true); $this->assertEquals( 'https://api.digitalocean.com/events/123/?client_id=foo&api_key=bar', $method->invoke($events, $this->eventId) ); } public function testShow() { $response = <<<JSON { "status": "OK", "event": { "id": 123, "action_status": "done", "droplet_id": 100824, "event_type_id": 1, "percentage": "100" } } JSON ; $events = new Events($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $events = $events->show($this->eventId); $this->assertTrue(is_object($events)); $this->assertEquals('OK', $events->status); $this->assertTrue(is_object($events->event)); $this->assertSame($this->eventId, $events->event->id); $this->assertSame('done', $events->event->action_status); $this->assertSame(100824, $events->event->droplet_id); $this->assertSame(1, $events->event->event_type_id); $this->assertSame('100', $events->event->percentage); } } <file_sep><?php /** * This file is part of the DigitalOcean library. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DigitalOcean\Tests\Images; use DigitalOcean\Tests\TestCase; use DigitalOcean\Images\Images; use DigitalOcean\Images\ImagesActions; /** * @author <NAME> <<EMAIL>> */ class ImagesTest extends TestCase { protected $imageId; protected $image; protected $imageBuildQueryMethod; protected function setUp() { $this->imageId = 123; $this->images = new Images($this->getMockCredentials(), $this->getMockAdapter($this->never())); $this->imageBuildQueryMethod = new \ReflectionMethod( $this->images, 'buildQuery' ); $this->imageBuildQueryMethod->setAccessible(true); } /** * @expectedException \RuntimeException * @expectedExceptionMEssage Impossible to process this query: https://api.digitalocean.com/droplets/?client_id=foo&api_key=bar */ public function testProcessQuery() { $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns(null)); $images = $images->getAll(); } public function testGetAllUrl() { $this->assertEquals( 'https://api.digitalocean.com/images/?client_id=foo&api_key=bar', $this->imageBuildQueryMethod->invoke($this->images) ); } public function testGetAll() { $response = <<<JSON {"status":"OK","images":[{"id":429,"name":"Real Backup 10242011","distribution":"Ubuntu"},{"id":430,"name":"test233","distribution":"Ubuntu"},{"id":431,"name":"test888","distribution":"Ubuntu"},{"id":442,"name":"tesah22","distribution":"Ubuntu"},{"id":443,"name":"testah33","distribution":"Ubuntu"},{"id":444,"name":"testah44","distribution":"Ubuntu"},{"id":447,"name":"ahtest55","distribution":"Ubuntu"},{"id":448,"name":"ahtest66","distribution":"Ubuntu"},{"id":449,"name":"ahtest77","distribution":"Ubuntu"},{"id":458,"name":"Rails3-1Ruby1-9-2","distribution":"Ubuntu"},{"id":466,"name":"NYTD Backup 1-18-2012","distribution":"Ubuntu"},{"id":478,"name":"NLP Final","distribution":"Ubuntu"},{"id":540,"name":"API - Final","distribution":"Ubuntu"},{"id":577,"name":"test1-1","distribution":"Ubuntu"},{"id":578,"name":"alec snapshot1","distribution":"Ubuntu"}]} JSON ; $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $images = $images->getAll(); $this->assertTrue(is_object($images)); $this->assertEquals('OK', $images->status); $this->assertCount(15, $images->images); $image1 = $images->images[0]; $this->assertSame(429, $image1->id); $this->assertSame('Real Backup 10242011', $image1->name); $this->assertSame('Ubuntu', $image1->distribution); $image2 = $images->images[1]; $this->assertSame(430, $image2->id); $this->assertSame('test233', $image2->name); $this->assertSame('Ubuntu', $image2->distribution); $image15 = $images->images[14]; $this->assertSame(578, $image15->id); $this->assertSame('alec snapshot1', $image15->name); $this->assertSame('Ubuntu', $image15->distribution); } public function testGetMyImagesUrl() { $this->assertEquals( 'https://api.digitalocean.com/images/?filter=my_images&client_id=foo&api_key=bar', $this->imageBuildQueryMethod->invoke( $this->images, null, null, array('filter' => ImagesActions::ACTION_FILTER_MY_IMAGES) ) ); } public function testGetMyImages() { $response = <<<JSON {"status":"OK","images":[{"id":429,"name":"Real Backup 10242011","distribution":"Ubuntu"},{"id":430,"name":"test233","distribution":"Ubuntu"},{"id":431,"name":"test888","distribution":"Ubuntu"},{"id":442,"name":"tesah22","distribution":"Ubuntu"},{"id":443,"name":"testah33","distribution":"Ubuntu"},{"id":444,"name":"testah44","distribution":"Ubuntu"},{"id":447,"name":"ahtest55","distribution":"Ubuntu"},{"id":448,"name":"ahtest66","distribution":"Ubuntu"},{"id":449,"name":"ahtest77","distribution":"Ubuntu"},{"id":458,"name":"Rails3-1Ruby1-9-2","distribution":"Ubuntu"},{"id":466,"name":"NYTD Backup 1-18-2012","distribution":"Ubuntu"},{"id":478,"name":"NLP Final","distribution":"Ubuntu"},{"id":540,"name":"API - Final","distribution":"Ubuntu"},{"id":577,"name":"test1-1","distribution":"Ubuntu"},{"id":578,"name":"alec snapshot1","distribution":"Ubuntu"}]} JSON ; $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $myImages = $images->getMyImages(); $this->assertTrue(is_object($myImages)); $this->assertEquals('OK', $myImages->status); $this->assertCount(15, $myImages->images); } public function testGetGlobalUrl() { $this->assertEquals( 'https://api.digitalocean.com/images/?filter=global&client_id=foo&api_key=bar', $this->imageBuildQueryMethod->invoke( $this->images, null, null, array('filter' => ImagesActions::ACTION_FILTER_GLOBAL) ) ); } public function testGetGlobal() { $response = <<<JSON {"status":"OK","images":[{"id":429,"name":"Real Backup 10242011","distribution":"Ubuntu"},{"id":430,"name":"test233","distribution":"Ubuntu"},{"id":431,"name":"test888","distribution":"Ubuntu"},{"id":442,"name":"tesah22","distribution":"Ubuntu"},{"id":443,"name":"testah33","distribution":"Ubuntu"},{"id":444,"name":"testah44","distribution":"Ubuntu"},{"id":447,"name":"ahtest55","distribution":"Ubuntu"},{"id":448,"name":"ahtest66","distribution":"Ubuntu"},{"id":449,"name":"ahtest77","distribution":"Ubuntu"},{"id":458,"name":"Rails3-1Ruby1-9-2","distribution":"Ubuntu"},{"id":466,"name":"NYTD Backup 1-18-2012","distribution":"Ubuntu"},{"id":478,"name":"NLP Final","distribution":"Ubuntu"},{"id":540,"name":"API - Final","distribution":"Ubuntu"},{"id":577,"name":"test1-1","distribution":"Ubuntu"},{"id":578,"name":"alec snapshot1","distribution":"Ubuntu"}]} JSON ; $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $globalImages = $images->getGlobal(); $this->assertTrue(is_object($globalImages)); $this->assertEquals('OK', $globalImages->status); $this->assertCount(15, $globalImages->images); } public function testShowUrl() { $this->assertEquals( 'https://api.digitalocean.com/images/123/?client_id=foo&api_key=bar', $this->imageBuildQueryMethod->invoke($this->images, $this->imageId) ); } public function testShow() { $response = <<<JSON {"status":"OK","image":{"id":429,"name":"Real Backup 10242011","distribution":"Ubuntu"}} JSON ; $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $show = $images->show($this->imageId); $this->assertTrue(is_object($show)); $this->assertEquals('OK', $show->status); $this->assertSame(429, $show->image->id); $this->assertSame('Real Backup 10242011', $show->image->name); $this->assertSame('Ubuntu', $show->image->distribution); } public function testDestroyUrl() { $this->assertEquals( 'https://api.digitalocean.com/images/123/destroy/?client_id=foo&api_key=bar', $this->imageBuildQueryMethod->invoke($this->images, $this->imageId, ImagesActions::ACTION_DESTROY_IMAGE) ); } public function testDestroy() { $response = <<<JSON {"status":"OK"} JSON ; $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $destroy = $images->destroy($this->imageId); $this->assertTrue(is_object($destroy)); $this->assertEquals('OK', $destroy->status); } public function testTransfertUrl() { $newRegion = array( 'region_id' => 123, ); $this->assertEquals( 'https://api.digitalocean.com/images/123/transfert/?region_id=123&client_id=foo&api_key=bar', $this->imageBuildQueryMethod->invoke( $this->images, $this->imageId, ImagesActions::ACTION_TRANSFERT, $newRegion ) ); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You need to provide an integer "region_id". */ public function testTransfertThrowsRegionIdInvalidArgumentException() { $this->images->transfert($this->imageId, array()); } public function testTransfert() { $response = <<<JSON {"status":"OK","event_id":7501} JSON ; $images = new Images($this->getMockCredentials(), $this->getMockAdapterReturns($response)); $image = $images->transfert($this->imageId, array('region_id' => 123)); $this->assertTrue(is_object($image)); $this->assertEquals('OK', $image->status); $this->assertSame(7501, $image->event_id); } }
9d02d0d8a8c389b1ed6445224f479107e2a3e089
[ "Markdown", "PHP" ]
20
PHP
ersin-demirtas/DigitalOcean
fc08778d8daf3afa6d7d8919fefb71ba6e3aacad
69b953530686dfa0c98ef39d8d6e2ba3ab0c8617
refs/heads/main
<file_sep>const item = document.querySelectorAll('.foto'); const nama = document.querySelector('.nama'); const asal = document.querySelector('.asal'); const data = [ { nama: "<NAME>", asal: "Blora", gambar: "puji.jpg" }, { nama: "<NAME>", asal: "Bandung", gambar: "khairunisa.jpg" }, { nama: "<NAME>", asal: "Jakarta Timur", gambar: "hardi.jpg" }, { nama: "<NAME>", asal: "Depok", gambar: "adinda.jpg" }, { nama: "<NAME>", asal: "Jakarta Timur", gambar: "Foto - Meutia Admiralda Andini.jpg" } ]; let i = -1; let j = 0; let k = 1; let l = 2; let m = 3; function show(){ if(item[2].getAttribute('class') === 'geser'){ item[0].classList.remove('geser'); item[1].classList.remove('geser'); item[2].classList.remove('geser'); item[3].classList.remove('geser1'); item[4].classList.remove('geser1'); nama.classList.remove('geser'); asal.classList.remove('geser'); if(m < data.length){ m++; if(m === 5){ m = 0; item[4].setAttribute('src',`photo/${data[m].gambar}`); }else{ item[4].setAttribute('src',`photo/${data[m].gambar}`); } } if(l < data.length){ l++; if(l === 5){ l = 0; item[3].setAttribute('src',`photo/${data[l].gambar}`); }else{ item[3].setAttribute('src',`photo/${data[l].gambar}`); } } if(k < data.length){ k++; if(k === 5){ k = 0; item[2].setAttribute('src',`photo/${data[k].gambar}`); nama.innerHTML = data[k].nama; asal.innerHTML = data[k].asal; }else{ item[2].setAttribute('src',`photo/${data[k].gambar}`); nama.innerHTML = data[k].nama; asal.innerHTML = data[k].asal; } } if(j < data.length){ j++; if(j === 5){ j = 0; item[1].setAttribute('src',`photo/${data[j].gambar}`); }else{ item[1].setAttribute('src',`photo/${data[j].gambar}`); } } if(i < data.length){ i++; if(i === 5){ i = 0; item[0].setAttribute('src',`photo/${data[i].gambar}`); }else{ item[0].setAttribute('src',`photo/${data[i].gambar}`); } } setTimeout(() => { show(); }, 5000); }else{ item[0].setAttribute('class','geser'); item[1].setAttribute('class','geser'); item[2].setAttribute('class','geser'); item[3].setAttribute('class','geser1'); item[4].setAttribute('class','geser1'); nama.setAttribute('class','geser'); asal.setAttribute('class','geser'); setTimeout(() => { show(); }, 500); } } show(); <file_sep>const button = document.getElementsByClassName('button')[0]; const headerRight = document.getElementsByClassName('header-right')[0]; const header = document.getElementsByTagName('header')[0]; button.addEventListener('click',() => { headerRight.classList.toggle('menu'); header.classList.toggle('menu'); }); $(window).on("scroll", function () { if ($(window).scrollTop() > 50) { $("header").addClass("active"); } else { $("header").removeClass("active"); } }); // animasi pada digital talent $(window).scroll(function () { var wScroll = $(this).scrollTop(); // p if (wScroll > $('.digitalent').offset().top - 350) { $('.pKiri').addClass('animated fadeInLeft'); $('.pKanan').addClass('animated fadeInRight'); } }); <file_sep># DTS Link : https://meuadmiralda.github.io/A03tech.github.io/ Anggota Kelompok A03: 1. <NAME> 2. <NAME> 3. <NAME> 4. <NAME> 5. Puji Septiyana Nautika
e87c052315c63d68bf34bd3b4e01095f0f83322d
[ "JavaScript", "Markdown" ]
3
JavaScript
meuadmiralda/A03tech.github.io
fcbeca29be86e3bb8373876c9a7243a66f18ebad
77c058005fb07f442876fb8483d23853ccdd7b91
refs/heads/master
<file_sep>import editValidEditFooterTemplate from './stepway.editValidEditFooter.template.html!text'; export const EDIT_TEXTINPUT_CONTROL_COMPONENT = 'editValidEditFooter'; export const editValidEditFooterComponent = { template : editValidEditFooterTemplate, bindings : { nyaSelect: '=', ok: '&', cancel: '&' }, controller : class editValidEditFooterController { constructor() { // } static get $inject() { return []; } } };
99b8fdee02203cfb42055c52c888e2818e7d8a62
[ "JavaScript" ]
1
JavaScript
atchariya/easyFormGenerator
c1c8cbb1a6ebfb9e460c7087c431d8fa1d8ab63b
4663eae4e08f5741780f5819836582a7ea00f877
refs/heads/master
<repo_name>nayankhadase/calculator<file_sep>/cal_full.py from tkinter import * # from tkinter import ttk,messagebox root=Tk() root.geometry("350x310") root.title("Calculator") root.resizable(False,False) mytxt=StringVar() digit='' def button(dig): global digit digit=digit+str(dig) mytxt.set(digit) def all_equal(): # global digit result=eval(inp1.get()) # result=eval(digit)#we can also use this mytxt.set(result) def clear_butn(): global digit digit=" " mytxt.set(digit) inp1=Entry(root,textvariable=mytxt,width=30,justify='right', bd=29,font=("Arial",10)) inp1.grid(row=0,columnspan=4) butn1=Button(root,text=' 7 ' ,command=lambda: button(7),bd=12).grid(row=1,column=0) butn2=Button(root,text=' 8 ' ,command=lambda: button(8),bd=12).grid(row=1,column=1) butn3=Button(root,text=' 9 ' ,command=lambda: button(9),bd=12).grid(row=1,column=2) but1=Button(root,text=' + ',command=lambda: button('+'),bd=12).grid(row=1,column=3) butn4=Button(root,text=' 4 ' ,command=lambda: button(4),bd=12).grid(row=2,column=0) butn5=Button(root,text=' 5 ' ,command=lambda: button(5),bd=12).grid(row=2,column=1) butn6=Button(root,text=' 6 ' ,command=lambda: button(6),bd=12).grid(row=2,column=2) but2=Button(root,text=' - ' ,command=lambda: button('-'),bd=12).grid(row=2,column=3) butn7=Button(root,text=' 1 ' ,command=lambda: button(1),bd=12).grid(row=3,column=0) butn9=Button(root,text=' 2 ' ,command=lambda: button(2),bd=12).grid(row=3,column=1) butn9=Button(root,text=' 3 ' ,command=lambda: button(3),bd=12).grid(row=3,column=2) but3=Button(root,text=' x ' ,command=lambda: button('*'),bd=12).grid(row=3,column=3) but5=Button(root,text=' CR ' ,command=clear_butn,bd=12).grid(row=4,column=0) butn0=Button(root,text=' 0 ' ,command=lambda: button(0),bd=12).grid(row=4,column=1) but5=Button(root,text=' = ' ,command=all_equal,bd=12).grid(row=4,column=2) but4=Button(root,text=' / ' ,command=lambda: button('/'),bd=12).grid(row=4,column=3) root.mainloop()
6a4ac1ec31bdd0bf94fc808d732f8d28b2e249d6
[ "Python" ]
1
Python
nayankhadase/calculator
e354493c6355c059c2894726a4e643f701cc37c4
b92914553892e3c1aaea0538b8747cc4ff1fe7de
refs/heads/master
<repo_name>sawit/reddit.dev<file_sep>/database/seeds/PostsTableSeeder.php <?php use Illuminate\Database\Seeder; use App\Post; class PostsTableSeeder extends Seeder { public function run(){ factory(Post::class, 100)->create(); } } <file_sep>/app/Http/routes.php <?php use App\Post; use App\Http\Requests; use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', 'HomeController@showWelcome'); Route::resource('posts', 'PostsController'); Route::post('/posts/add-vote', 'PostsController@addVote'); Route::get('/profile/{id}', 'UsersController@show'); Route::get('/post/{id}/show', 'PostsController@show'); // Authentication routes... Route::get('auth/login', 'Auth\AuthController@getLogin'); Route::post('auth/login', 'Auth\AuthController@postLogin'); Route::get('auth/logout', 'Auth\AuthController@getLogout'); // Registration routes... Route::get('auth/register', 'Auth\AuthController@getRegister'); Route::post('auth/register', 'Auth\AuthController@postRegister'); Route::get('/', 'HomeController@showWelcome'); Route::resource('posts', 'PostsController'); Route::get('/posts/search', 'PostsController@search'); Route::get('/posts/{id}/edit', 'PostsController@edit'); // Route::get('/posts/{id}/update', 'PostsController@update'); Route::get('/profile/{id}', 'UsersController@update'); // // Route::get('auth/account', 'PostsController@profile'); <file_sep>/app/Post.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Post; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\DB; class Post extends BaseModel { use SoftDeletes; protected $table = 'posts'; protected $softDeletes = true; protected $dates = ['created_at', 'updated_at']; public static $rules = [ 'title' => 'required|max:100|string', 'content' => 'required|string', 'url' => 'required|active_url' ]; protected function formatValidationErrors(Validator $validator) { return $validator->errors()->all(); } public function setContentAttribute($value) { $this->attributes['content'] = strip_tags($value); } public function setTitleAttribute($value) { $this->attributes['title'] = strip_tags($value); } public function setUrlAttribute($value) { $this->attributes['url'] = strip_tags($value); } public function user() { return $this->belongsTo(User::class, 'created_by'); } public static function sortPosts($pageSize) { return Post::orderBy('created_at', 'desc')->paginate($pageSize); } public static function searchContentTitleOwner($searchQuery) { return static::join('users', 'users.id', '=', 'posts.created_by')->where('posts.content', 'LIKE', "%{$searchQuery}%")->orWhere('posts.title', 'LIKE', "%{$searchQuery}%")->orWhere('users.name', 'LIKE', "%{$searchQuery}%")->select('*', 'posts.id as id')->take(5)->get(); } public function createdBy($user) { return (!is_null($user)) ? $this->created_by == $user->id : false; } public function votes() { return $this->hasMany(Vote::class); } public function upvotes() { return $this->votes()->where('vote', '=', 1); } public function downvotes() { return $this->votes()->where('vote', '=', 0); } public function voteScore() { $upvotes = $this->upvotes()->count(); $downvotes = $this->downvotes()->count(); return $upvotes - $downvotes; } public function userVote($user) { $this->votes()->where('user_id', '=', $user->id)->first(); } } <file_sep>/database/seeds/UserTableSeeder.php <?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder { public function run() { factory(App\User::class, 50)->create(); $user1 = new App\User(); $user1->email = '<EMAIL>'; $user1->name = 'emily'; $user1->password = Hash::make('<PASSWORD>'); $user1->remember_token = str_random(10); $user1->save(); } } <file_sep>/database/migrations/2016_08_17_155618_create_votes_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateVotesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('votes', function(Blueprint $votes) { $votes->increments('id'); $votes->integer('user_id')->unsigned(); $votes->foreign('user_id')->references('id')->on('users'); $votes->integer('post_id')->unsigned(); $votes->foreign('post_id')->references('id')->on('posts'); $votes->integer('vote'); $votes->timestamps(); }); // } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('votes'); } } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Auth; class HomeController extends Controller { public function uppercase($word = "caps") { return view('uppercase')->with('word', strtoupper($word)); } public function increment($number = 0) { $number += 1; return view('increment')->with('number', $number); } public function showWelcome() { $posts = Post::with('user')->orderBy('created_at', 'DESC')->take(10)->get(); return view('welcome')->with('posts', $posts); } } <file_sep>/README.md Laravel Exercises done during codeup<file_sep>/app/User.php <?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends BaseModel implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword; protected $table = 'users'; protected $fillable = ['name', 'email', 'password']; protected $hidden = ['password', 'remember_token']; public function posts() { return $this->hasMany(Post::class); } public function votes() { return $this->hasMany('App\Vote','App\Post'); } public static function count($userId) { return Post::where('created_by', $userId)->count(); } public static function searchByName($searchQuery) { return static::where('name', 'LIKE', "%{$searchQuery}%"); } } <file_sep>/database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class DatabaseSeeder extends Seeder { public function run() { Model::unguard(); $this->command->info('Deleting posts records'); DB::table('posts')->delete(); $this->command->info('Deleting users records'); DB::table('users')->delete(); $this->call(UserTableSeeder::class); $this->call(PostsTableSeeder::class); Model::reguard(); } } <file_sep>/app/Http/Controllers/PostsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; use App\Vote; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Auth; use Illuminate\Database\Eloquent\SoftDeletes; class PostsController extends Controller { public function __construct() { $this->middleware('auth', ['except' => ['index', 'show']]); } public function index(Request $request) { $searchQuery = $request->input('search'); if (!is_null($searchQuery)) { $posts = Posts::searchContentTitleOwner($searchQuery)->orderBy('created_at', 'DESC')->with('user')->paginate(10); } else { $posts = Post::with('user')->orderBy('created_at', 'DESC')->paginate(10); } $data = compact('searchQuery', 'posts'); return view('posts.index')->with($data); } public function create() { return view('posts.create'); } public function store(Request $request) { $this->validate($request, Post::$rules); $post = new Post(); $post->created_by = Auth::user()->id; Log::info($request->all()); // Auth::id; return $this->validateAndSave($post, $request); } public function show(Request $request, $id) { $post = Post::with('user')->findOrFail($id); if ($request->user()) { $user_vote = $post->userVote($request->user()); } else { $user_vote = null; } $data = compact('post', 'user_vote'); return view('posts.show')->with($data); } public function edit($id) { $post = Post::findOrFail($id); return view('posts.edit')->with('post', $post); } public function update(Request $request, $id) { $post = Post::findOrFail($id); return $this->validateAndSave($post, $request); } public function destroy($id) { $post = Post::find($id); if(!$post) { session()->flash('message', 'Post was not found'); } else { $post->delete(); session()->flash('message', 'Post deleted'); return redirect()->action('PostsController@index'); } } public function search(Post $post, Request $request) { $search = $request->input('search'); if ($search) { $results = Post::searchPosts($search); } return view('posts.results', ['search' => $results]); } private function validateAndSave(Post $post, Request $request) { $request->session()->flash('ERROR_MESSAGE', 'Post not created'); $this->validate($request, Post::$rules); $request->session()->forget('ERROR_MESSAGE'); $post->title = $request->input('title'); $post->url = $request->input('url'); $post->content = $request->input('content'); $post->save(); $request->session()->flash('SUCCESS_MESSAGE', 'Post created'); return redirect()->action('PostsController@index'); } public function addVote(Request $request) { $vote = Vote::with('post')->firstOrCreate([ 'post_id' => $request->input('post_id'), 'user_id' => $request->user()->id ]); $vote->vote->input('vote'); $vote->save(); $post = $vote->post; } } <file_sep>/database/migrations/2016_08_17_155602_create_posts_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function(Blueprint $posts) { $posts->increments('id'); $posts->string('title', 100); $posts->string('url'); $posts->longText('content'); $posts->integer('created_by')->unsigned(); $posts->foreign('created_by') ->references('id') ->on('users'); $posts->timestamps(); $posts->softDeletes(); }); // } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('posts'); } } <file_sep>/app/Http/roll_dice.php <?php if ($roll == $guess) { echo 'You guesed correctly!'; } else { echo 'Try again!'; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>My First View</title> </head> <body>     <h1>guess: <?= $guess ?></h1>  <h1>roll: <?= $roll ?></h1> </body> </html><file_sep>/routes.php <?php Route::get('/', function () { return view('welcome'); }); Route::get('/sayHello/{name}', function($name){ return "Hello, " . $name . "!"; }); Route::get('/uppercase/{word}', function($word) { if(!empty($word)) { return strtoupper($word);; } }); Route::get('/increment/{number}', function($number) { if(is_numeric($number)) { return ++$number; } });
b10648bdf7718a0af7d1fbff5cd138feafb54e35
[ "Markdown", "PHP" ]
13
PHP
sawit/reddit.dev
ff610398673ec84b8a3b924933449b7bc1837d6e
9203718ac6c414a5f9b18633d654898eb57a5a21
refs/heads/master
<repo_name>ezRAez/volcano_pointer<file_sep>/script.py import folium, pandas # creates dataframe from volcano data vol_df = pandas.read_csv("data/Volcanoes-USA.txt") avg_lat = vol_df['LAT'].mean() avg_lon = vol_df['LON'].mean() map = folium.Map(location=[avg_lat, avg_lon], zoom_start=6, tiles="Mapbox Bright") def color_picker(elevation): minimum = int(min(vol_df['ELEV'])) step = int((max(vol_df['ELEV']) - min(vol_df['ELEV'])) / 3) if elevation in range(minimum, minimum+step): return "green" elif elevation in range(minimum + step, minimum + step * 2): return "orange" else: return "red" vol_fg = folium.FeatureGroup(name="Volcano Locations") # markers will not show in layer Control for folium - must use feature group for lat,lon,name, elev in zip(vol_df["LAT"], vol_df["LON"], vol_df["NAME"], vol_df["ELEV"]): vol_fg.add_child(folium.Marker(location=[lat, lon], popup=name, icon=folium.Icon(color=color_picker(elev)))) map.add_child(vol_fg) # adds geojson pop data map.add_child(folium.GeoJson(data=open('data/world_pop.geojson'), name="World Population", style_function=lambda x: {'fillColor': 'green' if x['properties']['POP2005'] <= 10000000 else 'orange' if 10000000 < x['properties']['POP2005'] < 20000000 else 'red'})) map.add_child(folium.LayerControl()) map.save(outfile="index.html") <file_sep>/README.md # Volcano pointer and population map Easy introduction to dataframes in pandas and iteractive folium maps.
23892ff81ef912f873adb1c5bc993a5f9639503a
[ "Markdown", "Python" ]
2
Python
ezRAez/volcano_pointer
66e5830ca461e8524fb4ca8184097dbf18baea20
c4d7528719f064544df7eb9219f1eac584135ab0
refs/heads/master
<repo_name>RebecaTonu/Learn-N-Quiz<file_sep>/app/src/main/java/com/example/learnnquiz/obiecte/Sectiune.java package com.example.learnnquiz.Obiecte; public class Sectiune { private int lectieid; private int nrsectiune; private String titlu; private String text; private String titlulectie; private int sectiunelectie; public Sectiune (int lectieid, int nrsectiune, String titlu, String text, String titlulectie, int sectiunelectie) { this.lectieid = lectieid; this.nrsectiune = nrsectiune; this.titlu = titlu; this.text = text; this.titlulectie = titlulectie; this.sectiunelectie = sectiunelectie; } public int getLectieid() { return lectieid; } public void setLectieid(int lectieid) { this.lectieid = lectieid; } public String getTitlu() { return titlu; } public void setTitlu(String titlu) { this.titlu = titlu; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTitlulectie() { return titlulectie; } public void setTitlulectie(String titlulectie) { this.titlulectie = titlulectie; } public int getNrsectiune() { return nrsectiune; } public void setNrsectiune(int nrsectiune) { this.nrsectiune = nrsectiune; } public void setSectiunelectie(int sectiunelectie) { this.sectiunelectie = sectiunelectie; } public int getSectiunelectie() { return sectiunelectie; } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ClasaContinutAdapt.java package com.example.learnnquiz.Profesor; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; <<<<<<< HEAD import android.util.Log; ======= >>>>>>> 2c82b41... LNQ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.learnnquiz.R; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class ClasaContinutAdapt extends ArrayAdapter { private final Context context; private final ArrayList<ClasaContinutAdaptVal> val; public ClasaContinutAdapt(Context context, ArrayList<ClasaContinutAdaptVal> val) { super(context, R.layout.clasa_continut_item, val); this.val = val; this.context=context; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ View rowView = inflater.inflate(R.layout.clasa_continut_item, parent, false); TextView data=(TextView)rowView.findViewById(R.id.clasaContinutItemData); data.setText(val.get(position).data); TextView materie=(TextView)rowView.findViewById(R.id.clasaContinutItemMateria); materie.setText(val.get(position).materie); TextView dificultate=(TextView)rowView.findViewById(R.id.clasaContinutItemDificultate); dificultate.setText(val.get(position).dificultate); TextView precizari=(TextView)rowView.findViewById(R.id.clasaContinutItemPrecizari); precizari.setText(val.get(position).precizari); if (precizari.getLineCount()>6) precizari.setMaxLines(6); return rowView; } public void remove(int position){ val.remove(position); this.notifyDataSetChanged(); } @Override public void notifyDataSetChanged() { <<<<<<< HEAD Collections.sort(val, new ClassContentAdapterValuesIDComparator()); ======= Collections.sort(val, new ClasaContinutAdaptValIDComparator()); >>>>>>> 2c82b41... LNQ super.notifyDataSetChanged(); } static class ClasaContinutAdaptVal implements Parcelable { int id; String materie; String dificultate; String precizari; String data; int timestamp; public ClasaContinutAdaptVal(int id, String data, int timeStamp, String materie, String pages, String precizari){ this.id=id; this.data = data; this.timestamp=timeStamp; this.materie = materie; this.dificultate =pages; this.precizari = precizari; } private ClasaContinutAdaptVal(Parcel in){ id=in.readInt(); data =in.readString(); timestamp=in.readInt(); materie =in.readString(); dificultate =in.readString(); precizari =in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(data); dest.writeInt(timestamp); dest.writeString(materie); dest.writeString(dificultate); dest.writeString(precizari); } public static final Parcelable.Creator<ClasaContinutAdaptVal> CREATOR = new Parcelable.Creator<ClasaContinutAdaptVal>() { public ClasaContinutAdaptVal createFromParcel(Parcel in) { return new ClasaContinutAdaptVal(in); } public ClasaContinutAdaptVal[] newArray(int size) { return new ClasaContinutAdaptVal[size]; } }; } <<<<<<< HEAD class ClassContentAdapterValuesIDComparator implements Comparator<ClasaContinutAdaptVal> { ======= class ClasaContinutAdaptValIDComparator implements Comparator<ClasaContinutAdaptVal> { >>>>>>> 2c82b41... LNQ @Override public int compare(ClasaContinutAdaptVal lhs, ClasaContinutAdaptVal rhs) { return rhs.timestamp - lhs.timestamp; } } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/LoginProf.java package com.example.learnnquiz.Profesor; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatTextView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.example.learnnquiz.Conturi.ValidareCont; import com.example.learnnquiz.R; public class LoginProf extends AppCompatActivity implements View.OnClickListener { private final AppCompatActivity activity = LoginProf.this; private NestedScrollView nestedScrollView; private TextInputLayout textInputLayoutEmail; private TextInputLayout textInputLayoutParola; private TextInputEditText textInputEditTextEmail; private TextInputEditText textInputEditTextParola; private AppCompatButton appCompatButtonLogin; private AppCompatTextView textViewLinkInregistrareProf; private ValidareCont validareCont; private Profesordb profesordb; <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loginprof); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ getSupportActionBar().show(); initViews(); initListeners(); initObjects(); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private void initViews() { nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView); textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail); textInputLayoutParola = (TextInputLayout) findViewById(R.id.textInputLayoutParola); textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail); textInputEditTextParola = (TextInputEditText) findViewById(R.id.textInputEditTextParola); appCompatButtonLogin = (AppCompatButton) findViewById(R.id.appCompatButtonLogin); textViewLinkInregistrareProf = (AppCompatTextView) findViewById(R.id.textViewLinkInregistrareProf); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private void initListeners() { appCompatButtonLogin.setOnClickListener(this); textViewLinkInregistrareProf.setOnClickListener(this); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private void initObjects() { profesordb = new Profesordb(activity); validareCont = new ValidareCont(activity); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public void onClick(View v) { switch (v.getId()) { case R.id.appCompatButtonLogin: verifyFromSQLite(); break; case R.id.textViewLinkInregistrareProf: Intent intentRegister = new Intent(getApplicationContext(), RegProf.class); startActivity(intentRegister); break; } } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private void verifyFromSQLite() { if (!validareCont.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) { return; } if (!validareCont.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) { return; } if (!validareCont.isInputEditTextFilled(textInputEditTextParola, textInputLayoutParola, getString(R.string.error_message_password))) { return; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ if (profesordb.checkProfesor(textInputEditTextEmail.getText().toString().trim() , textInputEditTextParola.getText().toString().trim())) { Intent accountsIntent = new Intent(activity, MainProfesor.class); accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim()); emptyInputEditText(); startActivity(accountsIntent); } else { Snackbar.make(nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show(); } } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private void emptyInputEditText() { textInputEditTextEmail.setText(null); textInputEditTextParola.setText(null); } <<<<<<< HEAD @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.log, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int menu_id = item.getItemId(); switch (menu_id){ case R.id.action_loginadm: Intent in = new Intent(LoginProf.this, LoginProf.class); startActivity(in); ======= @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int menu_id = item.getItemId(); switch (menu_id){ case R.id.action_loginadm: Intent in = new Intent(LoginProf.this, LoginProf.class); startActivity(in); >>>>>>> 2c82b41... LNQ break; case R.id.action_register: Intent intt=new Intent(LoginProf.this, RegProf.class); startActivity(intt); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ return super.onOptionsItemSelected(item); } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ClasaNouContinutFrag.java package com.example.learnnquiz.Profesor; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.Toast; import org.lucasr.twowayview.TwoWayView; import java.util.ArrayList; import java.util.Calendar; import com.example.learnnquiz.R; public class ClasaNouContinutFrag extends Fragment { <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ public static String DATE_FORMAT = "EUR"; public static final String TAG="ClasaNouContinutFrag "; private static final String ARG_CLASA_ID = "clasaId"; private static final String ARG_PARTICIPANT = "participant"; <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private int nClasaId; private String nData; private String sMaterie; private String sDificultate; private String sPrecizari; private int nTimestamp; private ArrayList<ParticipantAdapt.ParticipantAdaptVal> nParticipant; <<<<<<< HEAD private PartiAdapt nAdapt; private ArrayList<PartiAdapt.PartiAdaptVal> nPartiParti; private OnNewClassContentListener nListener; private View nRootView; private AutoCompleteTextView nMaterie; public static ClasaNouContinutFrag newInstance(int classId, ArrayList<ParticipantAdapt.ParticipantAdaptVal> students) { ClasaNouContinutFrag fragment = new ClasaNouContinutFrag(); Bundle args = new Bundle(); args.putInt(ARG_CLASA_ID,classId); args.putParcelableArrayList(ARG_PARTICIPANT,students); fragment.setArguments(args); return fragment; } public ClasaNouContinutFrag() { } ======= private PartiAdapt nAdapt; private ArrayList<PartiAdapt.PartiAdaptVal> nPartiParti; private OnClasaNouaContinutListener nListener; private View nRootView; private AutoCompleteTextView nMaterie; public static ClasaNouContinutFrag newInstance(int clasaId, ArrayList<ParticipantAdapt.ParticipantAdaptVal> participant) { ClasaNouContinutFrag fragment = new ClasaNouContinutFrag(); Bundle args = new Bundle(); args.putInt(ARG_CLASA_ID,clasaId); args.putParcelableArrayList(ARG_PARTICIPANT,participant); fragment.setArguments(args); return fragment; } public ClasaNouContinutFrag() { } >>>>>>> 2c82b41... LNQ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState!=null){ nClasaId =savedInstanceState.getInt("clasaId"); nData =savedInstanceState.getString("data"); sMaterie =savedInstanceState.getString("materie"); sDificultate =savedInstanceState.getString("dif"); sPrecizari =savedInstanceState.getString("prec"); nParticipant =savedInstanceState.getParcelableArrayList("parti"); nPartiParti =savedInstanceState.getParcelableArrayList("partiparti"); nTimestamp =savedInstanceState.getInt("timestamp"); } else if (getArguments() != null) { nClasaId = getArguments().getInt(ARG_CLASA_ID); nParticipant =getArguments().getParcelableArrayList(ARG_PARTICIPANT); nPartiParti =new ArrayList(nParticipant.size()); for (int i = 0; i< nParticipant.size(); i++) { nPartiParti.add(new PartiAdapt.PartiAdaptVal( nParticipant.get(i).id, nParticipant.get(i).nume, getActivity().getResources().getIntArray(R.array.status).toString())); } Calendar c = Calendar.getInstance(); nTimestamp =c.get(Calendar.DAY_OF_MONTH)+c.get(Calendar.MONTH)*30+c.get(Calendar.YEAR)*365; if (DATE_FORMAT == "EUR") nData = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "." + Integer.toString(c.get(Calendar.MONTH) + 1) + "." + Integer.toString(c.get(Calendar.YEAR)); else if (DATE_FORMAT == "US") nData = Integer.toString(c.get(Calendar.MONTH) + 1) + "/" + Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "/" + Integer.toString(c.get(Calendar.YEAR)); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("clasaId", nClasaId); outState.putString("data", nData); outState.putString("materie", sMaterie); outState.putString("dif", sDificultate); outState.putString("prec", sPrecizari); outState.putInt("timestamp", nTimestamp); outState.putParcelableArrayList("parti", nParticipant); outState.putParcelableArrayList("partiparti", nAdapt.nVals); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { nRootView =inflater.inflate(R.layout.clasanoua_continut_frag, container, false); <<<<<<< HEAD createStudentsList(); nMaterie =(AutoCompleteTextView) nRootView.findViewById(R.id.nouClasaContinutFragMaterie); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, getBookselection()); nMaterie.setAdapter(adapter); ======= creeazaPartiList(); nMaterie =(AutoCompleteTextView) nRootView.findViewById(R.id.nouClasaContinutFragMaterie); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, getMaterieSelection()); nMaterie.setAdapter(adapter); >>>>>>> 2c82b41... LNQ Button dateBtn=(Button) nRootView.findViewById(R.id.nouClasaContinutFragData); dateBtn.setText(nData); dateBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { DialogFragment newFragment = new AddDateFragment(); newFragment.show(getActivity().getFragmentManager(),"Data"); } }); Button btn=(Button) nRootView.findViewById(R.id.nouClasaContinutFragNouContinut); btn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ sMaterie = nMaterie.getText().toString(); TextView pages=(TextView) nRootView.findViewById(R.id.nouClasaContinutFragDificultate); sDificultate =pages.getText().toString(); TextView info=(TextView) nRootView.findViewById(R.id.nouClasaContinutFragPrecizari); sPrecizari =info.getText().toString(); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ ContentValues vals = new ContentValues(5); vals.put(DbContract.ClasaContinut.COLUMN_MATERIE, sMaterie); vals.put(DbContract.ClasaContinut.COLUMN_PRECIZARI, sPrecizari); vals.put(DbContract.ClasaContinut.COLUMN_FOREIGN_KEY_CLASA, nClasaId); vals.put(DbContract.ClasaContinut.COLUMN_DIFICULTATE, sDificultate); vals.put(DbContract.ClasaContinut.COLUMN_DATA, nData); vals.put(DbContract.ClasaContinut.COLUMN_TIMESTAMP, nTimestamp); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ ContentResolver resolver=getActivity().getContentResolver(); Uri returnUri=resolver.insert(DbContract.ClasaContinut.CONTENT_URI,vals); int id = Integer.parseInt(returnUri.getLastPathSegment()); if(nParticipant.size()>0) { nPartiParti = nAdapt.nVals; } for(int i = 0; i< nPartiParti.size(); i++){ vals=new ContentValues(); vals.put(DbContract.ParticipantParti.COLUMN_FOREIGN_KEY_CLASACONTINUT,id); vals.put(DbContract.ParticipantParti.COLUMN_FOREIGN_KEY_PARTICIPANT, nPartiParti.get(i).id); vals.put(DbContract.ParticipantParti.COLUMN_STATUS, nPartiParti.get(i).status); returnUri=resolver.insert(DbContract.ParticipantParti.CONTENT_URI,vals); <<<<<<< HEAD } ClasaContinutAdapt.ClasaContinutAdaptVal newVals=new ClasaContinutAdapt.ClasaContinutAdaptVal(id, nData, nTimestamp, sMaterie, sDificultate, sPrecizari); nListener.OnNewClassContent(newVals); ======= } ClasaContinutAdapt.ClasaContinutAdaptVal newVals=new ClasaContinutAdapt.ClasaContinutAdaptVal(id, nData, nTimestamp, sMaterie, sDificultate, sPrecizari); nListener.ClasaNouaContinut(newVals); >>>>>>> 2c82b41... LNQ FragmentManager fm = getActivity().getSupportFragmentManager(); fm.popBackStack(); Toast.makeText(getActivity(),getActivity().getResources().getText(R.string.continutAdaugatAlert),Toast.LENGTH_LONG).show(); } }); return nRootView; } <<<<<<< HEAD private void createStudentsList(){ if(nParticipant.size()>0) { TwoWayView studentsList = (TwoWayView) nRootView.findViewById(R.id.participantListView); nAdapt = new PartiAdapt(getActivity(), nPartiParti); studentsList.setAdapter(nAdapt); ======= private void creeazaPartiList(){ if(nParticipant.size()>0) { TwoWayView participantList = (TwoWayView) nRootView.findViewById(R.id.participantListView); nAdapt = new PartiAdapt(getActivity(), nPartiParti); participantList.setAdapter(nAdapt); >>>>>>> 2c82b41... LNQ } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { <<<<<<< HEAD nListener = (OnNewClassContentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); ======= nListener = (OnClasaNouaContinutListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + ""); >>>>>>> 2c82b41... LNQ } } @Override public void onDetach() { super.onDetach(); nListener = null; } <<<<<<< HEAD public interface OnNewClassContentListener { public void OnNewClassContent(ClasaContinutAdapt.ClasaContinutAdaptVal values); } ======= public interface OnClasaNouaContinutListener { public void ClasaNouaContinut(ClasaContinutAdapt.ClasaContinutAdaptVal values); } >>>>>>> 2c82b41... LNQ public void setDate(String date, int timestamp){ nData =date; nTimestamp =timestamp; Button dateBtn=(Button) nRootView.findViewById(R.id.nouClasaContinutFragData); dateBtn.setText(nData); } <<<<<<< HEAD private String[] getBookselection(){ ArrayList<String> books=new ArrayList<>(); ======= private String[] getMaterieSelection(){ ArrayList<String> materie=new ArrayList<>(); >>>>>>> 2c82b41... LNQ ContentResolver resolver=getActivity().getContentResolver(); Cursor cursor=resolver.query(DbContract.ClasaContinut.CONTENT_URI,null,null,null,null); cursor.moveToFirst(); while(!cursor.isAfterLast()){ <<<<<<< HEAD if(!books.contains(cursor.getString(0))) books.add(cursor.getString(0)); cursor.moveToNext(); } String[] string=new String[books.size()]; return books.toArray(string); } public static class AddDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{ int day,month,year; int timestamp; ======= if(!materie.contains(cursor.getString(0))) materie.add(cursor.getString(0)); cursor.moveToNext(); } String[] string=new String[materie.size()]; return materie.toArray(string); } public static class AddDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{ int day,month,year; int timestamp; >>>>>>> 2c82b41... LNQ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState!=null){ day=savedInstanceState.getInt("day"); month=savedInstanceState.getInt("month"); year=savedInstanceState.getInt("year"); timestamp=savedInstanceState.getInt("timestamp"); } else { final Calendar c = Calendar.getInstance(); day = c.get(Calendar.DAY_OF_MONTH); month = c.get(Calendar.MONTH); year = c.get(Calendar.YEAR); <<<<<<< HEAD } return new DatePickerDialog(getActivity(),this,year,month,day); } ======= } return new DatePickerDialog(getActivity(),this,year,month,day); } >>>>>>> 2c82b41... LNQ @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { String date=""; if(DATE_FORMAT=="EUR") date=Integer.toString(dayOfMonth)+"."+Integer.toString(monthOfYear+1)+"."+Integer.toString(year); else if(DATE_FORMAT=="US") date=Integer.toString(monthOfYear+1)+"/"+Integer.toString(dayOfMonth)+"/"+Integer.toString(year); timestamp=dayOfMonth+(monthOfYear+1)*30+year*365; <<<<<<< HEAD ((MainProfesor)getActivity()).forwardDatetoNewClassContentFragment(date,timestamp); ======= ((MainProfesor)getActivity()).forwardDatetoClasaNouaContinutFrag(date,timestamp); >>>>>>> 2c82b41... LNQ } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("day",day); outState.putInt("month",month); outState.putInt("year",year); outState.putInt("timestamp",timestamp); } } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ClasaContinutFrag.java package com.example.learnnquiz.Profesor; <<<<<<< HEAD ======= //https://github.com/lucasr/twoway-view - folosit pentru grid view-ul perspectiva profesorului >>>>>>> 2c82b41... LNQ import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.learnnquiz.R; import org.lucasr.twowayview.TwoWayView; import java.util.ArrayList; public class ClasaContinutFrag extends Fragment { <<<<<<< HEAD private static final String ARG_CLASS_ID = "clasaID"; public static final String TAG="ClasaContinutFrag"; private int mClassId; public static ClasaContinutFrag newInstance(int classId) { ClasaContinutFrag fragment = new ClasaContinutFrag(); Bundle args = new Bundle(); args.putInt(ARG_CLASS_ID, classId); ======= private static final String ARG_CLASA_ID = "clasaID"; public static final String TAG="ClasaContinutFrag"; private int nClasaid; public static ClasaContinutFrag newInstance(int clasaId) { ClasaContinutFrag fragment = new ClasaContinutFrag(); Bundle args = new Bundle(); args.putInt(ARG_CLASA_ID, clasaId); >>>>>>> 2c82b41... LNQ fragment.setArguments(args); return fragment; } public ClasaContinutFrag() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { <<<<<<< HEAD mClassId = getArguments().getInt(ARG_CLASS_ID); ======= nClasaid = getArguments().getInt(ARG_CLASA_ID); >>>>>>> 2c82b41... LNQ } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TwoWayView list=(TwoWayView)inflater.inflate(R.layout.clasa_continut_frag, container, false); ArrayList<ClasaContinutAdapt.ClasaContinutAdaptVal> values=new ArrayList<>(); <<<<<<< HEAD values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(0,"01.10.1981",13,"12-133","something special", "ceva")); values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(1,"01.10.1981",20,"12-133","something special", "ceva")); values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(2,"01.10.1981",15,"12-133","something special", "ceva")); values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(3,"01.10.1981",12,"12-133","something special", "ceva")); ======= values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(0,"03.12.1999",13,"12-133","altceva", "ceva")); values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(1,"03.12.1999",20,"12-133","altceva", "ceva")); values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(2,"03.12.1999",15,"12-133","altceva", "ceva")); values.add(new ClasaContinutAdapt.ClasaContinutAdaptVal(3,"03.12.1999",12,"12-133","altceva", "ceva")); >>>>>>> 2c82b41... LNQ ClasaContinutAdapt adapter=new ClasaContinutAdapt(getActivity(),values); list.setAdapter(adapter); return list; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ParticipantFrag.java package com.example.learnnquiz.Profesor; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import com.example.learnnquiz.R; public class ParticipantFrag extends Fragment { public static final String ARG_CLASA_ID ="clasaId"; public static final String TAG="ParticipantFrag"; int nClasaId; ListView nParticipantList; <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ public static ParticipantFrag newInstance(int param_clasaID) { ParticipantFrag fragment = new ParticipantFrag(); Bundle args = new Bundle(); args.putInt(ARG_CLASA_ID, param_clasaID); fragment.setArguments(args); return fragment; } <<<<<<< HEAD public ParticipantFrag() { } ======= public ParticipantFrag() { } >>>>>>> 2c82b41... LNQ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); nClasaId = getArguments().getInt(ARG_CLASA_ID); setHasOptionsMenu(true); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView= inflater.inflate(R.layout.participant_frag, container, false); nParticipantList = (ListView)rootView.findViewById(R.id.participantListView); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ ArrayList<ParticipantAdapt.ParticipantAdaptVal> vals=getData(); if(vals==null) Toast.makeText(getActivity(),"Clasa goala",Toast.LENGTH_LONG).show(); else { ParticipantAdapt adapter = new ParticipantAdapt(getActivity(), vals); nParticipantList.setAdapter(adapter); } return rootView; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); inflater.inflate(R.menu.menu_participant,menu); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch(id) { <<<<<<< HEAD case R.id.addStudent: Fragment newStudentFragment= ParticipantNouFrag.newInstance(nClasaId); FragmentTransaction transaction=getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentContainer,newStudentFragment); ======= case R.id.adaugaParticipant: Fragment nouParticipantFrag= ParticipantNouFrag.newInstance(nClasaId); FragmentTransaction transaction=getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentContainer,nouParticipantFrag); >>>>>>> 2c82b41... LNQ transaction.addToBackStack(null); transaction.commit(); break; } return super.onOptionsItemSelected(item); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ public void updateAdapter(ParticipantAdapt.ParticipantAdaptVal vals, int position){ ParticipantAdapt adapter=(ParticipantAdapt) nParticipantList.getAdapter(); adapter.remove(position); adapter.add(vals); adapter.notifyDataSetChanged(); } <<<<<<< HEAD private ArrayList<ParticipantAdapt.ParticipantAdaptVal> getData(){ ArrayList<ParticipantAdapt.ParticipantAdaptVal> vals=new ArrayList<>(); ======= private ArrayList<ParticipantAdapt.ParticipantAdaptVal> getData(){ ArrayList<ParticipantAdapt.ParticipantAdaptVal> vals=new ArrayList<>(); >>>>>>> 2c82b41... LNQ ContentResolver resolver=getActivity().getContentResolver(); Uri uri= DbContract.Participant.CONTENT_URI_WITH_FOREIGNKEY.buildUpon().appendPath(Integer.toString(nClasaId)).build(); Cursor cursor=resolver.query(uri,null,null,null,null); cursor.moveToFirst(); while(!cursor.isAfterLast()){ vals.add(new ParticipantAdapt.ParticipantAdaptVal(cursor.getInt(0),cursor.getString(1),cursor.getString(2))); cursor.moveToNext(); } return vals; } } <file_sep>/app/src/main/java/com/example/learnnquiz/Preferinte.java package com.example.learnnquiz; public class Preferinte { <<<<<<< HEAD public static final String[] LEVELS = {"Incepator", "Amator", "Expert", "Profesionist"}; public static final int[] BOUNDARIES = {0, 100, 250, 500, 1000}; ======= public static final String[] NIVEL = {"Începător", "Amator", "Expert", "Profesionist"}; public static final int[] PUNCTAJE = {0,50, 75, 150, 175, 250}; >>>>>>> 2c82b41... LNQ } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ClasaAdapt.java package com.example.learnnquiz.Profesor; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.learnnquiz.R; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class ClasaAdapt extends ArrayAdapter { private final Context context; private final ArrayList<ClasaAdaptVal> val; public ClasaAdapt(Context context, ArrayList<ClasaAdaptVal> val) { super(context, R.layout.clasa_item, val); this.context = context; this.val = val; <<<<<<< HEAD Collections.sort(val,new ClassAdapterValuesTimeComparator()); ======= Collections.sort(val,new ClasaAdaptValTimeComparator()); >>>>>>> 2c82b41... LNQ } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.clasa_item, parent, false); TextView titlu = (TextView) rowView.findViewById(R.id.clasatitlu); titlu.setText(val.get(position).titlu); TextView startTime = (TextView) rowView.findViewById(R.id.clasaInceput); startTime.setText(val.get(position).startTime); TextView endTime = (TextView) rowView.findViewById(R.id.clasaSfarsit); endTime.setText(val.get(position).endTime); return rowView; } public void remove(int position){ val.remove(position); this.notifyDataSetChanged(); } @Override public void notifyDataSetChanged() { <<<<<<< HEAD Collections.sort(val,new ClassAdapterValuesTimeComparator()); ======= Collections.sort(val,new ClasaAdaptValTimeComparator()); >>>>>>> 2c82b41... LNQ super.notifyDataSetChanged(); } static class ClasaAdaptVal implements Parcelable{ String titlu; String startTime; String endTime; int _id; public ClasaAdaptVal(String titlu, String startTime, String endTime, int _id){ this._id=_id; this.startTime=startTime; this.endTime=endTime; this.titlu = titlu; } private ClasaAdaptVal(Parcel in){ titlu =in.readString(); startTime=in.readString(); endTime=in.readString(); _id=in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(titlu); dest.writeString(startTime); dest.writeString(endTime); dest.writeInt(_id); } public static final Parcelable.Creator<ClasaAdaptVal> CREATOR = new Parcelable.Creator<ClasaAdaptVal>() { public ClasaAdaptVal createFromParcel(Parcel in) { return new ClasaAdaptVal(in); } public ClasaAdaptVal[] newArray(int size) { return new ClasaAdaptVal[size]; } }; } <<<<<<< HEAD class ClassAdapterValuesTimeComparator implements Comparator<ClasaAdaptVal> { ======= class ClasaAdaptValTimeComparator implements Comparator<ClasaAdaptVal> { >>>>>>> 2c82b41... LNQ @Override public int compare(ClasaAdaptVal lhs, ClasaAdaptVal rhs) { int hour1=Integer.parseInt(lhs.startTime.substring(0,2)); int hour2=Integer.parseInt(rhs.startTime.substring(0,2)); return hour1-hour2; } } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ModifClasaContinutFrag.java package com.example.learnnquiz.Profesor; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.DialogInterface; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.lucasr.twowayview.TwoWayView; import java.util.ArrayList; import com.example.learnnquiz.R; public class ModifClasaContinutFrag extends Fragment { public static final String TAG="ModifClasaContinutFrag"; <<<<<<< HEAD public static String DATE_FORMAT = "EUR"; ======= public static String DATE_FORMAT = "EUR"; >>>>>>> 2c82b41... LNQ private static final String ARG_DATA = "data"; private static final String ARG_DIFICULTATE = "dif"; private static final String ARG_MATERIE = "mat"; private static final String ARG_PRECIZARI = "prec"; private static final String ARG_ID = "clasaId"; private static final String ARG_TIMESTAMP = "timestamp"; <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private String nSData; private String nSMaterie; private String nSDificultate; private String nSPrecizari; private int nId, nTimestamp; <<<<<<< HEAD private View nRootView; private TextView nData, nDificultate, nPrecizari; private AutoCompleteTextView nMaterie; private PartiAdapt nAdapt; private ArrayList<PartiAdapt.PartiAdaptVal> nPartiparti; private OnUpdateClassContentListener nListener; ======= private View nRootView; private TextView nData, nDificultate, nPrecizari; private AutoCompleteTextView nMaterie; private PartiAdapt nAdapt; private ArrayList<PartiAdapt.PartiAdaptVal> nPartiparti; private OnModifClasaContinutListener nListener; >>>>>>> 2c82b41... LNQ public static ModifClasaContinutFrag newInstance(String data, String materie, String dificultate, String precizari, int id, int timestamp) { ModifClasaContinutFrag fragment = new ModifClasaContinutFrag(); Bundle args = new Bundle(); args.putString(ARG_DATA,data); args.putString(ARG_DIFICULTATE, dificultate); args.putString(ARG_MATERIE, materie); args.putString(ARG_PRECIZARI, precizari); args.putInt(ARG_ID, id); args.putInt(ARG_TIMESTAMP,timestamp); <<<<<<< HEAD fragment.setArguments(args); return fragment; } public ModifClasaContinutFrag() { ======= fragment.setArguments(args); return fragment; } public ModifClasaContinutFrag() { >>>>>>> 2c82b41... LNQ } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState!=null){ nSData = savedInstanceState.getString("data"); nSMaterie = savedInstanceState.getString("mat"); nSDificultate = savedInstanceState.getString("dif"); nSPrecizari = savedInstanceState.getString("prec"); nId = savedInstanceState.getInt("id"); nPartiparti =savedInstanceState.getParcelableArrayList("partiparti"); } else if (getArguments() != null) { nSData = getArguments().getString(ARG_DATA); nSMaterie = getArguments().getString(ARG_MATERIE); nSDificultate = getArguments().getString(ARG_DIFICULTATE); nSPrecizari = getArguments().getString(ARG_PRECIZARI); nId = getArguments().getInt(ARG_ID); nTimestamp = getArguments().getInt(ARG_TIMESTAMP); getData(); } } private void getData() { nPartiparti =new ArrayList<>(); ContentResolver resolver=getActivity().getContentResolver(); Uri uri= DbContract.ParticipantParti.CONTENT_URI_WITH_CLASACONTINUTKEY.buildUpon().appendPath(Integer.toString(nId)).build(); Cursor cursor=resolver.query(uri,null,null,null,null); cursor.moveToFirst(); while(!cursor.isAfterLast()){ int id=cursor.getInt(1); String status=cursor.getString(2); String name=cursor.getString(3); nPartiparti.add(new PartiAdapt.PartiAdaptVal(id,name,status)); cursor.moveToNext(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("data", nSData); outState.putString("mat", nSMaterie); outState.putString("dif", nSDificultate); outState.putString("prec", nSPrecizari); outState.putInt("id", nId); outState.putParcelableArrayList("partiparti", nAdapt.nVals); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { nRootView = inflater.inflate(R.layout.modif_clasacontinut_frag, container, false); nData = (TextView) nRootView.findViewById(R.id.modifClasaContinutFragNouData); nData.setText(nSData); nMaterie = (AutoCompleteTextView) nRootView.findViewById(R.id.modifClasaContinutFragNouMaterie); nMaterie.setText(nSMaterie); <<<<<<< HEAD ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, getBookselection()); ======= ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, getMaterieSelection()); >>>>>>> 2c82b41... LNQ nMaterie.setAdapter(adapter); nDificultate = (TextView) nRootView.findViewById(R.id.modifClasaContinutFragNouDificultate); nDificultate.setText(nSDificultate); nPrecizari = (TextView) nRootView.findViewById(R.id.modifClasaContinutFragNouPrecizari); nPrecizari.setText(nSPrecizari); <<<<<<< HEAD TwoWayView studentsList = (TwoWayView) nRootView.findViewById(R.id.participantListView); nAdapt = new PartiAdapt(getActivity(), nPartiparti); studentsList.setAdapter(nAdapt); Button updateBtn = (Button) nRootView.findViewById(R.id.modifClasaContinutFragNouModif); updateBtn.setOnClickListener(new Button.OnClickListener() { @SuppressLint("LongLogTag") ======= TwoWayView participantList = (TwoWayView) nRootView.findViewById(R.id.participantListView); nAdapt = new PartiAdapt(getActivity(), nPartiparti); participantList.setAdapter(nAdapt); Button updateBtn = (Button) nRootView.findViewById(R.id.modifClasaContinutFragNouModif); updateBtn.setOnClickListener(new Button.OnClickListener() { @SuppressLint("") >>>>>>> 2c82b41... LNQ @Override public void onClick(View v) { nSData = nData.getText().toString(); nSMaterie = nMaterie.getText().toString(); nSDificultate = nDificultate.getText().toString(); nSPrecizari = nPrecizari.getText().toString(); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ if (DATE_FORMAT == "EUR") { try { int dividerPos = nSData.indexOf("."); int day = Integer.parseInt(nSData.substring(0, dividerPos)); String sub = nSData.substring(dividerPos + 1); dividerPos = sub.indexOf("."); int month = Integer.parseInt(sub.substring(0, dividerPos)); int year = Integer.parseInt(sub.substring(dividerPos + 1)); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ nTimestamp =day+month*30+year*365; }catch(Exception e){} } else if (DATE_FORMAT == "US"){ try { int dividerPos = nSData.indexOf("/"); int month = Integer.parseInt(nSData.substring(0, dividerPos)); String sub = nSData.substring(dividerPos + 1); dividerPos = sub.indexOf("/"); int day = Integer.parseInt(sub.substring(0, dividerPos)); int year = Integer.parseInt(sub.substring(dividerPos + 1)); nTimestamp =day+month*30+year*365; }catch(Exception e){} } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ ContentValues vals = new ContentValues(4); vals.put(DbContract.ClasaContinut.COLUMN_MATERIE, nSMaterie); vals.put(DbContract.ClasaContinut.COLUMN_PRECIZARI, nSPrecizari); vals.put(DbContract.ClasaContinut.COLUMN_DIFICULTATE, nSDificultate); vals.put(DbContract.ClasaContinut.COLUMN_DATA, nSData); vals.put(DbContract.ClasaContinut.COLUMN_TIMESTAMP, nTimestamp); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ Uri uri = DbContract.ClasaContinut.CONTENT_URI.buildUpon().appendPath(Integer.toString(nId)).build(); ContentResolver resolver = getActivity().getContentResolver(); if (resolver.update(uri, vals, DbContract.ClasaContinut._ID + " = ?", new String[]{Integer.toString(nId)}) > 0) { nPartiparti = nAdapt.nVals; for (int i = 0; i < nPartiparti.size(); i++) { uri = DbContract.ParticipantParti.CONTENT_URI_WITH_PARTICIPANTKEY.buildUpon().appendPath(Integer.toString(nId)).build(); vals = new ContentValues(); vals.put(DbContract.ParticipantParti.COLUMN_STATUS, nPartiparti.get(i).status); resolver.update(uri, vals, DbContract.ParticipantParti.COLUMN_FOREIGN_KEY_PARTICIPANT + " =? and " + DbContract.ParticipantParti.COLUMN_FOREIGN_KEY_CLASACONTINUT +" =?", new String[]{Integer.toString(nPartiparti.get(i).id),Integer.toString(nId)}); } ClasaContinutAdapt.ClasaContinutAdaptVal updatedObj = new ClasaContinutAdapt.ClasaContinutAdaptVal(nId, nSData, nTimestamp, nSMaterie, nSDificultate, nSPrecizari); <<<<<<< HEAD nListener.OnUpdateClassContent(updatedObj); ======= nListener.OnModifClasaContinut(updatedObj); >>>>>>> 2c82b41... LNQ FragmentManager fm = getActivity().getSupportFragmentManager(); fm.popBackStack(); Toast.makeText(getActivity(), getActivity().getResources().getText(R.string.continutModificatAlert), Toast.LENGTH_LONG).show(); } } }); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ Button deleteBtn = (Button) nRootView.findViewById(R.id.modifClasaContinutFragSterge); deleteBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { showAlertDialog(); } }); return nRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { <<<<<<< HEAD nListener = (OnUpdateClassContentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnUpdateClassContentListener"); ======= nListener = (OnModifClasaContinutListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " "); >>>>>>> 2c82b41... LNQ } } @Override public void onDetach() { super.onDetach(); nListener = null; } <<<<<<< HEAD public interface OnUpdateClassContentListener { public void OnUpdateClassContent(ClasaContinutAdapt.ClasaContinutAdaptVal updatedObj); public void onDeleteClassContent(ClasaContinutAdapt.ClasaContinutAdaptVal deletedObj); } private String[] getBookselection(){ ArrayList<String> books=new ArrayList<>(); ======= public interface OnModifClasaContinutListener { public void OnModifClasaContinut(ClasaContinutAdapt.ClasaContinutAdaptVal updatedObj); public void onStergeClasaContinut(ClasaContinutAdapt.ClasaContinutAdaptVal deletedObj); } private String[] getMaterieSelection(){ ArrayList<String> materie=new ArrayList<>(); >>>>>>> 2c82b41... LNQ ContentResolver resolver=getActivity().getContentResolver(); Cursor cursor=resolver.query(DbContract.ClasaContinut.CONTENT_URI,null,null,null,null); cursor.moveToFirst(); while(!cursor.isAfterLast()){ <<<<<<< HEAD if(!books.contains(cursor.getString(0))) books.add(cursor.getString(0)); cursor.moveToNext(); } String[] string=new String[books.size()]; return books.toArray(string); } private void showAlertDialog(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.getActivity()); alertDialogBuilder.setTitle(this.getActivity().getResources().getString(R.string.stergecontinut)); ======= if(!materie.contains(cursor.getString(0))) materie.add(cursor.getString(0)); cursor.moveToNext(); } String[] string=new String[materie.size()]; return materie.toArray(string); } private void showAlertDialog(){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.getActivity()); alertDialogBuilder.setTitle(this.getActivity().getResources().getString(R.string.stergecontinut)); >>>>>>> 2c82b41... LNQ alertDialogBuilder .setCancelable(true) .setPositiveButton(this.getActivity().getResources().getString(R.string.stergecontinut),new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { <<<<<<< HEAD Uri uri = DbContract.ClasaContinut.CONTENT_URI.buildUpon().appendPath(Integer.toString(nId)).build(); ContentResolver resolver = getActivity().getContentResolver(); if (resolver.delete(uri, DbContract.ClasaContinut._ID + " = ?", new String[]{Integer.toString(nId)}) > 0) { uri = DbContract.ParticipantParti.CONTENT_URI_WITH_CLASACONTINUTKEY.buildUpon().appendPath(Integer.toString(nId)).build(); resolver.delete(uri, null, null); ClasaContinutAdapt.ClasaContinutAdaptVal deletedObj = new ClasaContinutAdapt.ClasaContinutAdaptVal(nId, nSData, nTimestamp, nSMaterie, nSDificultate, nSPrecizari); nListener.onDeleteClassContent(deletedObj); ======= Uri uri = DbContract.ClasaContinut.CONTENT_URI.buildUpon().appendPath(Integer.toString(nId)).build(); ContentResolver resolver = getActivity().getContentResolver(); if (resolver.delete(uri, DbContract.ClasaContinut._ID + " = ?", new String[]{Integer.toString(nId)}) > 0) { uri = DbContract.ParticipantParti.CONTENT_URI_WITH_CLASACONTINUTKEY.buildUpon().appendPath(Integer.toString(nId)).build(); resolver.delete(uri, null, null); ClasaContinutAdapt.ClasaContinutAdaptVal deletedObj = new ClasaContinutAdapt.ClasaContinutAdaptVal(nId, nSData, nTimestamp, nSMaterie, nSDificultate, nSPrecizari); nListener.onStergeClasaContinut(deletedObj); >>>>>>> 2c82b41... LNQ FragmentManager fm = getActivity().getSupportFragmentManager(); fm.popBackStack(); Toast.makeText(getActivity(), getActivity().getResources().getText(R.string.continutStersAlert), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton(this.getActivity().getResources().getString(R.string.cancel),new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { <<<<<<< HEAD dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); ======= dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); >>>>>>> 2c82b41... LNQ alertDialog.show(); } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/PartiAdapt.java package com.example.learnnquiz.Profesor; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import com.example.learnnquiz.R; import java.util.ArrayList; public class PartiAdapt extends ArrayAdapter { ArrayList<PartiAdaptVal> nVals; private final Context context; <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ public PartiAdapt(Context context, ArrayList<PartiAdaptVal> values) { super(context, R.layout.participant_parti_item,values); this.nVals =values; this.context=context; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); <<<<<<< HEAD View rowView = inflater.inflate(R.layout.participant_parti_item, parent, false); TextView name=(TextView)rowView.findViewById(R.id.parti_participantNume); name.setText(nVals.get(position).nume); final int listPos=position; Spinner spinner=(Spinner)rowView.findViewById(R.id.statusSpinner); ArrayAdapter<CharSequence>attendanceAdapter= ArrayAdapter.createFromResource(context,R.array.status,android.R.layout.simple_spinner_item); attendanceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(attendanceAdapter); ======= View rowView = inflater.inflate(R.layout.participant_parti_item, parent, false); TextView name=(TextView)rowView.findViewById(R.id.parti_participantNume); name.setText(nVals.get(position).nume); final int listPos=position; Spinner spinner=(Spinner)rowView.findViewById(R.id.statusSpinner); ArrayAdapter<CharSequence>statusAdapter= ArrayAdapter.createFromResource(context,R.array.status,android.R.layout.simple_spinner_item); statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(statusAdapter); >>>>>>> 2c82b41... LNQ for(int i=0;i<spinner.getCount();i++) { String spinnerVal=(String)spinner.getItemAtPosition(i); if (spinnerVal.contains(nVals.get(position).status)) { spinner.setSelection(i); break; } } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { nVals.set(listPos,new PartiAdaptVal(nVals.get(listPos).id, nVals.get(listPos).nume,parent.getItemAtPosition(position).toString())); } <<<<<<< HEAD @Override public void onNothingSelected(AdapterView<?> parent) { ======= @Override public void onNothingSelected(AdapterView<?> parent) { >>>>>>> 2c82b41... LNQ } }); return rowView; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ static class PartiAdaptVal implements Parcelable { int id; String nume; String status; <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ public PartiAdaptVal(int id, String nume, String status){ this.id=id; this.nume = nume; this.status=status; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ private PartiAdaptVal(Parcel in){ id=in.readInt(); nume =in.readString(); status=in.readString(); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public int describeContents() { return 0; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(nume); dest.writeString(status); } public static final Parcelable.Creator<PartiAdaptVal> CREATOR = new Parcelable.Creator<PartiAdaptVal>() { public PartiAdaptVal createFromParcel(Parcel in) { return new PartiAdaptVal(in); } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ public PartiAdaptVal[] newArray(int size) { return new PartiAdaptVal[size]; } }; } } <file_sep>/app/src/main/java/com/example/learnnquiz/Adapt/ListaCurs.java package com.example.learnnquiz.Adapt; import android.content.Context; import android.support.v17.leanback.widget.HorizontalGridView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.learnnquiz.R; import com.example.learnnquiz.Obiecte.Curs; import java.util.List; public class ListaCurs extends BaseAdapter { private final Context context; private final List<Curs> curs; public ListaCurs(Context context, List<Curs> curs) { this.context = context; this.curs = curs; } @Override public int getCount() { return curs.size(); } @Override public Object getItem(int position) { return curs.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.curs, parent, false); TextView Titlucurstextview = view.findViewById(R.id.titlu_curs); Titlucurstextview.setText(curs.get(position).getTitlu()); ListaLectie lectieAdapter = new ListaLectie(context, curs.get(position).getLectie(), curs.get(position).getId()); HorizontalGridView lectieView = view.findViewById(R.id.gridlectie); lectieView.setAdapter(lectieAdapter); return view; } }<file_sep>/app/src/main/java/com/example/learnnquiz/activitati/Sectiuni.java package com.example.learnnquiz.Activitati; import android.content.Intent; import android.media.Image; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.learnnquiz.LNQDB; import com.example.learnnquiz.R; import com.example.learnnquiz.Obiecte.Sectiune; public class Sectiuni extends AppCompatActivity { TextView pagtextview; ImageView inapoiBt; ImageView inainteBt; ImageView inchideBt; ImageView skipbt; TextView Titlusectiunetextview; ImageView imaginesectiune; TextView Textsectiunetextview; Sectiune sectiune; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sectiune); Intent intent = getIntent(); final int lectieid = intent.getIntExtra("lectieid", 0); final int nrsectiune = intent.getIntExtra("nrsectiune", 0); LNQDB lnqdb = LNQDB.getInstance(this); sectiune = lnqdb.getSectiune(lectieid, nrsectiune); pagtextview = findViewById(R.id.pag); inapoiBt = findViewById(R.id.inapoi); inainteBt = findViewById(R.id.inainte); inchideBt = findViewById(R.id.inchidebt); skipbt=findViewById(R.id.skipbt); Titlusectiunetextview = findViewById(R.id.titlusectiune); imaginesectiune=findViewById(R.id.imaginesectiune); Textsectiunetextview = findViewById(R.id.textsectiune); Titlusectiunetextview.setText(sectiune.getTitlu()); Textsectiunetextview.setText(sectiune.getText()); String numeimg = "s" + lectieid + nrsectiune; imaginesectiune.setImageResource(getResources().getIdentifier(numeimg, "drawable", getPackageName())); Textsectiunetextview.setText(sectiune.getText()); String pag = sectiune.getTitlulectie() + " " + (nrsectiune + 1) + "/" + sectiune.getSectiunelectie(); pagtextview.setText(pag); skipbt.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { if(nrsectiune<sectiune.getSectiunelectie()-1){ startQuiz(lectieid); } } }); inchideBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Sectiuni.this, Acasa.class); startActivity(intent); } }); if(nrsectiune == 0){ inapoiBt.setVisibility(View.GONE); } else { inapoiBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SchimbaSectiune(lectieid, nrsectiune-1); } }); } inainteBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(nrsectiune<sectiune.getSectiunelectie()-1){ SchimbaSectiune(lectieid, nrsectiune+1); } else { startQuiz(lectieid); } } }); } void SchimbaSectiune(int lectieid, int nrsectiune){ Intent intent = new Intent(Sectiuni.this, Sectiuni.class); intent.putExtra("nrsectiune", nrsectiune); intent.putExtra("lectieid", lectieid); startActivity(intent); } void startQuiz(int lectieid){ Intent intent = new Intent(Sectiuni.this, com.example.learnnquiz.Activitati.Testare.class); intent.putExtra("lectieid", lectieid); startActivity(intent); } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ClasaContinutProv.java package com.example.learnnquiz.Profesor; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; <<<<<<< HEAD import android.util.Log; ======= >>>>>>> 2c82b41... LNQ import static com.example.learnnquiz.Profesor.DbContract.*; public class ClasaContinutProv extends ContentProvider { private static final int CLASA =1; private static final int CLASA_ID =2; <<<<<<< HEAD private static final int CLASA_ZI_TITLU_ORA_ID =101; private static final int PARTICIPANT =3; private static final int PARTICIPANT_ID =4; private static final int PARTICIPANT_CLASA_ID =401; private static final int CLASACONTINUT =5; private static final int CLASACONTINUT_ID =6; private static final int CLASACONTINUT_CLASA_ID =601; private static final int PARTICIPANTPARTI =7; private static final int PARTICIPANTPARTI_ID =8; private static final int PARTICIPANTPARTI_PARTICIPANT_ID =801; private static final int PARTICIPANTPARTI_CLASACONTINUT_ID =802; private static final UriMatcher mUriMatcher=new UriMatcher(UriMatcher.NO_MATCH); static { mUriMatcher.addURI(AUTHORITY, PATH_CLASA, CLASA); mUriMatcher.addURI(AUTHORITY, PATH_CLASA +"/#", CLASA_ID); mUriMatcher.addURI(AUTHORITY,"CLASA_ZI_TITLU_ORA_ID", CLASA_ZI_TITLU_ORA_ID); mUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT, PARTICIPANT); mUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT +"/#", PARTICIPANT_ID); mUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_WITH_FOREIGNKEY +"/#", PARTICIPANT_CLASA_ID); mUriMatcher.addURI(AUTHORITY, PATH_CLASACONTINUT, CLASACONTINUT); mUriMatcher.addURI(AUTHORITY, PATH_CLASACONTINUT +"/#", CLASACONTINUT_ID); mUriMatcher.addURI(AUTHORITY, PATH_CLASACONTINUT_WITH_FOREIGNKEY +"/#", CLASACONTINUT_CLASA_ID); mUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_PARTI, PARTICIPANTPARTI); mUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_PARTI_WITH_CLASACONTINUT_ID +"/#", PARTICIPANTPARTI_CLASACONTINUT_ID); mUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_PARTI_WITH_PARTI_ID +"/#", PARTICIPANTPARTI_PARTICIPANT_ID); } SQLiteDatabase mdataBase; ======= private static final int CLASA_ZI_TITLU_ORA_ID =11; private static final int PARTICIPANT =3; private static final int PARTICIPANT_ID =4; private static final int PARTICIPANT_CLASA_ID =41; private static final int CLASACONTINUT =5; private static final int CLASACONTINUT_ID =6; private static final int CLASACONTINUT_CLASA_ID =61; private static final int PARTICIPANTPARTI =7; private static final int PARTICIPANTPARTI_ID =8; private static final int PARTICIPANTPARTI_PARTICIPANT_ID =81; private static final int PARTICIPANTPARTI_CLASACONTINUT_ID =82; private static final UriMatcher nUriMatcher =new UriMatcher(UriMatcher.NO_MATCH); static { nUriMatcher.addURI(AUTHORITY, PATH_CLASA, CLASA); nUriMatcher.addURI(AUTHORITY, PATH_CLASA +"/#", CLASA_ID); nUriMatcher.addURI(AUTHORITY,"CLASA_ZI_TITLU_ORA_ID", CLASA_ZI_TITLU_ORA_ID); nUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT, PARTICIPANT); nUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT +"/#", PARTICIPANT_ID); nUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_WITH_FOREIGNKEY +"/#", PARTICIPANT_CLASA_ID); nUriMatcher.addURI(AUTHORITY, PATH_CLASACONTINUT, CLASACONTINUT); nUriMatcher.addURI(AUTHORITY, PATH_CLASACONTINUT +"/#", CLASACONTINUT_ID); nUriMatcher.addURI(AUTHORITY, PATH_CLASACONTINUT_WITH_FOREIGNKEY +"/#", CLASACONTINUT_CLASA_ID); nUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_PARTI, PARTICIPANTPARTI); nUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_PARTI_WITH_CLASACONTINUT_ID +"/#", PARTICIPANTPARTI_CLASACONTINUT_ID); nUriMatcher.addURI(AUTHORITY, PATH_PARTICIPANT_PARTI_WITH_PARTI_ID +"/#", PARTICIPANTPARTI_PARTICIPANT_ID); } SQLiteDatabase ndataBase; >>>>>>> 2c82b41... LNQ @Override public boolean onCreate() { return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { <<<<<<< HEAD mdataBase=new DbHelper(getContext()).getReadableDatabase(); Cursor cursor=null; switch(mUriMatcher.match(uri)) { case CLASA: cursor=mdataBase.query(Clasa.TABLE_NAME, new String[]{Clasa._ID, ======= ndataBase =new DbHelper(getContext()).getReadableDatabase(); Cursor cursor=null; switch(nUriMatcher.match(uri)) { case CLASA: cursor= ndataBase.query(Clasa.TABLE_NAME, new String[]{Clasa._ID, >>>>>>> 2c82b41... LNQ Clasa.COLUMN_TITLU, Clasa.COLUMN_METODA},null,null, null, null, null); break; case CLASA_ID: String id=uri.getLastPathSegment(); <<<<<<< HEAD cursor=mdataBase.query(Clasa.TABLE_NAME, new String[]{Clasa.COLUMN_DATA, ======= cursor= ndataBase.query(Clasa.TABLE_NAME, new String[]{Clasa.COLUMN_DATA, >>>>>>> 2c82b41... LNQ Clasa.COLUMN_DURATA, Clasa.COLUMN_MENTIUNI_PARTICIPANT, Clasa.COLUMN_DIFICULTATE, Clasa.COLUMN_METODA, Clasa.COLUMN_TIMP, Clasa.COLUMN_TITLU}, Clasa._ID+" =?", new String[]{id}, null, null, null); break; case CLASA_ZI_TITLU_ORA_ID: <<<<<<< HEAD cursor = mdataBase.query(Clasa.TABLE_NAME, new String[]{ ======= cursor = ndataBase.query(Clasa.TABLE_NAME, new String[]{ >>>>>>> 2c82b41... LNQ Clasa._ID, Clasa.COLUMN_TITLU, Clasa.COLUMN_TIMP, Clasa.COLUMN_DURATA, Clasa.COLUMN_DATA}, null, null, null, null, null); break; case PARTICIPANT_CLASA_ID: <<<<<<< HEAD String classId=uri.getLastPathSegment(); cursor=mdataBase.query(Participant.TABLE_NAME, new String[]{ ======= String clasaId=uri.getLastPathSegment(); cursor= ndataBase.query(Participant.TABLE_NAME, new String[]{ >>>>>>> 2c82b41... LNQ Participant._ID, Participant.COLUMN_PARTICIPANT_NUME, Participant.COLUMN_EMAIL <<<<<<< HEAD }, Participant.COLUMN_FOREIGN_KEY_CLASA +" =?", new String[]{classId}, null, null, null); break; case CLASACONTINUT: cursor=mdataBase.query(ClasaContinut.TABLE_NAME,new String[]{ ======= }, Participant.COLUMN_FOREIGN_KEY_CLASA +" =?", new String[]{clasaId}, null, null, null); break; case CLASACONTINUT: cursor= ndataBase.query(ClasaContinut.TABLE_NAME,new String[]{ >>>>>>> 2c82b41... LNQ ClasaContinut.COLUMN_MATERIE, ClasaContinut.COLUMN_DATA, ClasaContinut.COLUMN_TIMESTAMP, ClasaContinut.COLUMN_DIFICULTATE, ClasaContinut.COLUMN_PRECIZARI, ClasaContinut._ID},null,null,null,null,null); break; case CLASACONTINUT_CLASA_ID: <<<<<<< HEAD classId=uri.getLastPathSegment(); cursor=mdataBase.query(ClasaContinut.TABLE_NAME,new String[]{ ======= clasaId=uri.getLastPathSegment(); cursor= ndataBase.query(ClasaContinut.TABLE_NAME,new String[]{ >>>>>>> 2c82b41... LNQ ClasaContinut.COLUMN_MATERIE, ClasaContinut.COLUMN_DATA, ClasaContinut.COLUMN_TIMESTAMP, ClasaContinut.COLUMN_DIFICULTATE, ClasaContinut.COLUMN_PRECIZARI, <<<<<<< HEAD ClasaContinut._ID}, ClasaContinut.COLUMN_FOREIGN_KEY_CLASA +" =?",new String[]{classId},null,null, ClasaContinut.COLUMN_TIMESTAMP+" desc"); ======= ClasaContinut._ID}, ClasaContinut.COLUMN_FOREIGN_KEY_CLASA +" =?",new String[]{clasaId},null,null, ClasaContinut.COLUMN_TIMESTAMP+" desc"); >>>>>>> 2c82b41... LNQ break; case PARTICIPANTPARTI_CLASACONTINUT_ID: String clasaContinutId=uri.getLastPathSegment(); String query="Select "+ ParticipantParti.TABLE_NAME+"."+ ParticipantParti._ID+"," + ParticipantParti.TABLE_NAME+"."+ ParticipantParti.COLUMN_FOREIGN_KEY_PARTICIPANT +"," + ParticipantParti.TABLE_NAME+"."+ ParticipantParti.COLUMN_STATUS+"," + Participant.TABLE_NAME+"."+ Participant.COLUMN_PARTICIPANT_NUME <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ +" from "+ ParticipantParti.TABLE_NAME+" inner join "+ Participant.TABLE_NAME+" on " + ParticipantParti.TABLE_NAME+"."+ ParticipantParti.COLUMN_FOREIGN_KEY_PARTICIPANT +" = " + Participant.TABLE_NAME+"."+ Participant._ID+" where " + ParticipantParti.TABLE_NAME+"."+ ParticipantParti.COLUMN_FOREIGN_KEY_CLASACONTINUT +" = "+clasaContinutId+";"; <<<<<<< HEAD cursor=mdataBase.rawQuery(query,null); break; default: throw new IllegalArgumentException("Unknown URI " + uri); ======= cursor= ndataBase.rawQuery(query,null); break; >>>>>>> 2c82b41... LNQ } return cursor; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { ContentValues vals=values; if(vals==null) return null; String table=""; <<<<<<< HEAD mdataBase=new DbHelper(getContext()).getWritableDatabase(); switch(mUriMatcher.match(uri)) { ======= ndataBase =new DbHelper(getContext()).getWritableDatabase(); switch(nUriMatcher.match(uri)) { >>>>>>> 2c82b41... LNQ case CLASA: table= Clasa.TABLE_NAME; break; case PARTICIPANT: table= Participant.TABLE_NAME; break; case CLASACONTINUT: table= ClasaContinut.TABLE_NAME; break; case PARTICIPANTPARTI: table= ParticipantParti.TABLE_NAME; break; <<<<<<< HEAD default: throw new IllegalArgumentException("Unknown URI " + uri); } long rowId=mdataBase.insert(table,null,values); ======= } long rowId= ndataBase.insert(table,null,values); >>>>>>> 2c82b41... LNQ Uri noteUri=null; if(rowId>0) noteUri= ContentUris.withAppendedId(uri,rowId); return noteUri; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int affectedRows=0; <<<<<<< HEAD switch(mUriMatcher.match(uri)) { case CLASA_ID: String id=uri.getLastPathSegment(); mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.delete(Clasa.TABLE_NAME, Clasa._ID+"=?",new String[]{id}); ======= switch(nUriMatcher.match(uri)) { case CLASA_ID: String id=uri.getLastPathSegment(); ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.delete(Clasa.TABLE_NAME, Clasa._ID+"=?",new String[]{id}); >>>>>>> 2c82b41... LNQ break; case PARTICIPANT: break; case PARTICIPANT_ID: id=uri.getLastPathSegment(); <<<<<<< HEAD mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.delete(Participant.TABLE_NAME, Participant._ID+"=?",new String[]{id}); ======= ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.delete(Participant.TABLE_NAME, Participant._ID+"=?",new String[]{id}); >>>>>>> 2c82b41... LNQ break; case CLASACONTINUT: break; case CLASACONTINUT_ID: <<<<<<< HEAD String classId=uri.getLastPathSegment(); mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.delete(ClasaContinut.TABLE_NAME,selection,selectionArgs); break; case PARTICIPANTPARTI_PARTICIPANT_ID: String participantId=uri.getLastPathSegment(); mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.delete(ParticipantParti.TABLE_NAME, ParticipantParti.COLUMN_FOREIGN_KEY_PARTICIPANT +"=?",new String[]{participantId}); break; case PARTICIPANTPARTI_CLASACONTINUT_ID: String clasaContinutId=uri.getLastPathSegment(); mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.delete(ParticipantParti.TABLE_NAME, ParticipantParti.COLUMN_FOREIGN_KEY_CLASACONTINUT +"=?",new String[]{clasaContinutId}); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } return affectedRows; } ======= String clasaId=uri.getLastPathSegment(); ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.delete(ClasaContinut.TABLE_NAME,selection,selectionArgs); break; case PARTICIPANTPARTI_PARTICIPANT_ID: String participantId=uri.getLastPathSegment(); ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.delete(ParticipantParti.TABLE_NAME, ParticipantParti.COLUMN_FOREIGN_KEY_PARTICIPANT +"=?",new String[]{participantId}); break; case PARTICIPANTPARTI_CLASACONTINUT_ID: String clasaContinutId=uri.getLastPathSegment(); ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.delete(ParticipantParti.TABLE_NAME, ParticipantParti.COLUMN_FOREIGN_KEY_CLASACONTINUT +"=?",new String[]{clasaContinutId}); break; } return affectedRows; } >>>>>>> 2c82b41... LNQ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { String id=""; int affectedRows=0; <<<<<<< HEAD switch(mUriMatcher.match(uri)) { case CLASA_ID: id=uri.getLastPathSegment(); mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.update(Clasa.TABLE_NAME,values, Clasa._ID+" = ?",new String[]{id}); ======= switch(nUriMatcher.match(uri)) { case CLASA_ID: id=uri.getLastPathSegment(); ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.update(Clasa.TABLE_NAME,values, Clasa._ID+" = ?",new String[]{id}); >>>>>>> 2c82b41... LNQ break; case PARTICIPANT: break; case PARTICIPANT_ID: id=uri.getLastPathSegment(); <<<<<<< HEAD mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.update(Participant.TABLE_NAME,values, Participant._ID+"=?",new String[]{id}); ======= ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.update(Participant.TABLE_NAME,values, Participant._ID+"=?",new String[]{id}); >>>>>>> 2c82b41... LNQ break; case CLASACONTINUT: break; case CLASACONTINUT_ID: <<<<<<< HEAD String classId=uri.getLastPathSegment(); mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.update(ClasaContinut.TABLE_NAME,values,selection,selectionArgs); break; case PARTICIPANTPARTI_PARTICIPANT_ID: mdataBase=new DbHelper(getContext()).getWritableDatabase(); affectedRows=mdataBase.update(ParticipantParti.TABLE_NAME,values,selection,selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); ======= String clasaId=uri.getLastPathSegment(); ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.update(ClasaContinut.TABLE_NAME,values,selection,selectionArgs); break; case PARTICIPANTPARTI_PARTICIPANT_ID: ndataBase =new DbHelper(getContext()).getWritableDatabase(); affectedRows= ndataBase.update(ParticipantParti.TABLE_NAME,values,selection,selectionArgs); break; >>>>>>> 2c82b41... LNQ } return affectedRows; } } <file_sep>/README.md # Learn-N-Quiz The chosen theme consists of an android application that was wrote using Java as the programming language, using Android Studio as the support IDE with it's tools and features. "Learn'N Quiz" has two point of views, one for the teacher that allows it to create classes and offer tasks to the student. The other view is dedicated for the student that can view the topic's section and their difficulty levels, after the student goes through the domains, it can test theirself through a mini quiz. ## Professor view ![profesorfinal](https://user-images.githubusercontent.com/72438336/127784668-162c03b0-928d-4183-b066-4c93062c503f.png) The teacher can create classes, assign tasks, add participants and be given tasks but also modify the content of class components. ## Participant view ![participantview](https://user-images.githubusercontent.com/72438336/127784673-bbcafd79-007f-48f5-b2ae-121141e5918b.png) The user has the opportunity to discover information about the physical geography of the world and the basic human anatomy. The evaluation part is in the form of a quiz that indicates the correct answers through a semaphore type system (red / green), and after testing the user can see the score and then can check the profile where he can view the progress overall and per category. ## The project includes the following technologies: • The interface is designed using XML. <br/> • The functionalities include Java and JSON.<br/> • For data storage is used SQLite .<br/> <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/MainFrag.java package com.example.learnnquiz.Profesor; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.VelocityTracker; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.lucasr.twowayview.TwoWayView; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import com.example.learnnquiz.R; public class MainFrag extends Fragment { private final String TAG="MainFrag"; View nRootView; ClasaAdapt[] nAdapt; LinearLayout[] nWeekdays; TwoWayView[] nListView; <<<<<<< HEAD private VelocityTracker nVelocityTracker = null; public MainFrag() { } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_main_fragment,menu); ======= private VelocityTracker nVelocityTracker = null; public MainFrag() { } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_main_frag,menu); >>>>>>> 2c82b41... LNQ } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); <<<<<<< HEAD if(id==R.id.addClass_setting){ Fragment newClassFragment= ClasaNouaFrag.newInstance("zi"); FragmentTransaction transaction=getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentContainer,newClassFragment, ClasaNouaFrag.TAG); ======= if(id==R.id.adaugaClasa_menu){ Fragment nouClasaFrag= ClasaNouaFrag.newInstance("zi"); FragmentTransaction transaction=getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentContainer,nouClasaFrag, ClasaNouaFrag.TAG); >>>>>>> 2c82b41... LNQ transaction.addToBackStack(null); transaction.commit(); } <<<<<<< HEAD else if (id == R.id.action_settings) { return true; } ======= >>>>>>> 2c82b41... LNQ return super.onOptionsItemSelected(item); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setHasOptionsMenu(true); this.createAdapters(savedInstanceState); nWeekdays =new LinearLayout[7]; nListView =new TwoWayView[7]; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { nRootView = inflater.inflate(R.layout.main_frag, container, false); Calendar calendar=Calendar.getInstance(); int weekDay=calendar.get(Calendar.DAY_OF_WEEK); if(weekDay==1){ LinearLayout sunday=(LinearLayout) nRootView.findViewById(R.id.duminica); sunday.setBackgroundColor(getResources().getColor(R.color.White)); } else if(weekDay==2){ LinearLayout monday=(LinearLayout) nRootView.findViewById(R.id.luni); monday.setBackgroundColor(getResources().getColor(R.color.White)); } else if(weekDay==3){ LinearLayout tuesday=(LinearLayout) nRootView.findViewById(R.id.marti); tuesday.setBackgroundColor(getResources().getColor(R.color.White)); } else if(weekDay==4){ LinearLayout wednesday=(LinearLayout) nRootView.findViewById(R.id.miercuri); wednesday.setBackgroundColor(getResources().getColor(R.color.White)); } else if(weekDay==5){ LinearLayout thursday=(LinearLayout) nRootView.findViewById(R.id.joi); thursday.setBackgroundColor(getResources().getColor(R.color.White)); } else if(weekDay==6){ LinearLayout friday=(LinearLayout) nRootView.findViewById(R.id.vineri); friday.setBackgroundColor(getResources().getColor(R.color.White)); } else if(weekDay==7){ LinearLayout saturday=(LinearLayout) nRootView.findViewById(R.id.sambata); saturday.setBackgroundColor(getResources().getColor(R.color.White)); } for (int i = 0; i < 7; i++) { if (i == 0) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.luni); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.mondayListView); } else if (i == 1) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.marti); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.tuesdayListView); } else if (i == 2) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.miercuri); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.wednesdayListView); } else if (i == 3) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.joi); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.thursdayListView); } else if (i == 4) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.vineri); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.fridayListView); } else if (i == 5) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.sambata); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.saturdayListView); } else if (i == 6) { nWeekdays[i] = (LinearLayout) nRootView.findViewById(R.id.duminica); nListView[i] = (TwoWayView) nRootView.findViewById(R.id.sundayListView); } } this.setListeners(); return nRootView; } public void onSaveInstanceState(Bundle savedState){ super.onSaveInstanceState(savedState); for (int i = 0; i < 7; i++) { try { ArrayList<ClasaAdapt.ClasaAdaptVal> values=new ArrayList<ClasaAdapt.ClasaAdaptVal>(); for (int u = 0; u < nAdapt[i].getCount(); u++) values.add((ClasaAdapt.ClasaAdaptVal) nAdapt[i].getItem(u)); savedState.putParcelableArrayList("Day"+i,values); }catch(Exception e){} } } @Override public void onPause() { super.onPause(); } private void createAdapters(Bundle savedInstanceState){ if(nAdapt ==null) { ArrayList<ClasaAdapt.ClasaAdaptVal> list = new ArrayList<ClasaAdapt.ClasaAdaptVal>(); nAdapt = new ClasaAdapt[7]; if (savedInstanceState != null) { for (int i = 0; i < 7; i++) { list = savedInstanceState.getParcelableArrayList("Day" + i); nAdapt[i] = new ClasaAdapt(getActivity(), list); } }else { ContentResolver resolver = getActivity().getContentResolver(); Cursor cursor= resolver.query(DbContract.CLASA_ZI_TITLU_ORA_ID,null, null, null, null); cursor.moveToFirst(); ArrayList<List<ClasaAdapt.ClasaAdaptVal>> listGroup= new ArrayList<List<ClasaAdapt.ClasaAdaptVal>>(7); for(int i=0;i<7;i++) { listGroup.add(new ArrayList<ClasaAdapt.ClasaAdaptVal>()); } while(!cursor.isAfterLast()){ int id=cursor.getInt(0); String title=cursor.getString(1); String startTime=cursor.getString(2); String endTime=cursor.getString(3); try { JSONObject json = new JSONObject(cursor.getString(4)); JSONArray jarr=json.optJSONArray("selectedDays"); if (jarr != null) { for (int i=0;i<jarr.length();i++){ ClasaAdapt.ClasaAdaptVal obj = new ClasaAdapt.ClasaAdaptVal(title,startTime,endTime,id); ArrayList<ClasaAdapt.ClasaAdaptVal> tempList=(ArrayList)listGroup.get(jarr.getInt(i)); tempList.add(obj); listGroup.set(jarr.getInt(i),tempList); } } }catch (JSONException e){} cursor.moveToNext(); } for (int i=0;i<7;i++) { nAdapt[i] = new ClasaAdapt(getActivity(), (ArrayList)listGroup.get(i)); } } } else{ } } private void setListeners(){ for (int i = 0; i < 7; i++) { nListView[i].setAdapter(nAdapt[i]); nListView[i].setOnItemClickListener(new TwoWayView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ClasaAdapt.ClasaAdaptVal vals=(ClasaAdapt.ClasaAdaptVal)parent.getAdapter().getItem(position); <<<<<<< HEAD Fragment classFragment= ClasaFrag.newInstance(position,vals._id); FragmentTransaction transaction=getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentContainer,classFragment, ClasaFrag.TAG); ======= Fragment clasaFrag= ClasaFrag.newInstance(position,vals._id); FragmentTransaction transaction=getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentContainer,clasaFrag, ClasaFrag.TAG); >>>>>>> 2c82b41... LNQ transaction.addToBackStack(null); transaction.commit(); } }); } } <<<<<<< HEAD public void addNewClassToAdapter(ArrayList<Integer>days,String titlu,String startTime,String endTime, int id){ ======= public void adaugaClasaNouaAdapt(ArrayList<Integer>days, String titlu, String startTime, String endTime, int id){ >>>>>>> 2c82b41... LNQ for(int i=0;i<days.size();i++){ if (nAdapt[days.get(i)] != null) { ClasaAdapt.ClasaAdaptVal obj=new ClasaAdapt.ClasaAdaptVal(titlu,startTime,endTime,id); nAdapt[days.get(i)].add(obj); nAdapt[days.get(i)].notifyDataSetChanged(); } } } <<<<<<< HEAD public void updateClassinAdapter(String days,String titlu,String startTime, String endTime, int id){ ======= public void ModificaClasaAdapt(String days, String titlu, String startTime, String endTime, int id){ >>>>>>> 2c82b41... LNQ String[]weekDays=getActivity().getResources().getStringArray(R.array.zile); for (int i = 0; i < weekDays.length; i++) { if (nAdapt[i] != null) { if (days.contains(weekDays[i])) { boolean isOnNewDay = true; for (int u = 0; u < nAdapt[i].getCount(); u++) { ClasaAdapt.ClasaAdaptVal obj = (ClasaAdapt.ClasaAdaptVal) nAdapt[i].getItem(u); if (obj._id == id) { obj.titlu = titlu; obj.startTime = startTime; obj.endTime=endTime; nAdapt[i].remove(u); nAdapt[i].add(obj); isOnNewDay = false; } } if (isOnNewDay) { ClasaAdapt.ClasaAdaptVal obj = new ClasaAdapt.ClasaAdaptVal(titlu, startTime, endTime, id); nAdapt[i].add(obj); } nAdapt[i].notifyDataSetChanged(); } else{ for (int u = 0; u < nAdapt[i].getCount(); u++) { ClasaAdapt.ClasaAdaptVal obj = (ClasaAdapt.ClasaAdaptVal) nAdapt[i].getItem(u); if (obj._id == id) { nAdapt[i].remove(u); } } nAdapt[i].notifyDataSetChanged(); } } } } <<<<<<< HEAD public void deleteClassfromAdapter(int id){ ======= public void stergeClasaAdapt(int id){ >>>>>>> 2c82b41... LNQ ContentResolver resolver=getActivity().getContentResolver(); Uri uri= DbContract.Clasa.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build(); resolver.delete(uri,null,null); for (int i=0;i<7;i++) { if(nAdapt[i]!=null) { for (int u = 0; u < nAdapt[i].getCount(); u++) { ClasaAdapt.ClasaAdaptVal val = (ClasaAdapt.ClasaAdaptVal) nAdapt[i].getItem(u); if (val._id == id) { nAdapt[i].remove(u); } } } } } } <file_sep>/app/src/main/java/com/example/learnnquiz/Profesor/ModifClasaFrag.java package com.example.learnnquiz.Profesor; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.TimePickerDialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TimePicker; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import com.example.learnnquiz.R; public class ModifClasaFrag extends Fragment { public static final String TAG="ModifClasaFrag"; private static final String ARG_ID = "id"; private static final String ARG_TITLU = "titlu"; private static final String ARG_ZI = "zi"; private static final String ARG_METODA = "met"; private static final String ARG_HOUR = "hour"; private static final String ARG_ENDTIME = "endtime"; private static final String ARG_DIFICULTATE = "dif"; private static final String ARG_PRECIZARI = "prec"; <<<<<<< HEAD private String nSelectedDaysAsJson; ======= private String nSelectedDaysAsJson; >>>>>>> 2c82b41... LNQ private int nId; private String nTitlu; private String nDays; private String nMetoda; private String mTime; private String mEndTime; private String nDificultate; private String nPrecizari; <<<<<<< HEAD private View nRootView; ======= private View nRootView; >>>>>>> 2c82b41... LNQ @Override public void onSaveInstanceState(Bundle outState) { outState.putInt("id", nId); outState.putString("titlu", nTitlu); outState.putString("zi", nDays); outState.putString("met", nMetoda); outState.putString("timp",mTime); outState.putString("endTime",mEndTime); outState.putString("dif", nDificultate); outState.putString("prec", nPrecizari); outState.putString("selectedDaysAsJson", nSelectedDaysAsJson); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ super.onSaveInstanceState(outState); } private Button nTimeBtn, nEndTimeBtn; <<<<<<< HEAD private OnClassUpdatedListener nListener; ======= private OnClasaModifListener nListener; >>>>>>> 2c82b41... LNQ public static ModifClasaFrag newInstance(int id, String titlu, String days, String metoda, String hour, String endTime, String dificultate, String precizari) { ModifClasaFrag fragment = new ModifClasaFrag(); Bundle args = new Bundle(); args.putInt(ARG_ID, id); args.putString(ARG_TITLU, titlu); args.putString(ARG_ZI, days); args.putString(ARG_METODA, metoda); args.putString(ARG_HOUR, hour); args.putString(ARG_ENDTIME, endTime); args.putString(ARG_DIFICULTATE, dificultate); args.putString(ARG_PRECIZARI, precizari); fragment.setArguments(args); return fragment; } public ModifClasaFrag() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState!=null) { nId =savedInstanceState.getInt("id",0); nTitlu =savedInstanceState.getString("titlu",""); nDays =savedInstanceState.getString("zi",""); nMetoda =savedInstanceState.getString("met",""); mTime=savedInstanceState.getString("time",""); mEndTime=savedInstanceState.getString("endTime",""); nDificultate =savedInstanceState.getString("dif",""); nPrecizari =savedInstanceState.getString("prec",""); nSelectedDaysAsJson =savedInstanceState.getString("selectedDaysAsJson",""); } else if (getArguments() != null) { nId = getArguments().getInt(ARG_ID); nTitlu = getArguments().getString(ARG_TITLU); nDays = getArguments().getString(ARG_ZI); nMetoda = getArguments().getString(ARG_METODA); mTime = getArguments().getString(ARG_HOUR); mEndTime = getArguments().getString(ARG_ENDTIME); nDificultate = getArguments().getString(ARG_DIFICULTATE); nPrecizari = getArguments().getString(ARG_PRECIZARI); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { nRootView =inflater.inflate(R.layout.modifclasa_frag, container, false); EditText titlu=(EditText) nRootView.findViewById(R.id.nouClasaTitlu); titlu.setText(nTitlu); EditText metoda=(EditText) nRootView.findViewById(R.id.nouClasaMetoda); metoda.setText(nMetoda); EditText precizari=(EditText) nRootView.findViewById(R.id.nouClasaPrecizari); precizari.setText(nPrecizari); EditText dificultate=(EditText) nRootView.findViewById(R.id.modifClasaDif); dificultate.setText(nDificultate); Button daysBtn=(Button) nRootView.findViewById(R.id.nouClasaZile); daysBtn.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { DaysDialogFragment dialogFragment= DaysDialogFragment.newInstance(nDays); dialogFragment.show(getActivity().getFragmentManager(),"dialog"); } }); nTimeBtn = (Button) nRootView.findViewById(R.id.nouClasaInceput); nTimeBtn.setText(mTime); nTimeBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { DialogFragment timeFragment = TimeDialogFragment.newInstance(mTime); timeFragment.show(getActivity().getFragmentManager(), "Time"); } }); nEndTimeBtn = (Button) nRootView.findViewById(R.id.nouClasaSfarsit); nEndTimeBtn.setText(mEndTime); nEndTimeBtn.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { DialogFragment newFragment = EndTimeDialogFragment.newInstance(mEndTime); newFragment.show(getActivity().getFragmentManager(),"EndTime"); } }); <<<<<<< HEAD Button updateBtn=(Button) nRootView.findViewById(R.id.updateClassBtn); updateBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { ======= Button updateBtn=(Button) nRootView.findViewById(R.id.modifclasa); updateBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { >>>>>>> 2c82b41... LNQ EditText title=(EditText) nRootView.findViewById(R.id.nouClasaTitlu); nTitlu =title.getText().toString(); EditText location=(EditText) nRootView.findViewById(R.id.nouClasaMetoda); nMetoda =location.getText().toString(); EditText info=(EditText) nRootView.findViewById(R.id.nouClasaPrecizari); nPrecizari =info.getText().toString(); EditText lvl=(EditText) nRootView.findViewById(R.id.modifClasaDif); nDificultate =lvl.getText().toString(); ContentValues vals=new ContentValues(); vals.put(DbContract.Clasa.COLUMN_TITLU, nTitlu); vals.put(DbContract.Clasa.COLUMN_TIMP, mTime); if(nSelectedDaysAsJson !=null && nSelectedDaysAsJson !="") vals.put(DbContract.Clasa.COLUMN_DATA, nSelectedDaysAsJson); <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ vals.put(DbContract.Clasa.COLUMN_DURATA, mEndTime); vals.put(DbContract.Clasa.COLUMN_METODA, nMetoda); vals.put(DbContract.Clasa.COLUMN_DIFICULTATE, nDificultate); vals.put(DbContract.Clasa.COLUMN_MENTIUNI_PARTICIPANT, nPrecizari); Uri uri= DbContract.Clasa.CONTENT_URI.buildUpon().appendPath(Integer.toString(nId)).build(); ContentResolver resolver=getActivity().getContentResolver(); if(resolver.update(uri,vals,null,null)>0){ InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(v.getWindowToken(), 0); <<<<<<< HEAD nListener.OnClassUpdated(nId, nTitlu, nDays, nMetoda,mTime,mEndTime, nDificultate, nPrecizari); ======= nListener.onClasaModif(nId, nTitlu, nDays, nMetoda,mTime,mEndTime, nDificultate, nPrecizari); >>>>>>> 2c82b41... LNQ FragmentManager fm = getActivity().getSupportFragmentManager(); fm.popBackStack(); Toast.makeText(getActivity(),R.string.clasamodif,Toast.LENGTH_LONG).show(); } else{ <<<<<<< HEAD Toast.makeText(getActivity(),"Could not update",Toast.LENGTH_LONG).show(); ======= Toast.makeText(getActivity(),"Nu am putut modifica",Toast.LENGTH_LONG).show(); >>>>>>> 2c82b41... LNQ } } }); return nRootView; } <<<<<<< HEAD public void setSelectedTime(String TAG,String time){ ======= public void setTimpSel(String TAG, String time){ >>>>>>> 2c82b41... LNQ if(TAG.equals(this.TAG)) { nTimeBtn.setText(time); mTime = time; } else if(TAG.equals(this.TAG+"END")){ nEndTimeBtn.setText(time); mEndTime=time; } } <<<<<<< HEAD public void setSelectedWeekdays(ArrayList<Integer>data){ ======= public void setZileSel(ArrayList<Integer>data){ >>>>>>> 2c82b41... LNQ JSONObject jDays=new JSONObject(); JSONArray jarr=new JSONArray(data); try { jDays.put("selectedDays", jarr); }catch(JSONException e){ <<<<<<< HEAD } nSelectedDaysAsJson = jDays.toString(); nDays =toDays(nSelectedDaysAsJson); ======= } nSelectedDaysAsJson = jDays.toString(); nDays =toDays(nSelectedDaysAsJson); >>>>>>> 2c82b41... LNQ } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { <<<<<<< HEAD nListener = (OnClassUpdatedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnClassUpdatedListener"); } } ======= nListener = (OnClasaModifListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + ""); } } >>>>>>> 2c82b41... LNQ @Override public void onDetach() { super.onDetach(); nListener = null; } <<<<<<< HEAD public interface OnClassUpdatedListener { public void OnClassUpdated(int id,String titlu, String days,String metoda, String startTime, String endTime, String dificultate, String precizari); } public static class DaysDialogFragment extends DialogFragment { private String nSavedDays; public String[] ndays; public boolean[] nselections; ======= public interface OnClasaModifListener { public void onClasaModif(int id, String titlu, String days, String metoda, String startTime, String endTime, String dificultate, String precizari); } public static class DaysDialogFragment extends DialogFragment { private String nSavedDays; public String[] ndays; public boolean[] nselections; >>>>>>> 2c82b41... LNQ public static DaysDialogFragment newInstance(String days) { DaysDialogFragment frag = new DaysDialogFragment(); Bundle args = new Bundle(); args.putString("days", days); frag.setArguments(args); return frag; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ndays =getActivity().getResources().getStringArray(R.array.zile); nselections =new boolean[ndays.length]; if (getArguments() != null) { nSavedDays =getArguments().getString("days"); for(int i = 0; i< ndays.length; i++){ if(nSavedDays.contains(ndays[i])) nselections[i]=true; } } } <<<<<<< HEAD @Override public Dialog onCreateDialog(Bundle savedInstanceState) { ======= @Override public Dialog onCreateDialog(Bundle savedInstanceState) { >>>>>>> 2c82b41... LNQ return new AlertDialog.Builder( getActivity() ) .setTitle(getActivity().getResources().getString(R.string.nouZile) ) .setMultiChoiceItems(ndays, nselections, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) {} }) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ArrayList<Integer> selectedDays= new ArrayList<Integer>(); for (int i = 0; i < ndays.length; i++) { if (nselections[i]) selectedDays.add(i); } ((MainProfesor) getActivity()).forwardDataFromDialogFragmentToFragment(ModifClasaFrag.TAG, selectedDays); } }) .create(); } } <<<<<<< HEAD public static class TimeDialogFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{ String nTime; Calendar nCalendar; ======= public static class TimeDialogFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{ String nTime; Calendar nCalendar; >>>>>>> 2c82b41... LNQ public static TimeDialogFragment newInstance(String time){ TimeDialogFragment fragment = new TimeDialogFragment(); Bundle args = new Bundle(); args.putString("TIME",time); fragment.setArguments(args); return fragment; } <<<<<<< HEAD ======= >>>>>>> 2c82b41... LNQ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { nTime =getArguments().getString("TIME",""); int dividerPos= nTime.indexOf(":"); int hour= Integer.parseInt(nTime.substring(0,dividerPos)); int minute=Integer.parseInt(nTime.substring(dividerPos+1)); nCalendar =Calendar.getInstance(); nCalendar.set(Calendar.HOUR_OF_DAY,hour); nCalendar.set(Calendar.MINUTE,minute); } } <<<<<<< HEAD @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int hour = nCalendar.get(Calendar.HOUR_OF_DAY); int minute = nCalendar.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(),this,hour,minute,true); } ======= @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int hour = nCalendar.get(Calendar.HOUR_OF_DAY); int minute = nCalendar.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(),this,hour,minute,true); } >>>>>>> 2c82b41... LNQ @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String hour=Integer.toString(hourOfDay); if (hour.length()==1) hour="0"+hour; String min=Integer.toString(minute); if(min.length()==1) min="0"+min; String time=hour+":"+min; ((MainProfesor)getActivity()).forwardTimeFromDialogFragmentToFragment(TAG,time); } } <<<<<<< HEAD public static class EndTimeDialogFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{ String mTime; Calendar mCalendar; ======= public static class EndTimeDialogFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{ String nTime; Calendar nCalendar; >>>>>>> 2c82b41... LNQ public static EndTimeDialogFragment newInstance(String time){ EndTimeDialogFragment fragment = new EndTimeDialogFragment(); Bundle args = new Bundle(); args.putString("TIME",time); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { <<<<<<< HEAD mTime=getArguments().getString("TIME",""); int dividerPos=mTime.indexOf(":"); int hour= Integer.parseInt(mTime.substring(0,dividerPos)); int minute=Integer.parseInt(mTime.substring(dividerPos+1)); mCalendar=Calendar.getInstance(); mCalendar.set(Calendar.HOUR_OF_DAY,hour); mCalendar.set(Calendar.MINUTE,minute); ======= nTime =getArguments().getString("TIME",""); int dividerPos= nTime.indexOf(":"); int hour= Integer.parseInt(nTime.substring(0,dividerPos)); int minute=Integer.parseInt(nTime.substring(dividerPos+1)); nCalendar =Calendar.getInstance(); nCalendar.set(Calendar.HOUR_OF_DAY,hour); nCalendar.set(Calendar.MINUTE,minute); >>>>>>> 2c82b41... LNQ } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { <<<<<<< HEAD int hour = mCalendar.get(Calendar.HOUR_OF_DAY); int minute = mCalendar.get(Calendar.MINUTE); ======= int hour = nCalendar.get(Calendar.HOUR_OF_DAY); int minute = nCalendar.get(Calendar.MINUTE); >>>>>>> 2c82b41... LNQ return new TimePickerDialog(getActivity(),this,hour,minute,true); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String hour=Integer.toString(hourOfDay); if (hour.length()==1) hour="0"+hour; String min=Integer.toString(minute); if(min.length()==1) min="0"+min; String time=hour+":"+min; ((MainProfesor)getActivity()).forwardTimeFromDialogFragmentToFragment(TAG + "END", time); } } public String toDays(String jsonFormattedString) { String humanReadableString=""; try { JSONObject json = new JSONObject(jsonFormattedString); <<<<<<< HEAD JSONArray jarr=json.optJSONArray("selectedDays"); ======= JSONArray jarr=json.optJSONArray("zile"); >>>>>>> 2c82b41... LNQ if (jarr != null) { for (int i=0;i<jarr.length();i++){ switch(jarr.getInt(i)){ case 0: humanReadableString+=getActivity().getResources().getString(R.string.luni); break; case 1: humanReadableString+=getActivity().getResources().getString(R.string.marti); break; case 2: humanReadableString+=getActivity().getResources().getString(R.string.miercuri); break; case 3: humanReadableString+=getActivity().getResources().getString(R.string.joi); break; case 4: humanReadableString+=getActivity().getResources().getString(R.string.vineri); break; case 5: humanReadableString+=getActivity().getResources().getString(R.string.sambata); break; case 6: humanReadableString+=getActivity().getResources().getString(R.string.duminica); break; } if(i!=jarr.length()-1) humanReadableString+= ", "; } } }catch (JSONException e){} return humanReadableString; } } <file_sep>/app/src/main/java/com/example/learnnquiz/Adapt/ListaLectie.java package com.example.learnnquiz.Adapt; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; 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.RelativeLayout; import android.widget.TextView; import com.example.learnnquiz.R; import com.example.learnnquiz.Activitati.Sectiuni; import com.example.learnnquiz.Layout.FitDoughnut; import com.example.learnnquiz.Obiecte.Lectie; import java.util.ArrayList; import java.util.List; public class ListaLectie extends RecyclerView.Adapter<ListaLectie.SimpleViewHolder> { private final Context context; private List<Lectie> lectie; private final int idcurs; public ListaLectie(Context context, List<Lectie> elemente, int idcurs) { this.context = context; this.lectie = elemente; this.idcurs = idcurs; if (lectie == null) { lectie = new ArrayList<>(); } } public static class SimpleViewHolder extends RecyclerView.ViewHolder { public final TextView Titlulectietextview; public final RelativeLayout allView; public final ImageView imglectie; public final FitDoughnut doughnut; public SimpleViewHolder(View view) { super(view); Titlulectietextview = view.findViewById(R.id.titlu_lectie); allView = view.findViewById(R.id.allview); doughnut = view.findViewById(R.id.doughnutres); imglectie = view.findViewById(R.id.img_lectie); } } @Override public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View view = LayoutInflater.from(this.context).inflate(R.layout.lectie, parent, false); return new SimpleViewHolder(view); } @Override public void onBindViewHolder(final SimpleViewHolder holder, final int position) { holder.Titlulectietextview.setText(lectie.get(position).getTitlu()); String backrnume = "course" + idcurs; holder.imglectie.setBackgroundResource(context.getResources().getIdentifier(backrnume, "drawable", context.getPackageName())); String poznume = "z" + lectie.get(position).getId(); holder.imglectie.setImageResource(context.getResources().getIdentifier(poznume, "drawable", context.getPackageName())); if (lectie.get(position).getRezultat() > 0) { holder.doughnut.setVisibility(View.VISIBLE); holder.doughnut.animateSetPercent(((float) lectie.get(position).getRezultat() * 10) - 0.01f); } holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (lectie.get(position).getSectiuniNr() == 0) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { Intent intent = new Intent(context, Sectiuni.class); intent.putExtra("nrsectiune", 0); intent.putExtra("lectieid", lectie.get(position).getId()); context.startActivity(intent); } } }); } @Override public long getItemId(int position) { return position; } @Override public int getItemCount() { return this.lectie.size(); } }
bd5bb1a8c80909c718c7b97a439a012ea4f40f09
[ "Markdown", "Java" ]
17
Java
RebecaTonu/Learn-N-Quiz
67bb63251948cc3c985bee39d112c715d3306b65
fd991559c13a7ffec420fd8ef6131824aef94fd7
refs/heads/main
<file_sep>import { Then, When, Given } from "cypress-cucumber-preprocessor/steps"; const textbox_selector='.public-DraftStyleDefault-block' const error_selector='[class="styled__Top-sc-1naxbon-4 nfFBQ"]' const menu_selector='[class="select__menu css-1lmnvla"]' const dropdown_selector='.select__control' const history_selector='[class="ReactVirtualized__Grid__innerScrollContainer"] > div' const time_selector='time' const POST_selector='[data-testid=post-question-btn-active]' const url = 'https://aqa.int.sellercrowd.com/api/testing/auth-user/admin' const question='Would you hire a guy who can write automated tests in BDD (Cucumber) style with Cypress?' Then(`posts are updated correctly`, () => { cy.get(history_selector).first().should('include.text', question) }) Then(`posts should not be updated`, () => { cy.get(time_selector).first().invoke('attr', 'datetime') .then(($dtm)=>{ const now_dtm= new Date() const last_post=new Date($dtm) const long_time=10000 if(now_dtm-last_post>long_time){return 'Pass'}else{return 'Fail'} }).should('be.eq','Pass') }) When(`user types in a question`, () => { cy.get(textbox_selector).type(question) }) When(`user types in only one letter`, () => { cy.get(textbox_selector).type('x') }) And(`open chanel selector`, () => { cy.get('.select__control').click() }) When(`user picks {string} chanel`, (chanel) => { cy.get(menu_selector).contains(chanel).click() }) And(`press ENTER key`, () => { cy.get(textbox_selector).type('{enter}') }) And(`clicks "Post" button`, () => { cy.get(POST_selector).click() }) Given('Chanel selection is available', () => { cy.get(dropdown_selector) }) Then(`Mandatory chanel selection warning is displayed`, () => { cy.get(error_selector).should('include.text', 'Please select at least one of your channels.') }) Then(`warning message is displayed`, () => { cy.get(error_selector).should('include.text', 'Please type at least 20 characters.') }) Given('SellerCrowd website is opened', () => { cy.visit(url) })
e6dd10b6b7ed83316d601c9074d7f8f4bed506a0
[ "JavaScript" ]
1
JavaScript
irinelko/SellerCrowd
3fc847a028a8e9b917404c8ba67c646378b3e068
6247f616f6c70b63c9e6612ca7dc07d377b0ceb1
refs/heads/master
<file_sep># Write your code here! require 'sinatra' require_relative 'app.rb' run Application
af57fa7ce6f3f73da35d8aedf82b0af897cc1b21
[ "Ruby" ]
1
Ruby
Anton-Kalyutich/intro-to-capybara-online-web-sp-000
c93f1b1215afa2a510bd2cacead1af9d362d600f
0d40950b96ccb43718afdd159b19548b2d12869c
refs/heads/master
<file_sep><?php header("Cache-Control: no-cache"); header("Pragma: no-cache"); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="-1" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui"> <meta name="theme-color" content="#000000"> <title>WishWalk</title> <link rel="stylesheet" href="<?=ADMIN_PATH?>css/common/framework7.material.min.css"> <link rel="stylesheet" href="<?=ADMIN_PATH?>css/common/framework7.material.colors.min.css"> <link rel="stylesheet" href="<?=ADMIN_PATH?>css/common/framework7-icons.css"> <link rel="stylesheet" href="<?=ADMIN_PATH?>css/common/owl/owl.carousel.min.css"> <link rel="stylesheet" href="<?=ADMIN_PATH?>css/common/owl/owl.theme.default.min.css"> <link rel="stylesheet" href="<?=ADMIN_PATH?>css/common/common.css"> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/jquery.min.js"></script> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/framework7.min.js"></script> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/owl.carousel.min.js"></script> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/function.js"></script> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/common.js"></script> </head> <body> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Index extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('index_model'); } /* * index * 정수영 * 20170313 * 첫 redirection * url 조회 */ function index(){ $data["indexes"] = $this->index_model->getIndexInfo(); $this->load->view("index/index_view", $data); } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('user_model'); $this->load->library('walk_common'); $this->load->library('session_common'); } /* * indexPw * 이소희 * 20170313 * 비밀번호 초기화면 */ function indexPw($check){ $this->load->view ("activity/header_p"); $data["check"] = $check; $data["pw_error"] = ""; $this->load->view("user/user_pw_view",$data); $this->load->view ("activity/footer"); } /* * pwCheck * 이소희 * 20170314 * 비밀번호 확인 후 탈퇴 사유 뷰로 이동 */ function pwCheck($check){ if($this->session_common->checkSession("user")){ $user_id = $this->session_common->getSession("user")['user_id']; } $pw=trim($this->input->post('password')); $cnt = $this->user_model->pwCheck($user_id,$pw); //비밀번호를 입력하지 않거나 일치 하지 않을떄 if ($cnt < 1){ $data["pw_error"] = "비밀번호가 일치하지 않습니다."; $data["check"] = $check; $this->load->view ("activity/header_p"); $this->load->view("user/user_pw_view",$data); $this->load->view ("activity/footer"); }else{ $data["pwReasons"]= $this->walk_common->func_getCode('USER_LEAVE'); $this->load->view ("activity/header_p"); $this->load->view("/user/user_delete_reason",$data); $this->load->view ("activity/footer"); } } /* * deleteInfo * 이소희 * 20170314 * 회원 탈퇴 */ function deleteInfo(){ if($this->session_common->checkSession("user")){ $user_id = $this->session_common->getSession("user")['user_id']; } $reason=trim($this->input->post('reason')); $etc=trim($this->input->post('etc')); return $this->user_model->deleteInfo($user_id, $reason, $etc); } /* * userInfo * 이소희 * 20170317 * 회원정보 확인 + 세션 아이디로 회원 정보 확인 */ function userInfo(){ if($this->session_common->checkSession("user")){ $user_id = $this->session_common->getSession("user")['user_id']; } $data["info"] = $this->user_model->userInfo($user_id); $this->load->view("activity/header_p"); $this->load->view("user/user_info_view",$data); $this->load->view("activity/footer"); } /* * pwChange * 이소희 * 20170315 * 비밀번호 확인 후 변경 페이지로 이동 */ function pwChange($check){ if($this->session_common->checkSession("user")){ $user_id = $this->session_common->getSession("user")['user_id']; } $pw=trim($this->input->post('password')); $cnt = $this->user_model->pwCheck($user_id,$pw); //비밀번호를 입력하지 않거나 일치 하지 않을떄 if ($cnt < 1){ $data["pw_error"] = "비밀번호가 일치하지 않습니다."; $data["check"] = $check; $this->load->view("activity/header_p"); $this->load->view("user/user_pw_view",$data); $this->load->view("activity/footer"); }else{ $data["info"] = $this->user_model->userInfo($user_id); $this->load->view("activity/header_p"); $this->load->view("/user/user_pw_change",$data); $this->load->view("activity/footer"); } } /* * newPwSet * 이소희 * 20170315 * 비밀번호 재설정 */ function newPwSet(){ if($this->session_common->checkSession("user")){ $user_id = $this->session_common->getSession("user")['user_id']; } $pw=trim($this->input->post('password')); return $this->user_model->newPwSet($user_id, $pw); } /* * loginIndex * 이소희 * 20170316, 20170317 * 로그인화면 (main, 로그아웃 후 로그인 화면으로 이동) */ function loginIndex(){ $this->load->view("activity/header"); $this->load->view("user/login_index_view"); $this->load->view("activity/footer"); } /* * loginCheck * 이소희 * 20170316 * 로그인체크 * 사용자_id : (대회이름, 종료일시, 사용자_id, 이름, 참여중대회_id, cnt, logged_in 정보를 가지고옴) */ function loginCheck(){ $user_id=trim($this->input->post('user_id')); $password=trim($this->input->post('password')); $user = $this->user_model->loginCheck($user_id,$password); if($user->cnt==1){ $this->session_common->setSession("user", $user); } echo $user->cnt; } /* * logout * 이소희 * 20170317 * 로그아웃 */ function logout(){ $this -> session_common -> logout(); $this->load->view("activity/header_p"); $this->load->view("user/login_index_view"); $this->load->view("activity/footer"); } /* * findIdIndex * 이소희 * 20170316 * 아이디 찾기 index뷰 */ function findIdIndex(){ $this->load->view("activity/header_p"); $this->load->view("user/find_id_index_view"); $this->load->view("activity/footer"); } /* * insertCode * 이소희 * 20170316 * 인증번호 생성 */ function insertCode(){ $name=trim($this->input->post('name')); $phone=trim($this->input->post('phone')); //전화번호 DB 여부 확인 $cnt = $this->user_model->checkPhone($name, $phone); //해당 정보가 없을 때 if ($cnt < 1){ $return["cnt"] = $cnt; echo json_encode($return); }else{ $return["cnt"] = $cnt; //인증번호 6자리 생성 $rand_num = sprintf("%06d",rand(000000,999999)); $this->user_model->insertCode($name, $phone, $rand_num); $return["rand_num"] = $rand_num; echo json_encode($return); } } /* * checkCode * 이소희 * 20170316 * 인증번호 일치 여부 확인 */ function checkCode(){ $name=trim($this->input->post('name')); $phone=trim($this->input->post('phone')); $code=trim($this->input->post('code')); $cnt = $this->user_model->checkCode($name,$phone,$code); echo $cnt; } /* * findId * 이소희 * 20170316, 20170317 * 아이디 찾기 + get방식이 아니라 post방식으로 바꿈 */ function findId(){ $name=trim($this->input->post('name')); $phone=trim($this->input->post('phone')); $data['fid'] = $this->user_model->findId($name,$phone); $this->load->view("activity/header_p"); $this->load->view("user/find_id_result",$data); $this->load->view("activity/footer"); } /* * findPwIndex * 이소희 * 20170317 * 비밀번호 찾기 index 뷰 */ function findPwIndex(){ $this->load->view("activity/header_p"); $this->load->view("user/find_pw_index_view"); $this->load->view("activity/footer"); } /* * insertCode2 * 이소희 * 20170320 * 인증번호 생성 (아이디로 인증번호 생성) */ function insertCode2(){ $id=trim($this->input->post('user_id')); $phone=trim($this->input->post('phone')); //전화번호 DB 여부 확인 $cnt = $this->user_model->checkIdPhone($id, $phone); //해당 정보가 없을 때 if ($cnt < 1){ $return["cnt"] = $cnt; echo json_encode($return); }else{ $return["cnt"] = $cnt; //인증번호 6자리 생성 $rand_num = sprintf("%06d",rand(000000,999999)); $this->user_model->insertCode2($id, $phone, $rand_num); $return["rand_num"] = $rand_num; echo json_encode($return); } } /* * checkCode2 * 이소희 * 20170317 * 인증번호 일치 여부 확인 (아이디로 확인) */ function checkCode2(){ $user_id=trim($this->input->post('user_id')); $code=trim($this->input->post('code')); $cnt = $this->user_model->checkCode2($user_id,$code); echo $cnt; } /* * findPw * 이소희 * 20170317 * 비밀번호 재설정 */ function findPw(){ $data['user_id']=trim($this->input->post('user_id')); $this->load->view("activity/header_p"); $this->load->view("user/find_pw_change",$data); $this->load->view("activity/footer"); } /* * newPwSet2 * 이소희 * 20170320 * 비밀번호 재설정(아이디 고정X) */ function newPwSet2(){ $user_id=trim($this->input->post('user_id')); $pw=trim($this->input->post('password')); return $this->user_model->newPwSet2($user_id, $pw); } /* * registerIndex * 이소희 * 201703 * 회원가입 index 뷰 */ function registerIndex(){ $this->load->view("activity/header_p"); $this->load->view("user/register_index_view"); $this->load->view("activity/footer"); } /* * adsChangeIndex * 이소희 * 20170322 * 주소 변경 인덱스 뷰 */ function adsChangeIndex(){ if($this->session_common->checkSession("user")){ $data['user_id'] = $this->session_common->getSession("user")['user_id']; } $this->load->view("activity/header_p"); $this->load->view("user/ads_change_index",$data); $this->load->view("activity/footer"); } /* * adsChange * 이소희 * 20170322 * 주소 재설정 */ function adsChange(){ if($this->session_common->checkSession("user")){ $user_id = $this->session_common->getSession("user")['user_id']; } $newAdd=trim($this->input->post('newAdd')); $result = $this->user_model->adsChange($user_id, $newAdd); if($result==1){ redirect('/user/userInfo'); } } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Event extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('event_model'); $this->load->library('walk_common'); } /* * index * 홍익표 * 20170310 * 이벤트 조회 * max3개 까지 리스트 조회 * 3개가 넘을경우 더보기 보이기 */ function index(){ $data["events"] = $this->event_model->getLiveEvent(); $this->load->view("event/event_view", $data); } /* * walkMain * 홍익표 * 20170310 * 걷기 메일에서 호출 * max3개 까지 리스트 조회 * 3개가 넘을경우 더보기 보이기 */ function walkMain(){ $data["count"] = $this->event_model->getLiveEventCount(); $data["events"] = $this->event_model->getLiveEvent(0,3); $this->load->view("event/event_walk_main", $data); } } ?><file_sep><style> .faQ{ border-bottom:1px solid black; padding :10px; } .faA{ padding :10px; } .listTitle{ padding:5px; font-size:18px; } .listContents{ padding-bottom:20px; margin:5px; } </style> <div> <?php foreach($listTitles as $listTitle){ ?> <div class="listContents"> <div class="listTitle"> <?= $listTitle -> 코드명 ?></div> <?php foreach($faqs as $faq){ if($listTitle-> 코드명==$faq-> 코드명){ ?> <div class="faQ"> <?= $faq->글제목 ?> <div class="cbutton" style="float:right;"> &#8681; </div> </div> <div class="faA" style="display:none" value="<?= $faq->글내용 ?>"> </div> <?php } ?> <?php } ?> </div> <?php } ?> </div> <script> $(document).ready(function(){ $(".cbutton").each(function(idx){ $(this).click(function(){ $index = $(".faA").eq(idx); $index.html("Ans : " + $index.attr("value")); $index.toggle("fast"); }); }); }); </script><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Statistics extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('statistics_model'); } /* * index * 이민수 * 20170315 * 참가현황 통계 */ function index(){ echo "잘못된 접근"; exit(); } //나의 대회 참여 통계 function myTableStep(){ //로그인한 정보 $myLogin = array('USER_ID' => "gildong", 'USER_NAME' => "홍길동","USER_PIC"=>경로_사용자."hong.jpg"); $data["myInfo"] = $myLogin; //현재 참여중인 대회 여부??? $걷기대회_id="2"; $data["myTable_Step_Data"] = $this->statistics_model->getMyStepStatistics($myLogin['USER_ID'],$걷기대회_id); $data["myTable_TournamentStart"] = $this->statistics_model->getMyTournamentStart($myLogin['USER_ID'],$걷기대회_id); $data["myTable_TournamentInfo"] = $this->statistics_model->getMyTournamentInfo($걷기대회_id); $data["myTable_Stamp_Data"] = $this->statistics_model->getMyStamp($myLogin['USER_ID'],$걷기대회_id); $data["myTable_Card_Data"] = $this->statistics_model->getMyCard($myLogin['USER_ID'],$걷기대회_id); $this->load->view("statistics/my_statistics", $data); } //나의 통계 function myTableStepChart(){ $data=""; $this->load->view("statistics/my_statistics_chart", $data); } /* * 이종호 * 20170328 * Main_1 상단 걷기이력 컴포넌트 * */ function step_comp(){ $user = $this->session_common->getSession("user")['user_id']; $std = $this->statistics_model->getAllStep($user); $data["step_info"] = array(); foreach ($std as $val) { $step = number_format($val->걸음수); $date = (new DateTime($val->날짜))->format('Y년 m월 d일'); array_push($data["step_info"],json_encode(array("날짜"=>$date,"걸음수"=>$step))); } $this->load->view("statistics/step_comp",$data); } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once APPPATH.'controllers/activity/common/menu.php'; class MainActivity_1 extends CI_Controller { function __construct(){ parent::__construct(); //$this->load->model('index_model'); } /* * C : MainActivity_1 * 로그인 정보 없을 시 표출 * 대회리스트, 매거진 등 각 모듈별 리스트 페이지 */ function index(){ //$data["indexes"] = $this->index_model->getIndexInfo(); Menu::_header(); $this->load->view("activity/MainActivity_1/index"); Menu::_footer(); } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Actionsheet extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('prize_model'); $this->load->model('walk_model'); } /* * 이종호 * 20170329 * Main_2 스탬프 ActionSheet * 스탬프 현황 */ function getstamp_sheet(){ $user = $this->session_common->getSession("user")['user_id']; $contest_id = $this->session_common->getSession("user")['contest_id']; $data["contest"] = $this->walk_model->getInfoEvent($contest_id); $data["stamp"] = $this->prize_model->getStampRate($user,$contest_id); $data["user"] = $this->session_common->getSession("user"); $data["state"] = "get"; $this->load->view("actionsheet/stamp_sheet",$data); } /* * 이종호 * 20170329 * Main_2 스탬프 ActionSheet * 스탬프 적립 */ function setstamp_sheet(){ $user = $this->session_common->getSession("user")['user_id']; $contest_id = $this->session_common->getSession("user")['contest_id']; $data["contest"] = $this->walk_model->getInfoEvent($contest_id); $data["stamp"] = $this->prize_model->getStampRate($user,$contest_id); $data["user"] = $this->session_common->getSession("user"); $data["state"] = "set"; $this->load->view("actionsheet/stamp_sheet",$data); } /* * 이종호 * 20170330 * Main_2 스탬프 ActionSheet * 경품 현황 */ function getprize_sheet(){ $user = $this->session_common->getSession("user")['user_id']; $contest_id = $this->session_common->getSession("user")['contest_id']; $data["contest"] = $this->walk_model->getInfoEvent($contest_id); $data["prize"] = $this->prize_model->getUserPrizeCount($user,$contest_id); $data["user"] = $this->session_common->getSession("user"); $data["state"] = "get"; $this->load->view("actionsheet/prize_sheet",$data); } /* * 이종호 * 20170330 * Main_2 스탬프 ActionSheet * 경품 받기 */ function setprize_sheet(){ $user = $this->session_common->getSession("user")['user_id']; $contest_id = $this->session_common->getSession("user")['contest_id']; $data["contest"] = $this->walk_model->getInfoEvent($contest_id); $data["prize"] = $this->prize_model->getStampRate($user,$contest_id); $data["user"] = $this->session_common->getSession("user"); $data["state"] = "set"; $this->load->view("actionsheet/prize_sheet",$data); } }<file_sep><style> .summary_box .content_box{display:none;} </style> <div style="text-align:left;margin:5px;line-height:23px;"> <div>캐논과 함께하는</div> <div style="font-size:25px;font-weight:bold;"><?=$event->제목?></div> <div><?=$event->s_year." ".$event->s_md?> ~ <?php if( $event->s_year == $event->e_year ){ echo $event->e_md; } else{ echo $event->e_year." ".$event->e_md; }?> </div> <div>대한민국 국민 모두 함께하는<br>파노라마 걷기대회</div> </div> <div style="font-size:12px">+펼쳐보기</div> <div class="btn_info" style="background-color:#555;margin:5px;padding:5px 0px;">특별프로그램 안내</div> <div class="content_box">1</div> <div class="btn_info" style="background-color:#555;margin:5px;padding:5px 0px;">기념품안내</div> <div class="content_box"> <?php foreach ($mementos as $memento): ?> <p>기념품 : <?=$memento->경품명?> </p> <p>수량 : <?=$memento->경품수?>개</p> <?php endforeach; ?></div> <div class="btn_info" style="background-color:#555;margin:5px;padding:5px 0px;">경품안내</div> <div class="content_box"> <?php foreach ($gifts as $gift): ?> <p>기념품 : <?=$gift->경품명?> </p> <p>수량 : <?=$gift->경품수?>개</p> <?php endforeach; ?></div> <div class="btn_info" style="background-color:#555;margin:5px;padding:5px 0px;">유의사항</div> <div class="content_box"> ※ 유의사항 <div style="margin:10px">정해진 기간 동안 걸음 수를 맞추지 못하면 자동으로 실패됩니다. 트랙을 완보해도 스템프를 받지 못하면 기념품을 받을 수 없습니다. 경품추첨은 00월00일에 진행됩니다.</div> </div> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class promotion_model extends CI_Model{ function __construct(){ parent::__construct(); } /* getPromoCount * 조진근 * 프로모션 갯수 조회 */ function getPromoCount(){ $this->db->select("count(*) cnt"); $this->db->from("프로모션"); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용유무","Y"); return $this->db->get()->row()->cnt; } /* * 20170317 * getOpenedList * 조진근 * 현재 진행중인 프로모션 리스트를 가지고 온다. */ function getOpenedList($count='',$start=''){ $this->db->select('*',FALSE); $this->db->from("프로모션"); $this->db->where("now() > 시작일시",NULL,FALSE); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용유무","Y"); $this->db->order_by("작성일"); if($count !='' || $start !='') $this->db->limit($start,$count); return $this->db->get()->result(); } /* * 20170317 * getClosedList * 조진근 * 현재 종료된 프로모션 리스트를 가지고 온다. */ function getClosedList(){ $this->db->select('*',FALSE); $this->db->from("프로모션"); $this->db->where("now() > 종료일시",NULL,FALSE); $this->db->where("사용유무","Y"); return $this->db->get()->result(); } } ?> <file_sep><style media="screen"> .eventMain ul { padding: 5px 0; list-style-type: none; background-color: #282828 } .eventMain .container{ border : 1px solid black; width : 100%; background-color: gray; } .eventMain .header{ position: relative; background-color: gray; margin: 5px; border: 1px solid gray; padding-left: 1%; width: auto; } .eventMain .list{ color: white; position: relative ; width: auto; min-height: 100px; } .eventMain .article { position: relative; height: auto; } .eventMain .title{ color: whit position: relative; padding: 0 2%; } .eventMain #thumbnail{ position: ; margin: 0px 5px; float: left; } .eventMain #more { padding-right: 5px; float: right; color:#000; } .eventMain li { padding:5px; line-height:0px; } </style> <div class="eventMain"> <div class="container"> <div class="header"> <p>이벤트 <?php if( $count > 2 ){ ?> <a id="more" href="<?=WEB_ROOT?>magazine/magazineList"> 더보기</a> <?php } ?> </p> </div> <div class="article"> <ul> <?php foreach ( $events as $event ) { ?> <li> <img src="<?=경로_이벤트.$event->배너파일?>" alt=<?=htmlspecialchars($event->제목,ENT_QUOTES)?> width="100%"/> </li> <?php } ?> </ul> </div> </div> </div> <file_sep><div class="navbar-inner"> <div style="display:table;width:30%;height:100%;"> <a href="#" class="link prev" style="display:table-cell;vertical-align:middle;"> <img src="<?=IMG_PATH?>MainActivity_1/main_arrow_left.png" style="display:table-cell;height:80%;float:right;"> </a> </div> <div class="step" style="width:40%;height:100%;text-align:center;padding-top:15px;"> <span style="color:#c7c7c7;"></span> <h3></h3> </div> <div style="display:table;width:30%;height:100%;"> <a href="#" class="link next" style="display:table-cell;vertical-align:middle;"> <img src="<?=IMG_PATH?>MainActivity_1/main_arrow_right.png" style="display:table-cell;height:80%;"> </a> </div> </div> <script> var cnt = 0; var step_info = new Array(); <?php foreach($step_info as $val){ ?> step_info.push(JSON.parse('<?=$val?>')); <?php } ?> $("div[comp_prop='step_comp']").find(".step").find("span").text(step_info[0].날짜); $("div[comp_prop='step_comp']").find(".step").find("h3").text(step_info[0].걸음수); $("div[comp_prop='step_comp']").find(".link").on("click",function(){ if($(this).attr("class").indexOf("next")>-1){ if(cnt==0) return; cnt--; $("div[comp_prop='step_comp']").find(".step").find("span").text(step_info[cnt].날짜); $("div[comp_prop='step_comp']").find(".step").find("h3").text(step_info[cnt].걸음수); } if($(this).attr("class").indexOf("prev")>-1){ if(cnt==step_info.length-1) return; cnt++; $("div[comp_prop='step_comp']").find(".step").find("span").text(step_info[cnt].날짜); $("div[comp_prop='step_comp']").find(".step").find("h3").text(step_info[cnt].걸음수); } }); </script><file_sep><!DOCTYPE html> <html lang="ko" class=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,target-densitydpi=medium-dpi"/> <!-- 공통 스타일 --> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.colors.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7-icons.css"> <link rel="stylesheet" href="/mnt/walk/common/css/common.css?t=1"> <title>게시판</title> <style> .clear{clear:both;} .menu{border-top:1px solid #cdcdcd;margin-top:10px;padding-top:5px;border-bottom:1px solid #cdcdcd;margin-bottom:5px;padding-bottom:5px;} .menu:after {content:"";clear:both;display:block;} .list_box{display:block;} .contentBox{display:none;margin:2px;} .notice_item{ padding:10px 0px; } .notice_item:after{ content:"";clear:both;display:block; } .color_32{background-color:RGB(146,208,80);} .color_31{background-color:RGB(0,176,240);} </style> </head> <body style="overflow:auto;"> <div class="myStaticPage_wrapper"> <div class="navbar" style="background:#ababab;height:40px;line-height:40px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="center" > ← 게시판 </div> <div class="right"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> </div> </div> <div class="menu" style="margin-bottom:2px"> <div style="margin-left:-1px;width:50%;float:left;"> <div style="padding-right:10px;text-align:right"> 공지사항 </div> </div> <div style="width:50%;border-left:1px solid #cdcdcd;float:left;"> <div style="padding-left:10px;text-align:left"> 이벤트 </div> </div> </div> <div class="clear"></div> <div class="menu" style="border-width:0px;margin:3px 0px 0px 0px;padding:0px;"> <div style="margin-left:-1px;width:50%;float:left;"> <div style="padding:5px 10px 5px 0px;text-align:center;margin-left:20px;background-color:RGB(255,192,0);"> 전체공지 </div> </div> <div style="width:50%;border-left:1px solid #cdcdcd;float:left;"> <div style="padding:5px 0px 5px 10px;text-align:center;margin-right:20px;background-color:RGB(255,192,0);"> 내 공지 </div> </div> </div> <div class="clear"></div> <div class="notice_box list_box" style="margin-top:10px"> <?php //페이징 없이??? //운영단??? //일단 더보기로 구현해보자.... foreach($notices as $item){ echo ' <div class="notice_item item_'.$item->게시판_id.'" style="border-bottom:1px solid #cdcdcd"> <div style="width:25%;float:left;text-align:center;"> <div style="margin:0px 5px;"> <div class="color_'.$item->머릿글종류.'" style="padding:5px 0px;border:1px solid #cdcdcd;border-radius:5px;margin:auto;max-width:120px;">' .$item->코드명. '</div> </div> </div> <div style="width:60%;float:left;text-align:left;"> <div style="margin-left:5px">'.$item->글제목.'</div> </div> <div style="width:15%;float:left;text-align:center;font-size:12px;"> '.date_format(date_create($item->등록일),"m.d").' </div> </div> <div class="clear"></div> <div class="contentBox contentBox_'.$item->게시판_id.'"> <div style="border:1px solid #cdcdcd;border-radius:5px;padding:5px;">'.$item->글내용.'</div> </div> '; } ?> </div> <!-- <div id="btn_more" style="margin:10px;background-color:gray;text-align:center;padding:10px 0px;"> 더보기 </div> --> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js?timestamp=201512210800"></script> <script> $(document).ready(function(){ $(".notice_item").each(function(idx){ $(this).click(function(){ if($(".contentBox:eq("+idx+")").css("display")=="none"){ $(".contentBox").hide(); $(".contentBox:eq("+idx+")").fadeIn(); } else{ $(".contentBox:eq("+idx+")").hide(); } }); }); }); </script> </body> </html><file_sep> <div class="toggle_box_content"> <div id="view_time1" style="padding-top: 10px" value=" <?php if($date_diff_day < 1){ echo $current_event->d_total; }else{ echo $current_event->d_day; } ?>">참가기간:</div> <div class="item" style="float: left; width: 33.33333%"> <div style="font-size: 12px;">목표걸음수</div> <div style="font-size: 20px; color: RGB(255, 205, 51);"><?=$alldata->목표걸음수?></div> </div> <div class="item" style="float: left; width: 33.33333%"> <div style="font-size: 12px;">누적걸음수</div> <div style="font-size: 20px; color: RGB(255, 205, 51);"> <?=$alldata->누적걸음수?> </div> </div> <div class="item" style="float: left; width: 33.33333%"> <div style="font-size: 12px;">진행률</div> <div style="font-size: 20px; color: RGB(255, 205, 51);"><?=$complete_percent?>%</div> </div> <div style="clear: both;"></div> <div id="view_time2" style="margin-top: 10px" value="<?=$current_event->s_day?>"></div> <div style="margin: 10px 0px; color: RGB(119, 147, 173); font-size: 12px;">완보성공지수: 불안</div> <div class="item" style="float: left; width: 33.33333%"> <div style="font-size: 12px;">남은걸음수</div> <div style="font-size: 20px; color: RGB(255, 205, 51);"> <?=$alldata->남은걸음수?> </div> </div> <div class="item" style="float: left; width: 33.33333%"> <div style="font-size: 12px;">일평균걸음수</div> <div id = "aver_perday_id" style="font-size: 20px; color: RGB(255, 205, 51);"> <?=$per_day_walking?> </div> </div> <div class="item" style="float: left; width: 33.33333%"> <div style="font-size: 12px;">일평균 추천걸음수</div> <div id = "recom_perday_id" style="font-size: 20px; color: RGB(255, 205, 51);"><?=$recommand_per_walking?></div> </div> <div style="clear: both;"></div> <div id="pop_up_page" display="none"></div> </div> <!-- 토글 버튼 --> <div class="toggle_box"> <div style="height:7px;width:100%;background-color:black;">&nbsp;</div> <div class="toggle_btn"> <div class="toggle_btn_line1"></div> <div class="toggle_btn_line2"></div> </div> </div> <!-- 걸음 정보 --> <div class="info_box"> <div class="timer"> <div class="i_day"></div> <div class="i_timer"></div> </div> <div class="i_comment"> <div id="ticker-roll" class="ticker"> <ul> <li>대회 종료 시까지 트랙을 완보 해야 합니다.</li> <li id="recom_perday_id2"></li> </ul> </div> </div> </div> <script> <?php if($flag == 0){ //대회가 종료됬다면, ?> $('.toggle_box').addClass('end'); $('.info_box').addClass('end'); $('.info_box').find('.i_comment').html("<div>축하합니다!<br><?=$user_info['name']?>님은 완보에 성공하였습니다!</div>"); <?php }else{ ?> $('.toggle_box').addClass('ing'); $('.info_box').addClass('ing'); <?php } ?> function calculate(diff){ var currSec = 1; <?php // 밀리세컨 ?> var currMin = 60 ; <?php // 초 * 밀리세컨 ?> var currHour = 60 * 60 ; <?php // 분 * 초 * 밀리세컨 ?> var currDay = 24 * 60 * 60 ; <?php // 시 * 분 * 초 * 밀리세컨 ?> var day = parseInt(diff/currDay); <?php //d-day 일 ?> var hour = parseInt(diff/currHour); <?php //d-day 시 ?> var min = parseInt(diff/currMin); <?php //d-day 분 ?> var sec = parseInt(diff/currSec); <?php //d-day 초 ?> var viewHour = "0"; if(hour-(day*24) < 10){ viewHour = viewHour.concat(String(hour-(day*24))); }else{ viewHour = hour-(day*24); } var viewMin = "0"; if(min-(hour*60) < 10){ viewMin = viewMin.concat(String(min-(hour*60))); }else{ viewMin = min-(hour*60); } var viewSec = "0"; if(sec-(min*60) < 10){ viewSec = viewSec.concat(String(sec-(min*60))); }else{ viewSec = sec-(min*60); } var diff_time = new Array(4); diff_time[0] = String(day); <?php //일 차이?> diff_time[1] = String(viewHour);<?php //시간 차이?> diff_time[2] = String(viewMin); <?php //분 차이?> diff_time[3] = String(viewSec); <?php //초 차이?> return diff_time; } $(document).ready(function() { <?php //남은시간 = 대회종료일 - 현재 ?> setReaminTime = function (){ <?php //함수로 만들어 준다. ?> var date_end = $("#view_time1").attr("value"); <?php //현재날짜 ?> var date_now = parseInt(new Date().getTime()/1000); <?php //월에서 1 빼줘야 함 ?> var diff = date_end - date_now; var diff_time = calculate(diff); var temp = <?= $date_diff_day ?>; if(temp >= 1){ diff_time[0] = temp; } viewStr = diff_time[0] +" "+diff_time[1]+":"+diff_time[2]+":"+diff_time[3]; if(<?=$flag?>== 0){ <?php //대회가 지났다면, ?> $("#view_time1").html("<span style='font-size: 13pt;'><b> -- </b></span>"); $('.i_day').html("<span style='font-size: 12pt;'>-:</span><br>"); $('.i_timer').html("<span style='font-size: 12pt;margin-right:100px;'>-:-</span><br>"); }else{ <?php //대회가 종료되지 않았다면 ?> $("#view_time1").html("<span style='font-size: 13pt;'><b> D-"+viewStr+"</b></span><br>"); $('.i_day').html("<span><b> D-"+ diff_time[0] +"</b></span>"); $('.i_timer').html("<span><b>"+ diff_time[1] + ":" + diff_time[2] + ":" + diff_time[3]+ "</b></span>"); } } setByTime = function(){ <?php //지난시간 = 현재 - 대회시작일 ?> var date_start = $("#view_time2").attr("value"); <?php //현재날짜 ?> var date_now = parseInt(new Date().getTime()/1000); <?php //월에서 1 빼줘야 함 ?> var diff = date_now - date_start; //날짜 더하기 var diff_time = calculate(diff); viewStr = diff_time[0] +" "+diff_time[1]+":"+diff_time[2]+":"+diff_time[3]; $("#view_time2").html("<span style='font-size: 13pt;'><b> S-"+viewStr+"</b></span>"); } setReaminTime(); setByTime(); setInterval('setReaminTime()',1000); setInterval('setByTime()',1000); }); </script> <file_sep><!-- 트랙 정보 --> <div class="track_title navbar"> <div class="tit"><?=$contest_info[0]->제목?></div> <div class="share">알림</div> </div> <div class="track_content" style="background:url(<?=IMG_PATH?>MainActivity_2/track_bg.png);background-size:cover;"> <div style="background:rgba(0, 0, 0, 0.5);"> <!-- 오늘의 걸음수 --> <div class="walk_box" style="color:white;font-size:12px;color:#ababab;"> <div style="position:relative;padding:10px 0px;"> <div>오늘의 걸음수</div> <div id="step_cnt" style="font-size:25px;color:RGB(255,205,51)">0</div> <div style="position:absolute;left:20%;top:20px;"><img style="width:30px;" src="<?=IMG_PATH?>MainActivity_2/main_arrow_left.png"/></div> <div style="position:absolute;right:20%;top:20px;"><img style="width:30px;" src="<?=IMG_PATH?>MainActivity_2/main_arrow_right.png"/></div> </div> </div> <!-- 트랙 컴포넌트 --> <div class="track_box" > <div class="canvas" style="width:100%;font-size:0px;"> <canvas width='800' height='600' id='cv'/> </div> <div class="friend_comp" style="display:-webkit-box;height:60px;line-height:30px;padding:5px 20px;"> <div style="width:80%;height:100%;text-align:left;overflow-x:scroll;overflow-y:hidden;"> <div style="display:-webkit-inline-box;"> <div style="height:100%;line-height:1em;margin:0px 5px;position:relative;"><img src="<?=IMG_PATH?>MainActivity_2/profile1.jpg" style="width:46px;height:46px;border-radius:30px;"/><p style="padding:0px;margin:0px;text-align:center;">최주현</p></div> <div style="height:100%;line-height:1em;margin:0px 5px;position:relative;"><img src="<?=IMG_PATH?>MainActivity_2/profile2.jpg" style="width:46px;height:46px;border-radius:30px;"/><img src="<?=IMG_PATH?>MainActivity_2/badge_red.png" style="position:absolute;bottom:10px;right:-5px;background:#101313;border-radius:20px;width:25px;"/><p style="padding:0px;margin:0px;text-align:center;">조현철</p></div> <div style="height:100%;line-height:1em;margin:0px 5px;position:relative;"><img src="<?=IMG_PATH?>MainActivity_2/profile3.jpg" style="width:46px;height:46px;border-radius:30px;"/><img src="<?=IMG_PATH?>MainActivity_2/badge_blue.png" style="position:absolute;bottom:10px;right:-5px;background:#101313;border-radius:20px;width:25px;"/><p style="padding:0px;margin:0px;text-align:center;">이병현</p></div> <div style="height:100%;line-height:1em;margin:0px 5px;position:relative;"><img src="<?=IMG_PATH?>MainActivity_2/profile.png" style="width:46px;height:46px;border-radius:30px;"/><p style="padding:0px;margin:0px;text-align:center;">이종호</p></div> </div> </div> <div style="width:10%;height:100%;text-align:left;"> <div style="display:-webkit-inline-box;"> <div style="height:100%;line-height:1em;margin:0px 5px;"><img src="<?=IMG_PATH?>MainActivity_2/profile.png" style="height:80%;"/></div> </div> </div> </div> <div comp_prop='marquee_main_2_comp'></div> </div> </div> </div> <!-- 진행 정보 --> <div class="track_box_info" style="background-color:RGB(81,81,81);color:white;font-size:12px;padding:10px 0px;"> <div class="item rate" style="float:left;width:33.33333%"> <div class="i1">진행률</div> <div class="i2"><?=$stat_info["rate"]?>%</div> <div class="i3">누적걸음(필수)</div> </div> <div class="item stamp" style="float:left;width:33.33333%"> <div class="i1">스템프</div> <div class="i2"><?=$stat_info["stamp"]?></div> <div class="i3">핫스팟 방문(필수)</div> </div> <div class="item prize" style="float:left;width:33.33333%"> <div class="i1">경품추첨권</div> <div class="i2"><?=$stat_info['prize'][0]->cnt?></div> <div class="i3">미션참여(선택)</div> </div> </div> <div style="clear:both;"></div> <!-- 대회 정보 배너 --> <div class="carousel-wrapper" style="color:white;background:#515151;"> <div class="owl-carousel owl-theme"> <div class="item"><img src="<?=IMG_PATH?>MainActivity_2/banner1.png" style="width:100%;"/></div> <div class="item" style="display:none"><img src="<?=IMG_PATH?>MainActivity_2/banner2.png" style="width:100%"/></div> <div class="item" style="display:none"><img src="<?=IMG_PATH?>MainActivity_2/banner3.png" style="width:100%"/></div> </div> </div> <script> $(".owl-carousel").owlCarousel({ items:1, loop:false, nav:false, dots:true, margin:0, onInitialized :function(){ $(".owl-carousel .item").show(); } }); var tracker = new Tracker(); setTimeout(function(){ var w_height = $(window).height(); var w_width = $(window).width(); var cv_height = ( w_height - $('canvas').offset().top ) - 223; if(w_width<360){ cv_height *= 1.7 } var stamp_arr = JSON.parse('<?=json_encode($stamp_info)?>'); var checked_arr = JSON.parse('<?=json_encode($checked_info)?>'); var stamp_pg = new Array(); tracker.params.canvas.height = cv_height; tracker.params.track.logo = "<?=경로_걷기대회?>cannon/logo.png"; tracker.init(); tracker.drawTrack(); for(i=0;i<stamp_arr.length;i++){ var checked = false; for(j=0;j<checked_arr.length;j++){ if(checked_arr[j]['위시_id'] == stamp_arr[i]['위시_id']){ checked = true; break;} else{ checked = false; } } var rate = (stamp_arr[i]['위시기준']/stamp_arr[i]['목표걸음수'])*100 tracker.drawStamp(stamp_arr[i]['위시_id'], stamp_arr[i]['위시제목'],checked,rate); stamp_pg.push(rate); } tracker.drawPin(<?=$stat_info['rate']?>,stamp_pg); },100); $.post("/marquee/main_2_comp/", {}, function(response){ $("div[comp_prop='marquee_main_2_comp']").html(response); $("div[comp_prop='marquee_main_2_comp']").find("marquee").on("click",function(){ $(".toggle_btn").click(); }); }); $("div[comp_prop='contest_comp']").find(".track_box_info").find(".rate").on("click",function(){ $(".toggle_btn").click(); }); $("div[comp_prop='contest_comp']").find(".track_box_info").find(".stamp").on("click",function(){ myApp.pickerModal('.picker-get-stamp'); }); $("div[comp_prop='contest_comp']").find(".track_box_info").find(".prize").on("click",function(){ myApp.pickerModal('.picker-get-prize'); }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Hotspot extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library(array('session_common','walk_common')); $this->session_common->checkSession("user"); $this->load->model('hotspot_model'); } /* *조진근 *20170316 *hotspo_list 페이지로 연결 *핫스팟 리스트에 대한 $id값을 통하여 이동됨 */ function hotspotList(){ $temp = $this->session_common->getSession("user"); $user = $temp["user_id"]; $data["hotspots"] = $this->hotspot_model->getHotspotList($user); $this->load->view ("activity/header_p"); $this->load->view ("hotspot/hotspot_list", $data); $this->load->view ("activity/footer"); } /* *조진근 *20170329 * 프로모션 리스트를 가져옴 */ function hotspotListProm($id=''){ $temp = $this->session_common->getSession("user"); $user = $temp["user_id"]; $data["hotspots"] = $this->hotspot_model->getPromotionList($user, $id); $this->load->view ("activity/header_p"); $this->load->view ("hotspot/hotspot_list", $data); $this->load->view ("activity/footer"); } function hotspotListWithGoogleMap(){ $temp = $this->session_common->getSession("user"); $user = $temp["user_id"]; $contest = $temp["contest_id"]; $data["hotspots"] = $this->hotspot_model->getHotspotList($user); $data["state"] = $this->hotspot_model->getHotspotState($user, $contest); $this->load->view ("activity/header_p"); $this->load->view ("hotspot/hotspot_list_with_googleMap", $data); $this->load->view ("activity/footer"); } /* * 조진근 * 20170316 * hotspo_view 페이지로 연결 */ function hotspotView($id,$select=''){ if($select == ''){ $data["more"] = FALSE; } else{ $data["more"] = TRUE; } $user = $this->session_common->getSession("user")["user_id"]; $data["hotspot"] = $this->hotspot_model->getHotspotView($user ,$id); //파일 열기 $data["article"] = $data["hotspot"]->핫스팟_html; $this->load->view ("activity/header_p"); $this->load->view ("hotspot/hotspot_view",$data); $this->load->view ("activity/footer"); } /* * 조진근 * 20170316 * insertCheckIn * 경품추첨권 테이블에 경품권을 얻은 사용자 정보 삽입 */ function insertCheckIn(){ $user_id = $this->session_common->getSession("user")["user_id"]; $hotspot_id = trim($this->input->post("hotspot_id")); $this->hotspot_model->insertDB($user_id, $hotspot_id); } } ?> <file_sep><!-- Views --> <div class="views"> <div class="view view-main"> <div class="pages"> <!-- page --> <div data-page="MainActivity_1" class="page" style="background:#fff;overflow:hidden;"> <div class="page-content" style="background:#0d0d0d;overflow-x:hidden;"> <!-- navbar --> <div class="navbar" style="background:#0d0d0d;height:50px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="center"> <a href="/activity/MainActivity_1/" class="link external"> WISH WALK </a> </div> <div class="right"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> </div> </div> <!-- navbar END --> <!-- pedometer --> <div comp_prop="step_comp" class="navbar" style="background:#0a0a0a;height:70px;"> </div> <!-- pedometer --> <div comp_prop="marquee_main_1_comp" style="background-color:#ababab;"> </div> <!-- poster --> <div comp_prop="poster" style="background-color:#ababab;"> </div> <!-- poster END --> <!-- Competition Dashboard --> <div comp_prop="competit_dash" style="height:auto"> </div> <!-- Competition Dashboard END--> <!-- Ad Banner --> <div comp_prop="ad_banner" style="height:auto;line-height:0px;"> <img src="<?=IMG_PATH?>MainActivity_1/ad.jpg" style="width:100%;"> </div> <!-- Ad Banner END--> <!-- MAGAZINE LIST --> <div comp_prop="magazine_comp" style="height:auto"> </div> <!-- MAGAZINE LIST END--> <!-- EVENT LIST --> <div comp_prop="event_list" style="height:auto"> </div> <!-- EVENT END--> <!-- CHECK IN LIST --> <div comp_prop="checkin_list" style="height:auto"> </div> <!-- CHECK IN LIST END--> <div class="footer" style="background:#808080;padding:10px 0px;"> <div style="font-size:1em;text-align:center;position:relative;text-align:center;"> <p style="font-size:1.7em;margin:auto;">행복한걸음</p> <p style="font-size:1.7em;margin:auto;">WISH WALK</p> <br> <p style="margin:auto;">related</p> <div style="margin-top:10px;">&nbsp;한국관광공사&nbsp;문화관광부&nbsp;굿네이버스&nbsp;서울시청&nbsp;포커스뉴스&nbsp;</div> </div> </div> </div> </div> <!-- page END --> </div> </div> </div> <style> .owl-theme .owl-nav.disabled+.owl-dots{margin-top:0px;position:absolute;bottom:0px;left:0;right:0;} .owl-theme .owl-dots .owl-dot span{margin:2px 3px;width:5px;height:5px;} .card-content .pic_wrapper{width:100%;} @media screen and (orientation:landscape) { .owl-carousel .item{height:auto !important;} .card-content .pic_wrapper{height:auto !important;} .card-content img{height:auto !important;} } </style> <script> var myApp = new Framework7({ material: true, pushState : true, }); var mainView = myApp.addView('.view-main'); var $$ = Dom7; var w_width = $(window).width(); var w_height = $(window).height(); var poster_info_anim_flag = true; </script> <script> $(document).ready(function() { $.post("/statistics/step_comp/", {}, function(response){ $("div[comp_prop='step_comp']").html(response); }); $.post("/marquee/main_1_comp/", {}, function(response){ $("div[comp_prop='marquee_main_1_comp']").html(response); }); $.post("/walk/posterlist_comp/", {}, function(response){ $("div[comp_prop='poster']").html(response); resetUI(); $(".owl-carousel").owlCarousel({ items:1, loop:false, nav:false, dots:false, stagePadding: 55, margin: 20, onInitialized :function(){ $(".owl-carousel .item").show(); $("div[comp_prop='entrance_button']").find("a").attr("href",$(".owl-item").eq(0).find("a").attr("href")); $("div[comp_prop='entrance_button']").find(".walk_tit").text($(".owl-item").eq(0).find("h4").text()); } }); $(".owl-carousel").on('changed.owl.carousel', function(event) { $("div[comp_prop='entrance_button']").find("a").attr("href",$(".owl-item").eq(event.item.index).find("a").attr("href")); $("div[comp_prop='entrance_button']").find(".walk_tit").text($(".owl-item").eq(event.item.index).find("h4").text()); }); $("div[comp_prop='poster_info']").each(function(){ $(this).click(function(){ if($(this).find("div[comp_prop='poster_info_a']").css('display') == 'block'){ $(this).find("div[comp_prop='poster_info_a']").hide(); $(this).find("div[comp_prop='poster_info_b']").show(); } else{ $(this).find("div[comp_prop='poster_info_a']").show(); $(this).find("div[comp_prop='poster_info_b']").hide(); } }); }); }); $.post("/walk/getWishTrack/", {}, function(response){ $("div[comp_prop='competit_dash']").html(response); }); $.post("/magazine/magazine_comp/", { type:"h" }, function(response){ $("div[comp_prop='magazine_comp']").html(response); }); $.post("/event/walkMain/", {}, function(response){ $("div[comp_prop='event_list']").html(response); }); $.post("/promotion/checkinPreview/", {}, function(response){ $("div[comp_prop='checkin_list']").html(response); }); }); $(window).resize(function(){ resetUI(); }); function resetUI(){ $(".owl-carousel .item").height($(window).height()-214+"px"); $(".card-content .pic_wrapper").height($(window).height()-320+"px"); } </script> <file_sep><div class="profile_box"> <div class="profile_top"> <div style="position:absolute; top:30%; align:center; width:100%"> <div class="profilethumb"><img src="<?=경로_사용자?><?=$joininfos->사진?>" alt="프로필사진"></div> </div> <div class="top_nameinfo" style="width:100%; top:80%; font-size:30px; margin-top:10px; text-align:center;"><?=$stepinfos->이름?></div> </div> <div class="profile_middle"> <div class="middle_info"> <div class="sub_middle_info"> <b><?=$friendcnt?></b> </div>친구수 </div> <div class="middle_info"> <div class="sub_middle_info"> <b><?=$joininfos->참여대회수?></b> </div>대회 참가수 </div> <div class="middle_info"> <div class="sub_middle_info"> <?php if($stepinfos->일일평균걸음수 == null){ ?> <b>X</b> <?php }else{ ?> <b><?=$stepinfos->일일평균걸음수?></b> <?php } ?> </div>일일 평균 걸음 수 </div> </div> <div class="profile_bottom"> <div style="padding:5px; text-align:left;">최근 참여 대회</div> <?php foreach($recentEventInfos as $recentEventInfo){ ?> <div class="bottom_info"> <div class="sub_bottom_info"> <img src="<?=경로_걷기대회?><?=$recentEventInfo->대회포스터?>" alt="참가대회 이미지"> </div><?=$recentEventInfo->제목?> </div> <?php } ?> </div> <table style="width:100%;height:10%"> <tr> <td><div class="sendbtn">쪽지보내기</div></td> <td><div class="circlebtn" style="left:10%"><p style="margin-top:30%;">응원하기</p></div></td> <td><div class="circlebtn" style="left:15%"><p style="margin-top:30%;">약올리기</p></div></td> </tr> </table> </div><file_sep> <div class="toolbar" style="background:#0d0d0d;"> <div class="toolbar-inner"> <div class="left" style="margin-left:15px;"><?=$contest[0]->제목?></div> <div class="right" style="margin-right:15px;"><a href="#" class="close-picker" style="color:white;">닫기</a></div> </div> </div> <div class="picker-modal-inner"> <?php if($state=="get"){ ?> <div class="content-block" style="text-align:center;line-height:2em;"> <h2>경품추첨권 현황 : <?=$prize[0]->cnt?>개</h2> <img src="<?=경로_경품?>card_yes.png" style="width:100px;"/> <p style="line-height:1.5em;">조금만 더 힘내세요~!</p> </div> <?php }else{ ?> <div class="content-block" style="text-align:center;line-height:2em;"> <h1>축하합니다!</h1> <h3>경품추첨권 1개를 획득하셨습니다</h3> <img src="<?=경로_경품?>card_yes.png" style="width:100px;"/> <p style="line-height:1.5em;">아래 버튼을 클릭하시면 경품을 받을 수 있습니다.</p> <a href="#" id="set_prize" class="button button-raised button-fill color-pink" style="color:white;margin-top:15px;">경품추첨권 받으러가기</a> </div> <?php } ?> </div> <file_sep> <?php foreach($friendIds as $friendId){ ?> <?php $date_temp=date_create($friendId->전송일시); $date_time = date_format($date_temp,"h:i"); $date_ampm = date_format($date_temp,"A"); $date_ampm =$date_ampm =="AM"?"오전":"오후"; ?> <?php if($friendId->전송_id==$user_id) { ?> <li class="group_box" msid="<?=$friendId->쪽지_id ?>"> <div style="position:relative;margin-right:10px"> <table style="max-width:80%;table-layout:fixed;" align="right"> <tr> <td> <div class="time" style="margin-left:5px;" > <?=$date_ampm?> <?=$date_time?> </div> </td> <td style="max-width:60%"> <div class="even"> <?=$friendId-> 내용?> </div> </td> </tr> </table> </div> </li> <?php }else{ ?> <li msid="<?=$friendId->쪽지_id ?>"> <div style="position:relative;"> <table style="max-width:90%;table-layout:fixed;"> <tr> <td><div class="mythumb3"><img src="<?=경로_사용자?><?=$friendId->사진?>" alt=""></div></td> <td style="max-width:70%"> <div><?=$friendId->전송_id?></div> <div class="odd"> <?=$friendId->내용?> </div> </td> <td> <div class="time" style="margin-left:5px;" > <?=$date_ampm?> <?=$date_time?> </div> </td> </tr> </table> </div> </li> <?php } ?> <?php } ?> <file_sep><style> .table_container{ margin:0px 0px 0px 10px; } .table_layer{ width:100%; background-color:white; table-layout:fixed; } </style> <div class="sub_menu_tab"> <ul> <li id="sub_left" onclick="friendsReload2(1);changeFont(4)">내 친구초대</li> <li id="sub_right" onclick="friendsReload2(2);;changeFont(5)">대회참여 초대</li> </ul> </div> <div class="res" style="margin-top:100px;"> </div> <script> $(document).ready(function() { friendsReload2(1); changeFont(4); }); <?php //소메뉴 클릭시 페이지 이동을 위한 함수 ?> function friendsReload2(idx){ switch(idx){ case 1: $(".res").load("/friends/inviteFriends"); break; case 2: $(".res").load("/friends/inviteEvents"); break; } }; </script><file_sep><style> .celtitle{ font-weight:bold; font-size:20px; margin:20px; } .celebrities{ background-color:green; color:white; font-weight:bold; padding:5px; margin-top:20px; margin-bottom:10px; } </style> <div class="celMessage_box" style="width:100% height:100%"> <?php foreach($celMessages as $celMessage){ ?> <div class="celebrities"> <?= $celMessage -> 내용 ?> </div> <div align="center"> <video controls src="<?= 경로_메시지?><?= $celMessage -> 동영상경로 ?>" width="80%" height="20%"> </video> </div> <?php } ?> </div> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Friends extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('friends_model'); } /* * index * 최재성 * 20170314 * 친구 초기화면 */ function index(){ $user_id = $this->session_common->getSession("user")["user_id"]; $this->load->view ( "activity/header_p" ); $this->load->view("friends/friendIndex_view"); $this->load->view ( "activity/footer" ); } /* * friendList * 최재성 * 20170314 * 친구목록 대메뉴 */ function friendList(){ $user_id = $this->session_common->getSession("user")["user_id"]; $this->load->view("friends/friendsList_view"); } /* * invite * 최재성 * 20170320 * 친구초대 소메뉴 */ function invite(){ $user_id = $this->session_common->getSession("user")["user_id"]; $this->load->view("friends/invite_view"); } /* * myFriends * 최재성 * 20170315 * 친구목록 화면 */ function myFriends(){ $user_id = $this->session_common->getSession("user")["user_id"]; $data["friendIds"]= $this->friends_model->myFriends($user_id); $data["friendcnt"]= $this->friends_model->cntFriends($user_id); $this->load->view("friends/myFriends_view",$data); } /* * friendsInfo * 최재성 * 20170315 * 친구프로필 화면 */ function friendsInfo(){ $user_id = $this->session_common->getSession("user")["user_id"]; $friend_id= (string) $this->input->post('friend_id'); $data["friendcnt"]= $this->friends_model->cntFriends($friend_id); //친구 수 $data["stepinfos"]= $this->friends_model->avgStepInfo($friend_id); $data["joininfos"]= $this->friends_model->joinInfo($friend_id); $data["recentEventInfos"]= $this->friends_model->recentEventInfo($friend_id); $this->load->view("friends/friendsInfo_view",$data); } /* * msCheck * 최재성 * 20170315 * 쪽지보기 화면 */ function msCheck(){ $user_id = $this->session_common->getSession("user")["user_id"]; $data["userId"]=$user_id; $data["friendIds"]= $this->friends_model->msCheck($user_id); $this->load->view("/friends/msCheck_view",$data); } /* * refreshCheck * 최재성 * 20170403 * 쪽지보기 화면 refresh */ function refreshCheck(){ $user_id = $this->session_common->getSession("user")["user_id"]; $data["userId"]=$user_id; $data["friendIds"]= $this->friends_model->msCheck($user_id); $this->load->view("/friends/msCheck_view_list",$data); } /* * refreshMs * 최재성 * 20170329 * 채팅 통신 */ function refreshMs(){ $user_id = $this->session_common->getSession("user")["user_id"]; $group_id= (string) $this->input->post('groupId'); $msId=trim($this->input->post('msId')); $data["groupIds"]= $group_id; $data["user_id"] = $user_id; $data["friendIds"] = $this->friends_model->refreshMs($group_id,$msId); $result=$this->friends_model->checkYN($user_id,$group_id); $this->load->view("/friends/msRoom_view_list",$data); } /* * addMs * 최재성 * 20170315 * 더보기 메세지 */ function addMs(){ $user_id = $this->session_common->getSession("user")["user_id"]; $group_id= (string) $this->input->post('groupId'); $upperMsId= (string) $this->input->post('upperMsId'); if($group_id==null &&$upperMsId==null){ return; }else{ $data["friendIds"]= $this->friends_model->addMs($group_id,$upperMsId); $data["user_id"] = $user_id; $this->load->view("/friends/msRoom_view_list",$data); } } /* * msRoom * 최재성 * 20170315 * 채팅방 화면(쪽지 보기를 통한 접근) */ function msRoom(){ $user_id = $this->session_common->getSession("user")["user_id"]; $group_id= (string) $this->input->post('groupId'); $data["user_id"] = $this->session_common->getSession("user")["user_id"]; $data["friendIds"]= $this->friends_model->msRoom($group_id); $minRow=$this->friends_model->minMs($group_id); $totalminMs=$this->friends_model->totalminMs($group_id); $msCnt= $this->friends_model->msRoomCnt($group_id); $result=$this->friends_model->checkYN($user_id,$group_id); $data["groupIds"]= $group_id; $data["msCnt"]= $msCnt; $data["upperMsId"]= $minRow; $data["totalminMs"]= $totalminMs; $this->load->view ( "activity/header_p" ); $this->load->view("/friends/msRoom_view",$data); $this->load->view ( "activity/footer" ); } /* * msRoomOther * 최재성 * 20170315 * 채팅방 화면(내 친구 탭에서 쪽지 버튼을 통한 접근) */ function msRoomOther(){ $friend_id= (string) $this->input->post('friend_id'); $user_id = $this->session_common->getSession("user")["user_id"]; $row = $this->friends_model->msRoomOther($friend_id,$user_id); if(count($row) == 0){ $row = $this->friends_model->msRoomNew($friend_id,$user_id); } $group_id=$row->그룹_id; $minRow=$this->friends_model->minMs($group_id); $totalminMs=$this->friends_model->totalminMs($group_id); $msCnt= $this->friends_model->msRoomCnt($group_id); $updateYN = $this->friends_model->checkYN($user_id,$group_id); //확인여부를 체크하여 New 아이콘 없앰 $data["groupIds"]= $group_id; $data["msCnt"]= $msCnt; $data["upperMsId"]= $minRow; $data["totalminMs"]= $totalminMs; $data["user_id"] = $this->session_common->getSession("user")["user_id"]; $data["friendIds"]= $this->friends_model->msRoom($group_id); $this->load->view ( "activity/header_p" ); $this->load->view("/friends/msRoom_view",$data); $this->load->view ( "activity/footer" ); } /* * insertContents * 최재성 * 20170315 * 채팅방 내용저장 */ function insertContents(){ $user_id = $this->session_common->getSession("user")["user_id"]; $contents=trim($this->input->post('contents')); $group_id=trim($this->input->post('groupId')); $msId=trim($this->input->post('msId')); $data["groupIds"]= $group_id; $data["user_id"] = $user_id; $data["friendIds"] = $this->friends_model->insertContents($group_id,$user_id,$contents,$msId); $this->load->view("/friends/msRoom_view_list",$data); } /* * inviteFriends * 최재성 * 20170317 * 친구초대 */ function inviteFriends(){ $user_id = $this->session_common->getSession("user")["user_id"]; $data["friendIds"]= $this->friends_model->inviteFriend($user_id); $data["userIds"]= $this->friends_model->inviteFriend2($user_id); $this->load->view("/friends/inviteFriend_view",$data); } /* * acceptEvents * 최재성 * 20170328 * 대회참여 수락 */ function acceptEvents(){ $user_id = $this->session_common->getSession("user")["user_id"]; $event_id=trim($this->input->post('event_id')); //$friend_id=trim($this->input->post('friend_id')); $result=$this->friends_model->acceptEvents($event_id,$user_id); $result=$this->friends_model->deletetEvents($event_id,$user_id); return $result; } /* * rejectEvents * 최재성 * 20170328 * 대회참여 수락 */ function rejectEvents(){ $invite_id=trim($this->input->post('invite_id')); $result=$this->friends_model->rejectEvents($invite_id); return $result; } /* * inviteEvents * 최재성 * 20170317 * 대회참여 초대 */ function inviteEvents(){ $user_id = $this->session_common->getSession("user")["user_id"]; $data["friendIds"]= $this->friends_model->inviteEvents($mode="1",$user_id); $data["userIds"]= $this->friends_model->inviteEvents($mode="2",$user_id); $this->load->view("/friends/inviteEvent_view",$data); } /* * deleteMs * 최재성 * 20170316 * 채팅방 삭제 */ function deleteMs(){ $user_id = $this->session_common->getSession("user")["user_id"]; $group_id=trim($this->input->post('groupId')); $result = $this->friends_model->deleteMs($group_id, $user_id); return $result; } /* * deleteFriends * 최재성 * 20170314 * 친구삭제 */ function deleteFriends(){ $user_id = $this->session_common->getSession("user")["user_id"]; $friend_id=trim($this->input->post('friend_id')); $state = $this->state=16; $result = $this->friends_model->deleteFriends($user_id, $friend_id, $state); $result = $this->friends_model->deleteFriends($friend_id, $user_id, $state); return $result; } /* * rejectFriends * 최재성 * 20170317 * 친구 초대 거절 */ function rejectFriends(){ $user_id = $this->session_common->getSession("user")["user_id"]; $state = $this->state=15; $friend_id=trim($this->input->post('friend_id')); $result=$this->friends_model->rejectFriends($user_id,$friend_id,$state); $result=$this->friends_model->rejectFriends2($user_id,$friend_id,$state); return $result; } /* * acceptFriends * 최재성 * 20170317 * 친구 초대 수락 */ function acceptFriends(){ $user_id = $this->session_common->getSession("user")["user_id"]; $state = $this->state=14; $friend_id=trim($this->input->post('friend_id')); $result=$this->friends_model->acceptFriends($friend_id, $user_id,$state); return $result; } /* * index * 최재성 * 20170314 * 초대 기본화면 */ function inviteIndex(){ $user_id = $this->session_common->getSession("user")["user_id"]; $this->load->view ( "activity/header_p" ); $this->load->view("friends/inviteIndex_view"); $this->load->view ( "activity/footer" ); } /* * inviteList * 최재성 * 20170314 * 초대 초기화면 */ function inviteList(){ $user_id = $this->session_common->getSession("user")["user_id"]; $event_id = $this->session_common->getSession("user")["contest_id"]; $data["invitefriends"]= $this->friends_model->inviteList($user_id,$event_id); $this->load->view("friends/inviteList_view",$data); } /* * insertInvite * 최재성 * 20170314 * 초대한 친구 저장 */ function insertInvite(){ $user_id = $this->session_common->getSession("user")["user_id"]; $event_id = $this->session_common->getSession("user")["contest_id"]; $friend_id=trim($this->input->post('friend_id')); $result = $this->friends_model->insertInvite($event_id, $user_id, $friend_id); return $result; } } ?><file_sep><?php header("Cache-Control: no-cache"); header("Pragma: no-cache"); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Pragma" content="no-cache" /> <meta http-equiv="Expires" content="-1" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui"> <title>WishWalk</title> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/jquery.min.js"></script> </head> <body> <file_sep><style> body{margin:0px;} .chat_box { display: inline-block; color: #34495e; margin: 0; width:100%; overflow:auto; background-color:#fdffa8; } .chat_box .addMs { position:fixed; left:0; right:0; top:0px; z-index:100; width:90%; height:20px; background-color:#ffca47; text-align:center; margin:10px 0px 10px 7px; padding:10px; border-radius:10px; opacity:0.4; } .chat_box ul { -webkit-padding-start: 0px; width:100%; } .chat_box li{ display: table; font-size: 12px; line-height: 25px; margin-bottom:10px; width:100%; } .chat_box .odd { display: block; padding: 10px; margin-bottom: 7px; font-size: 15px; line-height: 25px; border-top-left-radius: 6px; border-top-right-radius: 6px; border-bottom-right-radius: 6px; border-bottom-left-radius: 6px; background-color: #ecf0f1; clear: both; /* float: left; */ position: relative; word-wrap: break-word; word-break: break-all; } .odd:after { content: ' '; top: auto; bottom: auto; border: 12px solid; border-color: transparent transparent #ecf0f1 transparent; margin: 0 0 0 -23px; float: left; position: absolute; left: 10px; bottom: 6px; } .chat_box .even { display: block; padding: 10px; margin-bottom:7px; font-size: 15px; line-height: 25px; border-top-left-radius: 6px; border-top-right-radius: 6px; border-bottom-right-radius: 6px; border-bottom-left-radius: 6px; background-color: #C1E4EC; /* float: left; */ position: relative; word-wrap: break-word; word-break: break-all; } .even:after { content: ' '; top:auto; bottom: auto; right:28px; border: 12px solid; border-color: transparent transparent #C1E4EC transparent; margin: 0 -40px 0 0; position: absolute; bottom: 6px; } .chat_box li .time { font-size:10px; width:55px; text-align:center; } .mspop { position:fixed; width:100%; padding:15px 0 15px 0; z-index:100; background-color:#a18752; bottom:0; } .mspop .input_ms { float:left; width:70%; height:19px; padding:5px; border-radius:8px; margin-left:2%; } .mspop .enter_btn { position:absolute; background-color :#ffffff; border-radius:12px; text-align:center; padding:7px; right:4%; } .mythumb3 { margin-right:10px; width: 50px; height: 50px; top:20px; overflow: hidden; border-radius: 50px; clear:both; } .mythumb3 img { width: 50px; height: 50px; } </style> <div class="chat_box"> <div class="addMs">△ MORE MESSEGE</div> <ul class="heightchk"> <?php foreach($friendIds as $friendId){ ?> <?php $date_temp=date_create($friendId->전송일시); $date_time = date_format($date_temp,"h:i"); $date_ampm = date_format($date_temp,"A"); $date_ampm =$date_ampm =="AM"?"오전":"오후"; ?> <?php if($friendId->전송_id==$user_id) { ?> <li class="group_box" msid="<?=$friendId->쪽지_id ?>"> <div style="position:relative;margin-right:10px"> <table style="max-width:80%;table-layout:fixed;" align="right"> <tr> <td> <div class="time" style="margin-left:5px;" > <?=$date_ampm?> <?=$date_time?> </div> </td> <td style="max-width:60%"> <div class="even"> <?=$friendId-> 내용?> </div> </td> </tr> </table> </div> </li> <?php }else{ ?> <li msid="<?=$friendId->쪽지_id ?>"> <div style="position:relative;"> <table style="max-width:90%;table-layout:fixed;"> <tr> <td><div class="mythumb3"><img src="<?=경로_사용자?><?=$friendId->사진?>" alt=""></div></td> <td style="max-width:70%"> <div><?=$friendId->전송_id?></div> <div class="odd"> <?=$friendId->내용?> </div> </td> <td> <div class="time" style="margin-left:5px;" > <?=$date_ampm?> <?=$date_time?> </div> </td> </tr> </table> </div> </li> <?php } ?> <?php } ?> </ul> </div> <div class="mspop"> <div class="enter_text"> <input class="input_ms" type="text" placeholder="Please enter your messege." name="contents"/> <div id="enter_btn" class="enter_btn">ENTER</div> </div> </div> <script> var groupId = "<?=$groupIds?>"; var msCnt = "<?=$msCnt?>"; <?php //전체 쪽지의 개수 ?> var upperMsId = "<?=$upperMsId?>"; <?php //초기값 설정 ?> var totalminMs = "<?=$totalminMs?>"; function getMaxId(){ if($(".chat_box ul li").last().attr("msid")==null){ return 0; }else{ return $(".chat_box ul li").last().attr("msid"); <?php //가장 마지막 메세지의 쪽지_id를 받아옴 ?> } } function msAjax(url,data,isMove){ <?php //공통된 ajax문 함수 ?> $.ajax({ type:"POST", url: url, dataType:"text", data:data, success: function(result){ $(".heightchk").append(result.trim()); <?php //li태그의 상위 태그에 붙임 ?> if(result.trim()!="") bottomMove(); },error: function(result){ alert("오류가 발생했습니다."); } }); } function getNewMs(){ <?php //상대방의 메세지 받아오기 ?> msAjax("/friends/refreshMs",{"groupId" : groupId,"msId" : getMaxId() },false); } $(document).ready(function() { if(msCnt<=10){ addMsHidden(); } $("#enter_btn").click(function(){ <?php //메세지 입력 이벤트 ?> contents = $(".input_ms").val(); if(contents==null || contents==""){ <?php //내용을 입력하지 않았을 시에 alert ?> alert("값을 입력하세요"); return; } input_Reset(); msAjax("/friends/insertContents",{"groupId" : groupId, "contents" : contents,"msId" : getMaxId()},true); }); $(".addMs").click(function(){ <?php //메세지 더보기 버튼 클릭시 발생 이벤트 ?> $.ajax({ type:"POST", url: "/friends/addMs", dataType:"text", data:{ "groupId" : groupId, "upperMsId": upperMsId }, success: function(result){ topMove(); $(".chat_box .heightchk").prepend(result.trim()); upperMsId = $(".chat_box .heightchk:eq(0) li:eq(0)").attr("msid"); if(upperMsId==totalminMs){ addMsHidden(); <?php //더보기 할 필요가 없으니 버튼 숨김 ?> } },error: function(result){ alert("오류가 발생했습니다."); } }); }); resetUI(); bottomMove(); setInterval(getNewMs, 5000); <?php //5초마다 한번씩 getNewMs 함수 발동 ?> }); $(window).resize(function(){resetUI();}); function resetUI(){ $(".chat_box").width($(window).width()); $(".chat_box").height($(window).height()-60); } function bottomMove(){ <?php //스크롤 아래 고정 함수 ?> var docHeight = $(".heightchk").height(); $('.chat_box').scrollTop(docHeight); } function topMove(){ <?php //스크롤 위 고정 함수 ?> $('.chat_box').scrollTop("0"); } function input_Reset(){ <?php //메세지 입력란 입력 후 공백처리 ?> $(".input_ms").val(''); } function addMsHidden(){ $(".addMs").css("display","none"); } </script><file_sep> <style> div.selected_walk_event .clicked_event_list { position: static; font-size: 14px; } div.selected_walk_event #content_company { text-align: center; font-size: 14px; } div.selected_walk_event #content_title { text-align: center; font-size: 30px; } div.selected_walk_event #cotent_image { max-height: 200px; max-width: 300px; position: relative; display: block; margin-left: auto; margin-right: auto; border: 2px; } div.selected_walk_event #content_summary_info { position: relative; margin-left: auto; margin-right: auto; font-size: 12px; display: table; background-color: papayawhip; border-style: groove; border-radius: 10px; font-weight: 600; } div.selected_walk_event .event_summary { cursor: pointer; background: silver; margin: 5px; border-radius: 6px; } div.selected_walk_event #event_summary_detail { display: none; } div.selected_walk_event #event_course_detail { display: none; } div.selected_walk_event #event_prize_detail { display: none; } div.selected_walk_event #event_promotion_detail { display: none; } div.selected_walk_event #event_caution_detail { display: none; } div.selected_walk_event .event_course_info { cursor: pointer; background: silver; margin: 5px; border-radius: 6px; } div.selected_walk_event .event_prize_info { cursor: pointer; background: silver; margin: 5px; border-radius: 6px; } div.selected_walk_event .event_promotion_info { cursor: pointer; background: silver; margin: 5px; border-radius: 6px; } div.selected_walk_event .event_caution_info { cursor: pointer; background: silver; margin: 5px; border-radius: 6px; } div.selected_walk_event div.event_apply_button { cursor: pointer; margin-right: auto; margin-left: auto; text-align: -webkit-center; border: groove; height: 20px; background: steelblue; margin: 20px; border-radius: 6px; } </style> <div class=selected_walk_event> <div class="clicked_event_list"> <!--전체 리스트--> <div class="event_first_info"> <!-- 첫번째 대회 정보 --> <div id="content_company"><?=$alldata[0]->머릿말 ?></div> <!--주최측--> <div id="content_title"> <b> <?=$alldata[0]->제목?></b> </div> <!-- 제목 --> <img id="cotent_image" src="<?=경로_걷기대회.$alldata[0]->대회포스터 ?>"></img> <!-- 사진 --> <div id="content_summary_info"> <!-- 신청기간 --> <p>신청기간 : <?= $alldata[0]->참여기간 ?> </p> <p>완보걸음 : <?=$alldata[0]->완보걸음?> </p> <p>경품 : <?= $alldata[0]->경품?> </p> <p>기념품 : <?= $alldata[0]->기념품?> </p> </div> </div> <div class="clicked_content_info"> <div class="event_summary"> <!-- 대회 개요 --> <b>대회개요 </b> <div id="event_summary_detail"> <!-- 대회 개요 하위메뉴 --> <ul class="event_summary_top_detail"> <li class="event_title_summary_detail"> <span style="color:#3459e2;">대회명 :</span> <span><?=$selectEvent[0]->제목 ?></span> </li> <li class="event_title_summary_detail"> <span style="color:#3459e2;">목표완보걸음 :</span> <span><?=$selectEvent[0]->목표걸음수?></span> </li> <li class="event_title_summary_detail"> <span style="color:#3459e2;">진행일시 : </span> <span><?= $alldata[0]->참여기간 ?></span> <p style="margin-top:0px; margin-bottom:0px"><?= substr($selectEvent[0]->시작일시,10,20)?> 부터 접수</p> </li> <li class="event_title_summary_detail"> <span style="color:#3459e2">경품/기념품 추첨일 : </span> <span> <?=$alldata[0]->추첨일?> </span> </li> <li class="event_title_summary_detail"> <span style="color:#3459e2">주최 : </span> <span> <?=$alldata[0]->주최?> </span> </li> <li class="event_title_summary_detail"> <span style="color:#3459e2">협찬 : </span> <span> <?=$alldata[0]->협찬?> </span> </li> </ul> </div> </div> <div class="event_course_info"> <!-- 코스안내 --> <b>코스안내</b> <div id="event_course_detail"> <!-- 코스안내 하위메뉴 --> <p>- 본 대회는 4개의 위시와 4개의 미션으로 나뉘어 있습니다.</p> <p>- 위시는 약 2만보 달성 시 마다 확인할 수 있습니다.</p> <p>- 미션은 대회 중 무작위로 생성되며, 생성즉시 확인하실 수 있습니다.</p> </div> </div> <div class="event_prize_info"> <!-- 경품 & 기념품 안내 --> <b>경품 &기념품안내</b> <div id="event_prize_detail"> <!-- 경품 & 기념품 안내 하위메뉴 --> <ul class="event_prize_top_detail"> <!--<li id="event_ranprize_summary_detail"> <p style="color:#3459e2;">경품수 :</p> <p>총 <?=$selectEvent[0]->경품수 ?> 개<p> <li id="event_prize_summary_detail"> <p style="color:#3459e2;">기념품수 : </p> <p>총 <?=$selectEvent[0]->기념품수 ?> 개</p> </li>--> <li id="event_ranprize_contents_detail"> <p style="color:#3459e2;"> 경품 : </p> <p> <?= $alldata[0]->경품 ?></p> </li> <li id="event_prize_contents_detail"> <p style="color:#3459e2;"> 기념품 : </p> <p> <?= $alldata[0]->기념품 ?></p> </li> </ul> </div> </div> <div class="event_promotion_info"> <!-- 체크인 프로모션 안내 --> <b>핫스팟안내</b> <div id="event_promotion_detail"> <!-- 체크인 프로모션 안내 하위메뉴 --> <p>· 위치안내</p> <p>서울 삼성동 캐논 본사, 북촌 한옥마을, 선유도 공원 </p> <p>· 보상안내</p> <p>핫스팟 체크인 완료 시 경품추첨권 각 1장</p> </div> </div> <div class="event_caution_info"> <!-- 유의사항 안내 --> <b>유의사항 안내</b> <div id="event_caution_detail"> <!-- 유의사항 안내 하위메뉴 --> <p>-보행 중 충돌로 인한 신체부상 및 물품 훼손의 경우 본 대회와는 책임이 없으니 유의하시기 바랍니다.</p> <p>-대회 종료 전까지 완보하신 참가자 중 위시 및 미션을 해결하셔야 경품 및 기념품 추첨 대상에 포함됩니다.</p> <p>-부정한 방법으로 대회에 참여한 참가자는 별도 제재를 받을 수 있습니다.</p> </div> </div> </div> <div class="event_apply_button" value="<?=$selectEvent[0]->걷기대회_id?>">대회신청하기</div> </div> </div> <script> var cur_open = ""; //현재 열려있는 토글 function toggleclose(submenu_class){ $('#'+cur_open).animate({ opacity : "show", //투명도 height : "toggle", queue : true }) cur_open=""; } function toggle_animate(move_menu){ if(cur_open!="" && cur_open!=move_menu){ //열려있는 토글이 현재 토글이 아니면, toggleclose(cur_open); //열려있는 토글닫고, $('#'+move_menu).animate({ //다시 토글 opacity : "show", //투명도 height : "toggle", }); cur_open = move_menu; } else if(cur_open==""){ //열려있는 토글이 없다면, $('#'+move_menu).animate({ //다시 토글 opacity : "show", //투명도 height : "toggle", }); cur_open = move_menu; }else if(cur_open == move_menu){ //현재 열려있는 토글이 지금 토글이면, toggleclose(cur_open); //열려있는 토글 닫기 } } $(document).ready(function() { $('.clicked_content_info div').click(function() { var submenu_check = $(this).attr('class'); //클래스 확인을 위함 if(submenu_check == "event_summary"){ var move_menu = "event_summary_detail"; //움직일 토글 toggle_animate(move_menu); } else if (submenu_check == "event_course_info") { var move_menu = "event_course_detail"; //움직일 토글 toggle_animate(move_menu); } else if (submenu_check == "event_prize_info") { var move_menu = "event_prize_detail"; //움직일 토글 toggle_animate(move_menu); } else if (submenu_check == "event_promotion_info") { var move_menu = "event_promotion_detail"; //움직일 토글 toggle_animate(move_menu); } else if (submenu_check == "event_caution_info") { var move_menu = "event_caution_detail"; //움직일 토글 toggle_animate(move_menu); } }); }); $(".event_apply_button").on("click",function(){ location.href = "/walk/applyWalkEvent/"+$(this).attr("value"); //해당 url로 이동 -> user_id도 함께 넘겨야함. }); </script> </html> <?php ?> <file_sep><style media="screen"> .HotspotView{ border-radius : 5px; width: 100%; } .HotspotView ul { padding-left: 0; align-items: left; list-style-type: none; } .HotspotView a{ text-decoration:none !important; } .container hr{ border-width: 1px; border-style: solid; } .HotspotView .header{ font-size: 16px; background-color: rgba(201, 201, 201, 0.8); padding : 3%; position: relative; margin-bottom: 1.5%; } .HotspotView .getTicket{ text-align: center; } .HotspotView .title{ position: relative; text-align: center; } .HotspotView .imformation{ text-align: center; } .HotspotView .imformation p{ margin: 0; } .HotspotView .link{ display: inline-block; width: 94%; color: white; background-color: skyblue; padding: 6px; padding-left: 3%; padding-right: 3%; } .HotspotView .article{ padding : 1%; text-align: justify; font-size: 12px; } .HotspotView .article p{ margin: 0px; } .HotspotView #banner{ position: relative; width: 100% } .HotspotView #title{ padding: 5px; color: white; background-color: rgba(50,92,135,0.7); position: absolute; transform: translateY(-107%); padding : 2%; width: 96%; } .HotspotView #left{ font-size: 18px; float: left; margin-right: auto; } .HotspotView #right{ padding : 5px; float: right; margin-left: auto; } .HotspotView #thumb{ display: block; margin-top: 5%; margin-left: auto; margin-right: auto; height: auto; width: 80%; } .HotspotView .goToMain{ background: gray; text-align: center; padding : 1.5%; } .HotspotView .goToMain p{ margin : 0; } </style> <div class="HotspotView"> <div class="container"> <div class="header"> <div id="back">◀ 명소 실제방문</div> </div> <div class="getTicket"> <p>축하합니다. 체크인을 완료하였습니다.</p> <p>경품추첨권 <?=$hotspot->추첨권수?>장을 획득하셨습니다.</p> </div> <div class="title"> <img id="banner"src="<?=경로_핫스팟.$hotspot->banner?>" alt=""> <div id="title"> <div id="left"><?=$hotspot->제목?></div> <div id="right">[<?=$hotspot->주최?>]</div> </div> </div> <div class="imformation"> <p class="link" value="<?=$hotspot->핫스팟_id?>">체크인하기</p> </div> <?php if ($more != TRUE): ?> <script type="text/javascript"> $(document).ready(function() { $(".imformation").hide(); }); </script> <?php elseif ($hotspot->분류 !=NULL): ?> <script type="text/javascript"> $(document).ready(function() { $(".imformation").hide(); }); </script> <?php endif; ?> <hr> <div class="article"></div> <div class="goToMain"> <p>처음으로</p> </div> </div> </div> <script type="text/javascript"> function hotspotAjax(url, data, page_id){ $.ajax({ type:"POST", url: url, dataType:"text", data:data, success: function(result){ $(".imformation").hide(); alert("체크인했습니다."); },error: function(result){ } }); } var rad = function(x) { return x * Math.PI / 180; }; function getDistance(p1, p2) { //마커 사아의 거리를 구하는 함수 var R = 6378137; // Earth’s mean radius in meter var dLat = rad(p2.lat() - p1.lat()); var dLong = rad(p2.lng() - p1.lng()); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong / 2) * Math.sin(dLong / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; $(document).ready(function() { $("#back").on("click", function(){ window.location.assign("<?=WEB_ROOT?>hotspot/hotspotListWithGoogleMap"); }); $(".link").on("click", function(){ hotspot_id = $(this).attr("value"); hotspotAjax( "/hotspot/insertCheckIn",{ "hotspot_id" : hotspot_id},hotspot_id ); }); $(".goToMain").on("click", function(){ window.location.assign("/activity/MainActivity_2/"); }); $.ajax({ type:"GET", url: "<?=WEB_ROOT.$article?>", dataType:"text", success: function(result){ $(".article").html(result); }, error: function(result){ } }); }); </script> <file_sep><style media="screen"> ul { margin: 0; padding-left: 0; list-style-type: none; } a{ text-decoration:none !important; } .header{ position: relative; background-color: gray; width: auto; margin-bottom: 2.5%; } .header p{ padding: 10px; margin: 0; } .list{ position: relative; height: auto; margin-bottom: 2.5%; width: 100%; } .title{ padding: 7px 5px; width: auto; color: white; background-color: rgba(0,172,238,0.5); margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .article { position: relative; height: auto; margin-top: 2.5%; } .banner { width: 100%; margin-bottom: -4px; height: auto; } </style> <div class="magazineList"> <div class="container" > <div class="header"> <p>매거진</p> </div> <div class="article"> <ul> <?php foreach ($magazines as $magazine){ ?> <li class='list' value="<?=$magazine->매거진_id?>"> <p class="title"><?= $magazine->제목 ?></p> <img class="banner" src="<?=경로_매거진.$magazine->배너?>" alt=""> </li> <?php } ?> </ul> </div> </div> </div> <script type="text/javascript"> $(document).ready(function(){ $(".list").on("click",function(){ window.location.assign("<?=WEB_ROOT?>magazine/magazineView/"+$(this).attr("value")); })} ); </script> <file_sep><style media="screen"> .drawTab .tab ul { padding: 0; list-style-type: none; text-align: center; } .drawTab .tab li{ padding-left: 5px; padding-right: 5px; font-size: 1em; margin: 0 0; width: 25%; display: inline; } .drawTab .tab li:first-child{ border-left:none; } .drawTab .container{ height: auto; } .drawTab .header{ position: relative; background-color: gray; margin-bottom: 2.5%; width: auto; } .drawTab .header p{ padding : 2.5%; margin: 0; color: white; } .drawTab .tab{ margin-bottom: 2.5%; font-size: 10pt; } .drawTab .tab ul{ background-color : orange; margin: 0; padding : 2.5%; } .drawTab .list{ border: 1px solid black; margin: 5px; cursor: pointer; } .drawTab #banner{ width: 100%; } .drawTab .bold{ font-weight:bold !important; } .drawTab .off{ display: none; } .drawTab .draw ul { border: 1px solid black; position: relative; padding: 0; text-align: center; } .draw{ position: relative; width: 100%; } .draw .img{ width: 100%; } .draw .select{ position: absolute; width: inherit; opacity: 0.5; } .gift_draw{ text-align: center; } .gift_list{ margin: 4%; width: 40%; display: inline-block; font-size: 12px; } .gift_list p{ font-size: 11px; margin-top: 1%; margin-bottom: 0; } </style> <div class="drawTab"> <div class="container"> <div class="header"> <p>경품추천</p> </div> <div class="tab"> <ul> <li class="bold" id="prize">경품추첨</li> <li class="" id="gift">기념품추천</li> </ul> </div> <div class="article"> <div id="view"></div> </div> </div> </div> <script type="text/javascript"> $(function() { loadList("prize"); $("#prize").click(function(){ $("#prize").addClass("bold"); $("#gift").removeClass("bold"); loadList("prize"); }); $("#gift").click(function(){ $("#prize").removeClass("bold"); $("#gift").addClass("bold"); loadList("gift"); }); }); function loadList(type){ $("#view").load("drawView/"+type); } $(document).on("click", ".gift_list", function(){ if( $(this).attr("id") == 1 || $(this).attr("id") == 3){ $(this).children(".img").attr("src","<?=WEB_ROOT.경로_공통이미지?>get_prize.jpg"); } else{ $(this).children(".img").attr("src","<?=WEB_ROOT.경로_공통이미지?>fail_prize.jpg"); } }); </script> <file_sep><style> .popup_page{ position: absolute; margin: 12%; background-color: white; width: 70%; height: 80%; border: 3px solid black; border-radius: 10px; } .popup_page .top_info{ position: relative; width: 100%; height: 15%; background-color: white; border-bottom: 3px solid black; text-align: center; top: 2%; } .popup_page .middle_info{ position: relative; width: 100%; height: 37%; background-color: white; border-bottom: 3px solid black; text-align: -webkit-auto; } .popup_page .bottom_info{ position: relative; width: 100%; height: 36%; background-color: white; border-bottom: 3px solid black; text-align: -webkit-auto; } .popup_page .ok_button{ position: absolute; width: 100%; height: 8%; background-color: #f3f35d; border-bottom: 3px solid black; text-align: center; font-size: 14px; font-weight: 800; border-radius: 10px; cursor: pointer; } .popup_page .target_walking_num{ width: 30%; background-color: #ffc107; height: 52%; border: 3px solid; text-align: center; position: absolute; } .popup_page .day_per_aver_walking{ width: 30%; background-color: #ffc107; height: 52%; position: absolute; margin-left: 34%; border: 3px solid; text-align: center; } .popup_page .complete_walking{ width: 30%; background-color: #ffc107; height: 52%; position: absolute; margin-left: 68%; border: 3px solid; text-align: center; } .popup_page .rank_of_people{ position: relative; height: 20%; top: 60%; font-size: 10px; font-weight: bold; width: 70%; } .popup_page .show_complete_viwer{ position: relative; height: 15%; top: 40%; font-size: 12px; font-weight: bold; width: 35%; left: 66%; cursor: pointer; text-align: -webkit-center; } .popup_page .mission_num{ position: absolute; width: 70%; height: 12%; background-color: antiquewhite; font-size: 14px; } .popup_page .numof_val{ position: absolute; left: 70%; width: 30%; height: 12%; font-size: 14px; background: bisque; } .popup_page .checkin_success{ position: absolute; width: 70%; height: 12%; background-color: antiquewhite; font-size: 14px; margin-top: 10%; } .popup_page .chechin_val{ position: absolute; left: 70%; width: 30%; height: 12%; font-size: 14px; background: bisque; margin-top: 10%; } .popup_page .hotspot_success{ position: absolute; width: 70%; height: 12%; background-color: antiquewhite; font-size: 14px; margin-top: 21%; } .popup_page .numof_hotspot{ position: absolute; left: 70%; width: 30%; height: 12%; font-size: 14px; background: bisque; margin-top: 21%; } .popup_page .suc_mission_num{ position: absolute; width: 70%; height: 12%; background-color: antiquewhite; font-size: 14px; margin-top: 31%; } .popup_page .suc_mission_val{ position: absolute; left: 70%; width: 30%; height: 12%; font-size: 14px; background: bisque; margin-top: 31%; } .select_popup_page{ width: 85%; height: 120px; border: 3px solid; border-radius: 10px; font-weight: bold; position: relative; margin: 10px; margin-left: auto; margin-right: auto; } .select_popup_page .ment_post_btn{ cursor: pointer; border: 1px solid; position: absolute; background: gold; width: 49%; display: block; bottom: 0px; left: 0px; text-align: center; border-bottom-left-radius: 6px; } .select_popup_page .exit_event_btn{ cursor: pointer; border: 1px solid; position: absolute; background: gold; width: 50%; display: block; left: 49%; bottom: 0px; text-align: center; border-bottom-right-radius: 6px; } .select_popup_page .btns{ position: absolute; background: gold; bottom: 0px; width: 100%; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; border: 1px solid; } .user_preserve_popup{ position: absolute; margin-left: auto; margin-right: auto; top: 40%; width: 96%; height: 50%; background: darkgray; border: 3px solid; border-radius: 8px; display : none; } .user_preserve_popup .top_user_preserve_popup{ position: relative; width: 100%; height: 25%; background: bisque; border-top-left-radius: 8px; border-top-right-radius: 8px; border-bottom: 1px solid; text-align: -webkit-center; } .user_preserve_popup .middle_user_preserve_popup{ position: relative; width: 100%; height: 60%; background: bisque; border-top-left-radius: 8px; border-top-right-radius: 8px; border-bottom: 1px solid; text-align: -webkit-center; } .user_preserve_popup .bottom_user_preserve_popup{ position: relative; width: 100%; height: 14.5%; border-top-left-radius: 8px; border-top-right-radius: 8px; border-bottom: 1px solid; text-align: -webkit-center; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; background: gold; } .bottom_user_preserve_popup .left_bt{ width: 49%; position: absolute; left: 0; height: 100%; border-right: 1px solid; cursor: pointer; } .bottom_user_preserve_popup .right_bt{ width: 59%; position: absolute; height: 100%; left: 47%; cursor: pointer; } .event_poster{ height: 50px; max-width: 100px; width: 80px; max-height: 100%; } .event_name{ font-size: 14px; } .event_day{ font-size: 14px; } .event_st{ font-size:14px; } </style> <div class="popup_page"> <div class="top_info"> <span style="font-size: 20px"><b>축하합니다.<br></b></span> <span style="font-size: 13px">대회의 목표걸음을 완보하셨습니다.</span> </div> <div class="middle_info"> <p style="font-size: 10px; margin-left: 10%; "><b>나의 참여 기록 </b></p> <div class="target_walking_num"> <p style="font-size: 10px;"><?= $middle_view->목표걸음수 ?> 보</p> <p style="font-size: 10px;">대회 목표 걸음수</p> </div> <div class="day_per_aver_walking"> <p id ="day_of_aver_walking" style="font-size: 10px;"> <?= $middle_view->평균걸음수 ?> 보</p> <p style="font-size: 10px;">일일 평균 걸음수</p> </div> <div class="complete_walking"> <p style="font-size: 10px;"><?= $middle_view->소요일?> </p> <p style="font-size: 10px;">완보 소요일</p> </div> <div class="rank_of_people"> <?= $middle_view->완보랭킹 ?>번째 완보자 입니다. </div> <div class="show_complete_viwer"> 완료증 보기> </div> </div> <div class="bottom_info"> <p style="font-size: 10px; margin-left: 10%;"><b>미션 참여</b></p> <p> <span class="mission_num"> 성공 미션수</span> <span class="numof_val"> <?= $middle_view->미션수행 ?> 개</span> </p> <p> <span class="suc_mission_num"> 완료한 미션</span> <span class="suc_mission_val"> <?= $middle_view->미션수행 ?> (<?= $middle_view->미션완료율 ?>) </span> </p> <p> <span class="checkin_success"> Wish 스템프 성공여부</span> <span class="chechin_val"> <?= $middle_view->체크인성공여부 ?> </span> </p> <p> <span class="hotspot_success"> 완료한 Wish</span> <span class="numof_hotspot"> <?= $middle_view->Wish ?> (<?= $middle_view->Wish완료율 ?>) </span> </p> </div> <div class="ok_button" onclick="select_popup()"> 확인 </div> </div> <div class='select_popup_page' style="display:none"> <div class = 'message_comp'> <p style="text-align: center;">대회가 종료되었습니다.</p> <p style="text-align: center;">참가 후기를 남기시겠습니까 ? </p> <div class="btns"> <span class='ment_post_btn'>후기남기기</span> <span class='exit_event_btn' onclick='preserve_popup()'>대회종료하기</span> </div> </div> </div> <div class='user_preserve_popup' > <div class='top_user_preserve_popup'> <p style="margin:0px"> 현재 <?= $count ?> 개의 찜한 대회가 있습니다. </p> <p> 어떤 대회에 참가 하시겠습니까? </p> </div> <div class= 'middle_user_preserve_popup' > <div class='user_preserve_item'> <ul style="margin: 0px; padding:0px;"> <?php foreach ($preserveEvent as $row){?> <li style="list-style-type: none;"> <img class='event_poster' src= <?= 경로_걷기대회.$row->대회포스터 ?> ></img> <span class='event_name'> <?= $row->제목?> <br></span> <span class='event_day'> <?= $row->시작일시 ?>~<?=$row->종료일시?><br></span> <span class='event_st'> <?= $row->진행여부?> </span> </li> <?php } ?> </ul> </div> </div> <div class= 'bottom_user_preserve_popup'> <span class='left_bt'>참가 신청하기</span> <span class='right_bt'>바로 종료하기</span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> function select_popup(){ $('.popup_page').css('display','none'); $('.select_popup_page').css('display','block'); } function preserve_popup(){ $('.select_popup_page').css('display','none'); $('.user_preserve_popup').css('display','block'); } </script> <file_sep>function is_empty(ele) { if(ele == "" || ele == "undefined" || ele == null || typeof(ele) == "undefined" ){ return true; } else { return false; } }<file_sep><?php if(empty($alldata->로고)) $src = ""; else $src = 경로_걷기대회.$alldata->로고; ?> <style media="screen"> .background_image{ background-image: url("<?=$src?>"); background-repeat:no-repeat; background-position:center; background-origin:content-box; background-size: 90%; opacity: 0.7!important; filter:alpha(opacity=30); width: 94%; height: 100%; position: absolute; } .container{ height: 100%; width: 100%; margin: 0; } .header{ text-align: center; color: white; background-color: black; padding: 2%; } .header span{ width: 10%; float: left; } .header p{ margin: 0; } .article{ position: relative; margin: 2.5%; opacity: 1.0!important; } .subtitle{ position: relative; text-align: center; font-size: 12px; padding : 3%; } .condition{ text-align: center; } .condition p{ margin : 0; margin-bottom: 2%; } .condition .entry{ width: 25%; display: inline-block; margin-bottom: 2.5%; } .tab{ text-align: center; } .mytab{ padding: 2%; background-color: gray; width: 43%;; display: inline-block; } .info{ margin: 3%; } .info p{ margin: 1%; font-size: 12px; } #my_opp{ text-align: center; } .opp{ text-align: center; margin:auto; width: 40%; display: inline-block; } .check{ color: white; text-align: center; padding: 1.5%; margin: auto; width: 91%; background-color: red; cursor: pointer; } #bottom_box{ border: 1px solid blue; padding: 1.5%; } .highlight{ margin: auto; margin-top: 2%; color: white; text-align: center; padding: 1.5%; background-color: gray; } .check_list{ list-style-type : circle; padding-left: 6%; padding-bottom: 2%; position: relative; font-size: 12px; } .prize_button{ border: 1px solid black; } .off{ display: none; } .bold{ font-weight: bold; } img.logo{ position: relative; width: 20%; } </style> <div class="background"> <div class="background_image"> </div> <div class="container"> <div class="header"> <span></span> <p>대회현황</p> </div> <div class="article"> <div class="subtitle"> <img class="logo" src="<?=경로_걷기대회.$alldata->로고?>"> <p>캐논에서 대회현황을 알려드립니다.</p> </div> <hr> <div class="condition"> <p>전체 참가자 현황</p> <div class="entry"> <p>참가자수</p> <p><?=$alldata->참가자수 ?>명</p> </div> <div class="entry"> <p>완보자 수</p> <p><?=$alldata->완보자수?>명</p> </div> <div class="entry"> <p>완보율</p> <p><?=$alldata->완보율?></p> </div> </div> <div class="tab"> <div class="mytab" id="info"> 나의 참가현황 </div> <div class="mytab" id="opp"> 당첨확률 </div> </div> <div class="info" id="my_info"> <p>참가번호 : <?= $user_id?> (완보번호 : <?= $user_id?>)</p> <p>참가자명 : <?= $user_name?></p> <p>참가기간 : <?= $alldata->유저참가신청일시?> ~ <?php if($end_state==1){ echo $alldata->종료일시;}else{echo date("Y-m-d");}?>(<?=$user_prt_day?>일)</p> <p>누적걸음수 : <?= $alldata->누적걸음수?> (남은걸음수 : <?= $alldata->남은걸음수?>)</p> <p>진행률 : <?= $alldata->진행률?></p> <p>스템프 : <?= $alldata->유저위시개수?>/<?= $alldata->위시개수?></p> <p>경품추첨권 : 2</p> <p>핫스팟 : <?= $alldata->유저핫스팟개수?></p> </div> <div class="info off" id="my_opp"> <div class="opp"> <p style=" margin : 0">나의 기념품 당첨확률</p> <p style="margin-top : 1%; margin-bottom : 1%;">0%</p> <p style="margin : 0; margin-bottom : 5%;">평균 00%</p> <div class= "prize_button">기념품보기</div> </div> <div class="opp"> <p style=" margin : 0">나의 경품 당첨확률</p> <p style="margin-top : 1%; margin-bottom : 1%; ">10.6%</p> <p style="margin : 0; margin-bottom : 5%;">평균 00%</p> <div class= "prize_button">경품보기</div> </div> <div style="text-align : left; font-size : 12px;"> * 대회기간 내에 완보하지 못하면 추첨대상에서 제외됩니다. </div> </div> <div class="check"> 당첨자발표확인 </div> <div class="info"> <div class="info_walk" id="info_walk"> <div id="bottom_box"> <p>대회기간 : <?= $alldata->대회기간?> (<?= $date_diff_day ?>일)</p> <p>기념품/경품 추첨일 : <?= $alldata->추첨일?></p> <p>목표걸음수 : <?= $alldata->목표걸음수?></p> <p>위시스템프 : <?= $alldata->위시개수?></p> <p>핫스팟 : <?= $alldata->핫스팟개수?></p> <p>기념품 수량 : <?= $alldata->기념품수 ?></p> <p>경품수량 : <?= $alldata->경품수 ?></p> </div> <div class="highlight"> 대회개요 자세히보기-> </div> <ul class="check_list"> <li>대회기간 내에 목표걸음을 도달해야 완보로 처리됩니다.</li> <li>하루최대 2만보까지만 걸음수가 체크됩니다.</li> </ul> </div> <div class="info_prize off" id="info_prize"> <div class="highlight">기념품 추첨기준</div> <ul class="check_list"> <li>대회기간 내에 목표걸음을 완보한 참가자만 추첨기회가 주어집니다.</li> <li>위시스템프를 모두 휙득해야만 추첨기회가 주어집니다.</li> <li>준비한 기념품 수량보다 완보자가 많으면 랜덤으로 추첨합니다.</li> </ul> <div class="highlight">경품 추첨기준</div> <ul class="check_list"> <li>대회기간 내에 목표걸음을 완보한 참가자만 추첨기회가 주어집니다.</li> <li>위시스템프를 모두 휙득해야만 추첨기회가 주어집니다.</li> <li>준비한 경품 수량보다 완보자가 많으면 랜덤으로 추첨합니다.</li> </ul> </div> </div> </div> </div> </div> <script> $(document).ready(function() { $("#info").click(function(){ $("#my_info").removeClass("off"); $("#info_walk").removeClass("off"); $("#my_opp").addClass("off"); $("#info_prize").addClass("off"); }); $("#opp").click(function(){ $("#my_opp").removeClass("off"); $("#info_prize").removeClass("off"); $("#my_info").addClass("off"); $("#info_walk").addClass("off"); }); }); $("div.check").on("click",function(){ location.href = "/walk/prizeConfirm/" }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Question_model extends CI_Model{ function __construct(){ parent::__construct(); } function questionIndex_sub($index){ $this->db->select("*"); $this->db->from("게시판"); $this->db->where("게시판종류",$index); $this->db->order_by('게시판_id'); return $this->db->get()->result(); } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); require_once APPPATH.'controllers/activity/common/menu.php'; class MainActivity_2 extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('walk_model'); $this->load->model('statistics_model'); //사용자진행율 } /* * C : MainActivity_2 * 참가중인 대회 대쉬보드 * */ function index($contest_state = 3){ $data["event_info"] = $this->walk_model->getInfoEvent( $this->session_common->getSession("user")['contest_id'] ); if($contest_state==0){ $data["contest_state"] = 0; } else if($contest_state==1){ $data["contest_state"] = 1; } else{ $date_a = new DateTime(); $date_b = new DateTime($data["event_info"][0]->종료일시); if($date_b < $date_a) { $data["contest_state"] = 0; } //대회 종료 else { $data["contest_state"] = 1; } //대회 진행중 } $this->load->view ("activity/header"); $this->load->view ("activity/MainActivity_2/index",$data); $this->load->view ("activity/footer"); } /* * MainActivity_2 하위 컴포넌트 * 대회 트랙 컴포넌트 * */ function contest_comp(){ $this->load->model('prize_model'); // 사용자 스탭프/경품 $contest_state = $this->input->post("contest_state"); $data["event_info"] = $this->walk_model->getCereMony( $this->session_common->getSession("user")['user_id'] ); $data["contest_info"] = $this->walk_model->getInfoEvent( $this->session_common->getSession("user")['contest_id'] ); $data["user_info"] = $this->session_common->getSession("user"); /* 사용자 진행율 */ $user = $this->session_common->getSession("user")['user_id']; $name = $this->session_common->getSession("user")['name']; $contest_id = $this->session_common->getSession("user")['contest_id']; $result = $this->statistics_model->main_2_marquee($user, $contest_id); if(!$result){ $data["str"] = ""; } else{ $flag_step = $result["대회"] -> 목표걸음수; $date = $result["대회"] -> 종료일시; $contest = $result["통계"]; $date_a = new DateTime(); $date_b = new DateTime($date); $date_diff = date_diff($date_a, $date_b)->days; $total_step = 0; foreach ($contest as $val) { $total_step += $val->걸음수; } if(count($contest)==0) $rate = 0; else $rate = ($total_step/$flag_step) *100; //$rate = ( ($total_step/count($contest)) / (($flag_step - $total_step)/$date_diff) ) * 100; } /* 사용자 스탬프 */ $stamp = $this->prize_model->getStampRate($user,$contest_id); if($contest_state ==1){ $data["stamp_info"] = $this->prize_model->getTrackStamp($contest_id); $data["checked_info"] = $this->prize_model->getTrackCheckedStamp($user,$contest_id); // $data["stamp_info"] = array(); // foreach ($stamp_info as $val) { array_push($data["stamp_info"],(array)$val); } } /* 사용자 경품 */ $prize = $this->prize_model->getUserPrizeCount($user,$contest_id); $data["stat_info"] = array( "total_step"=> $total_step, "rate" => (int)$rate, "stamp" => $stamp[0]->얻은스탬프." / ".$stamp[0]->총스탬프, "prize" => $prize, ); if($contest_state==0) $this->load->view ("track/contest_end_comp",$data); if($contest_state==1) $this->load->view ("track/contest_ing_comp",$data); } } ?> <file_sep><style media="screen"> html{ } ul { padding-left: 0; list-style-type: none; } .hotspotList p{ margin: 0; } .hotspotList .header{ font-size: 16px; background-color: rgba(201, 201, 201, 0.8); padding : 3%; position: relative; margin-bottom: 1.5%; } .hotspotList .gps{ position: absolute; display: block; text-align: center; float : right; background-color: rgba(119, 242, 146,0.7); width: 35%; padding: 1px; z-index: 10; } .hotspotList .gps p{ padding : 5px; font-size: 12px; } .hotspotList .wellcome{ padding: 2.5%; background: pink; margin : 2.5% 0 ; text-align: center; } .hotspotList .myInfo{ font-size: 12px; margin-top: 4.5%; text-align: right; } .hotspotList .nearby{ text-align: center; padding: 2.5%; } .hotspotList .nearby ul{ margin : 0 !important; } .hotspotList .article ul{ margin: 0; width: 100%; } .hotspotList .list{ background-color: rgba(190,190,190,0.4); display: inline-table; width: 100%; } .hotspotList .list p{ position: relative; font-size: 12px; } .hotspotList .sub{ display: table-header-group; } .hotspotList .sub span{ padding: 5px; } .hotspotList .info{ margin-bottom: 0.5%; padding-left: 1%; font-size: 14px; text-align: left; vertical-align: middle; display: run-in; } .hotspotList .state{ font-size: 12px; padding : 5px; float: right; } .hotspotList .title{ font-size: 12px; float: left; text-align: left; } .hotspotList .banner{ margin-left: 1%; margin-bottom: 1%; display: table-cell; vertical-align: middle; float: left; width: 30%; } .hotspotList .map{ position: relative; width: 100%; height:300px; margin-bottom: 2.5%; z-index: 0; } .hotspotList #nearby{ font-size: 14px; } .hotspotList .checkIn{ margin: 1% 0; background: yellow; text-align: center; display: table-footer-group; } .hotspotList .checkIn p{ padding: 1.5%; } .hotspotList .hotspotInfo{ padding-top: 1%; padding-left: 1%; margin-bottom: 1%; display: inline-block; width: 67%; height: auto } .hotspotList .more{ padding: 2%; float: right; font-size: 12px; position: relative; } </style> <script type="text/javascript"> var id = new Array(); var myLatLng = new Array(new Array(),new Array()); var customInfo = new Array(); </script> <div class="hotspotList"> <div class="container"> <div class="header"> <div id="back">◀ 명소 실제방문</div> </div> <div class="article"> <div class="wellcome"> <p>핫스팟에 입장하신 것을 환영합니다.</p> <p>핫스팟에 방문해서 체크인하면<br>경품당첨 확률이 높아지는 추첨권을 드립니다.</p> <div class="myInfo"> <ul> <li>내 체크인 완료 개수 : <?=$state->checkIn?></li> <li>총 획득 경품추첨권 : <?=$state->prize?></li> </ul> </div> </div> <div class="nearby"> <p id="nearby">계산중 입니다.</p> </div> <div class="gps"> <p>GPS정보 수신 중</p> </div> <div class="map" id="map"></div> <ul> <?php foreach ($hotspots as $hotspot){ ?> <li class='list' id="<?=$hotspot->핫스팟_id?>"> <div class="sub"> <span class="title"><?=$hotspot->제목 ?></span> <div class="state"> <?php if(!($hotspot->분류 == NULL)) { ?> <span>참여완료</span> <?php } else if ($hotspot->종료시간 >= time()) { ?> <span> 참여가능 </span> <?php } else { ?> <span> 종료됨 </span> <?php }?> </div> </div> <script type="text/javascript"> id.push(<?=$hotspot->핫스팟_id?>); myLatLng[0].push(<?=$hotspot->위도?>); myLatLng[1].push(<?=$hotspot->경도?>); customInfo.push(<?=$hotspot->핫스팟_id?>); </script> <img class="banner" src="<?=경로_핫스팟.$hotspot->배너?>" alt=""> <div class="hotspotInfo"> <p class="info">체크인 가능시간 | <?= $hotspot->체크인_종료시간?></p> <p class="dist info"></p> <span class="info">아이콘 경품추첨권 <?=$hotspot->추첨권수?>장 </span> <span class="more" value="<?=$hotspot->핫스팟_id?>" >자세히보기</span> </div> <div class="checkIn" value="<?=$hotspot->핫스팟_id?>"> <p>체크인하기</p> </div> </li> <?php } ?> </ul> </div> </div> </div> <script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap" async defer></script> <script> function initMap() { //구글 맵 선언 var marker = new Array(); var temp; var index; var loc = {lat : 37.566567, lng : 126.992542}; //지도의 중심점 var shortDist // loc의 위치로 부터 가장 가까운 핫스팟을 거리를 저장 var center //loc위치의 마커 var select // 가장 가까운 핫스팟의 index 값 var dist; // 지도의 중심으로부터 각각의 핫스팟의 거리값을 저장 var map = new google.maps.Map(document.getElementById("map"), { // 지도 정보 선언 center: loc, // 지도의 중심 scrollwheel: false, zoom: 13, mapTypeControl : false, streetViewControl: false, fullscreenControl: false, }); center = new google.maps.Marker({ // 각각의 핫스팟과 지도의 중심점을 구하기 위해서 마커로 선언 position: loc, map: map, icon: { path:google.maps.SymbolPath.CIRCLE //fillOpacity:0.0, //strokeOpacity: 0.0 } }) for(var i = 0; i < id.length; i++){ temp = {lat : myLatLng[0][i] ,lng : myLatLng[1][i]} // 각각의 핫스팟의 위도, 경도값을 저장 marker[i] = new google.maps.Marker({ //각각의 마커는 배열로 선언되어 index로 접근 가능 position: temp, map: map, customInfo: customInfo[i] // 위에서 저장한 핫스팟_id를 가져옴 하단에 리스트를 표시하기 위하여 사용 }); setMarker(marker[i], center); // 마커를 설정 하단에 선언되어 있음 if(i == 0){ shortDist = getDistance(marker[i].position, center.position); select = 0; } // 첫번째 마커가 가장 짧으므로 저장 else if ( shortDist > ( tempDist = getDistance(marker[i].position, center.position) ) ){ shortDist = tempDist; select = i; }// 저장된 거리를 비교하여 짧으면 그 거리를 저장하고 인덱스 값도 저장 }; //for문 종료 marker[select].setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png'); //가장짧은 거리의 핫스팟의 마커 아이콘을 변경 $( ".list" ).hide(); $( ".dist" ).text( "아이콘 " + Math.round(shortDist) + "m"); $( '#' + marker[select].customInfo ).show(); $( "#nearby" ).text("현재 가장 가까운 핫스팟은 "+ Math.round(shortDist) +"m 이내에 있습니다!"); } function setMarker(marker, center) { marker.addListener('click', function(){ $( ".list" ).hide(); $( ".dist" ).text("아이콘 " + Math.round( getDistance(this.position, center.position) ) + "m"); $( '#'+this.customInfo ).show(); console.log(this.customInfo); }); } var rad = function(x) { return x * Math.PI / 180; }; function getDistance(p1, p2) { //마커 사아의 거리를 구하는 함수 var R = 6378137; // Earth’s mean radius in meter var dLat = rad(p2.lat() - p1.lat()); var dLong = rad(p2.lng() - p1.lng()); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong / 2) * Math.sin(dLong / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; }; function hotspotAjax(url, data, page_id){ $.ajax({ type:"POST", url: url, dataType:"text", data:data, success: function(result){ window.location.assign("<?=WEB_ROOT?>hotspot/hotspotView/"+page_id); },error: function(request,status,error){ alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error); } }); } $(document).ready(function(){ $(".checkIn").on("click",function(){ hotspot_id = $(this).attr("value"); hotspotAjax( "/hotspot/insertCheckIn",{ "hotspot_id" : hotspot_id},hotspot_id ); }); $("#back").on("click", function(){ history.back(); }); $(".more").on("click", function(){ window.location.assign("<?=WEB_ROOT?>hotspot/hotspotView/"+$(this).attr("value")+"/more"); }); }); </script> <file_sep> <div class="toolbar" style="background:#0d0d0d;"> <div class="toolbar-inner"> <div class="left" style="margin-left:15px;"><?=$contest[0]->제목?></div> <div class="right" style="margin-right:15px;"><a href="#" class="close-picker" style="color:white;">닫기</a></div> </div> </div> <div class="picker-modal-inner"> <?php if($state=="get"){ ?> <div class="content-block" style="text-align:center;line-height:2em;"> <h1>축하합니다!</h1> <div style="height:1px;width:100%;border-top:1px solid #ccc;margin:15px 0px;"></div> <h3>스탬프 1개를 획득하셨습니다</h3> <img src="<?=경로_경품?>stamp_yes.png" style="width:100px;"/> <p style="line-height:1.5em;">스탬프를 모두 획득한 참가자에게는<br>기념품 추첨 자격이 주어집니다.</p> <a href="#" id="get_stamp" class="button button-raised button-fill color-pink" style="color:white;margin-top:15px;">나의 획득현황 상세 보기</a> </div> <?php }else{ ?> <div class="content-block" style="text-align:center;line-height:2em;"> <h1>위시에 도착하였습니다!</h1> <div style="height:1px;width:100%;border-top:1px solid #ccc;margin:15px 0px;"></div> <h3>스탬프를 획득하실 수 있습니다</h3> <p style="line-height:1.5em;margin-top:20px">위시에 도착해서 콘텐츠를 확인하면<br>기념품 추첨에 필요한 스탬프를 드립니다.</p> <p style="margin-top:20px;">예상 획득내용</p> <p style="color:yellow;">스탬프 1개</p> <a href="#" id="set_stamp" class="button button-raised button-fill color-pink" style="color:white;margin-top:15px;">위시 콘텐츠 보고 스탬프 받기</a> </div> <?php } ?> </div> <file_sep><style> body{margin:0px;} .top_content .background{ background-image: url("<?=경로_걷기대회?>prize_companies.png"); background-size: contain; opacity: 1.0!important; filter:alpha(opacity=30); width: 100%; height: 100%; position: absolute; } .top_content .content{ position: absolute; width: 100%; height: 100%; text-align: -webkit-center; background: #282525; opacity: 0.9!important; } .top_content .prize_image{ width: 100%; height: 40%; } .top_content .loading_gif{ width: 10%; height: 5%; } </style> <div class="top_content"> <div class= "background_img"> <div class = "background"></div> </div> <div class="content" style="opacity: 0!important"> <p><b style="color:white">광고 후 곧 발표됩니다!</b></p> <img class="prize_image" src="<?=경로_걷기대회?>prize_camera.jpg"></img> <p><b style="color:white">협찬사 광고시청 후 결과를 보실 수 있습니다.</b></p> <p id=ShowSeconds style="color:white"></p> <img class="loading_gif" src="<?=경로_걷기대회?>loading.gif"></img> <p><b style="color:white">조회중..</b></p> </div> </div> <script type="text/javascript"> $(document).ready(function(){ window_onload(); }); function window_onload(){ setTimeout('show_content()',2000) // 2초후 show_content() 함수를 호출한다. } function show_content(){ $('.background_img').animate({ opacity: 0.5 },1000); $('.content').animate({ opacity: 1 },function(){ setShowTime(); setInterval('setShowTime()',1000); }); } var second=10; function setShowTime(){ $("#ShowSeconds").html(second+"초"); if(second !=0){ second--; } } </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | File and Directory Modes |-------------------------------------------------------------------------- | | These prefs are used when checking and setting modes when working | with the file system. The defaults are fine on servers with proper | security, but you may wish (or even need) to change the values in | certain environments (Apache running a separate process for each | user, PHP under CGI with Apache suEXEC, etc.). Octal values should | always be used to set the mode correctly. | */ define('FILE_READ_MODE', 0644); define('FILE_WRITE_MODE', 0666); define('DIR_READ_MODE', 0755); define('DIR_WRITE_MODE', 0777); /* |-------------------------------------------------------------------------- | File Stream Modes |-------------------------------------------------------------------------- | | These modes are used when working with fopen()/popen() | */ define('FOPEN_READ', 'rb'); define('FOPEN_READ_WRITE', 'r+b'); define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care define('FOPEN_WRITE_CREATE', 'ab'); define('FOPEN_READ_WRITE_CREATE', 'a+b'); define('FOPEN_WRITE_CREATE_STRICT', 'xb'); define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b'); /* End of file constants.php */ /* Location: ./application/config/constants.php */ if(ENVIRONMENT == "development"){ //개발 환경 설정 define('WEB_ROOT', 'http://localhost/'); define('FILE_ROOT', 'C:\\workspace\\WALK\\public_html\\'); }else if(ENVIRONMENT == "stage"){ //운영 환경 설정 define('WEB_ROOT', 'http://devwk.focus.kr/'); define('FILE_ROOT', '/FILE/SERVICE/public_html/walk/public_html/'); }else if(ENVIRONMENT == "production"){ define('WEB_ROOT', 'http://walk.focus.kr/'); define('FILE_ROOT', '/FILE/SERVICE/public_html/walk/public_html/'); }else if(ENVIRONMENT == "mig"){ define('WEB_ROOT', 'http://1.227.58.11:1990/'); define('FILE_ROOT', '/FILE/SERVICE/public_html/walk/public_html/'); } //공통 define('ACTIVITY_PATH', WEB_ROOT.'activity/'); //Migration Root 경로 define('IMG_PATH', WEB_ROOT.'mnt/walk/activity/'); //Migration IMG Root 경로 define('ADMIN_PATH', WEB_ROOT.'admst/'); //리소스 Roo 경로 define('경로_공통이미지', '/mnt/walk/images/'); define('경로_이벤트', '/mnt/walk/event/'); define('경로_매거진', '/mnt/walk/magazine/'); define('경로_핫스팟', '/mnt/walk/hotspot/'); define('경로_사용자', '/mnt/walk/user/'); define('경로_걷기대회', '/mnt/walk/master/'); define('경로_메시지', '/mnt/walk/message/'); define('경로_경품', '/mnt/walk/prize/'); define('경로_기념품', '/mnt/walk/gift/'); <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Statistics_model extends CI_Model{ function __construct(){ parent::__construct(); } //나의 대회 참여 통계 function getMyStepStatistics($사용자_id,$걷기대회_id){ $sql = " select 무형식원본날짜,원본날짜, 날짜, format(걸음수,0) 걸음수, format(누적걸음수,0) 누적걸음수, format(( 목표걸음수-누적걸음수),0) 남은걸음수 , (목표걸음수-누적걸음수) 원본남은걸음수, concat(round((누적걸음수 /목표걸음수)*100,1),'%') 진행률, round((누적걸음수 /목표걸음수)*100,1) 원본진행률, 증감 from ( SELECT 날짜 무형식원본날짜, DATE_FORMAT(날짜,'%Y.%m.%d') 원본날짜, DATE_FORMAT(날짜,'%m.%d') 날짜, 걸음수, (@runtot := a.걸음수 + @runtot) 누적걸음수, COALESCE(a.걸음수-@이전값,0) 증감, @이전값:=a.걸음수, (SELECT 목표걸음수 FROM focus_walk.걷기대회 a where a.걷기대회_id=".$걷기대회_id.") 목표걸음수 FROM focus_walk.사용자통계 a ,(SELECT @runtot:=0,@lastStep:=0,@이전값:=0) c where a.사용자_id='".$사용자_id."' and a.걷기대회_id =".$걷기대회_id." order by 사용자_id asc ) c "; $query = $this->db->query($sql); return $query->result(); } //대회 참가 현황 통계 function getMyTournamentInfo($걷기대회_id){ $this->db->from("걷기대회"); $this->db->where("걷기대회_id",$걷기대회_id); return $this->db->get()->result(); } //대회 참가신청일 function getMyTournamentStart($사용자_id,$걷기대회_id){ $sql = "SELECT DATE_FORMAT(참가신청일시, '%Y.%m.%d') 참가신청일시 FROM (걷기대회_참가자) WHERE 걷기대회_id = '$걷기대회_id' AND 사용자_id = '$사용자_id'"; $query = $this->db->query($sql); return $query->result(); } //획득 스탬프 function getMyStamp($사용자_id,$걷기대회_id){ $sql = " select * from ( select a.위시_id,a.위시제목,if(isnull(사용자_id),'실패','성공') 위시성공여부 FROM 위시 a left join 위시_스템프 b on a.위시_id = b.위시_id and b.사용자_id='$사용자_id' where 걷기대회_id =$걷기대회_id order by a.위시기준 ) aa "; $query = $this->db->query($sql); return $query->result(); } //획득 경품추천권 function getMyCard($사용자_id,$걷기대회_id){ $sql = " select * from ( select a.미션_id,a.미션명,if(isnull(사용자_id),'실패','성공') 미션성공여부 FROM 미션 a left join 미션_수행 b on a.미션_id = b.미션_id and b.사용자_id='$사용자_id' where 걷기대회_id =$걷기대회_id ) aa "; $query = $this->db->query($sql); return $query->result(); } /* * Main_1 상단 marquee 컴포넌트 모델 * 이종호 * 20170328 * 사용자 현재 참가중인 대회 이름, 기간 리턴 */ function main_1_marquee($contest) { $this->db->select("제목, 종료일시"); $this->db->from("걷기대회"); $this->db->where("걷기대회_id",$contest); return $this->db->get()->row(); } /* * Main_2 하단 marquee 컴포넌트 모델 * 이종호 * 20170328 * 사용자 평균걸음 및 추천걸음 리턴 */ function main_2_marquee($user,$contest) { $this->db->select("종료일시,목표걸음수"); $this->db->from("걷기대회"); $this->db->where("걷기대회_id",$contest); $a = $this->db->get()->row(); $this->db->select("*"); $this->db->from("사용자통계"); $this->db->where("사용자_id",$user); $this->db->where("걷기대회_id",$contest); $b = $this->db->get()->result(); return array("대회"=>$a,"통계"=>$b); } /* * Main_1 상단 걷기 통계 * 이종호 * 20170328 * 사용자 전체걸음수 리턴 */ function getAllStep($user) { $this->db->select("사용자_id, 날짜, 걸음수 "); $this->db->from("사용자통계"); $this->db->where("사용자_id",$user); $this->db->order_by('날짜',"desc"); return $this->db->get()->result(); } } ?> <file_sep><style media="screen"> .checkIn ul { margin-top: 10px; margin-bottom: 5px; padding: 0; list-style-type: none; text-align: center; } .checkIn .tab li{ border-left: 1px solid black; padding-left: 5px; padding-right: 5px; font-size: 1em; margin:0 0; width: 25%; display: inline; } .checkIn .tab li:first-child{ border-left:none; } .container{ height: auto; } .checkIn .header{ position: relative; background-color: gray; border: 1px solid gray; padding-left: 1%; width: auto; margin-bottom: 2.5%; } .checkIn .header p{ margin: 0; padding : 2.5%; color: white; } .checkIn .tab{ font-size: 10pt; } .checkIn .tab ul{ background-color : rgb(255, 213, 79); padding : 2.5%; margin: auto; } .checkIn .miniTitle{ font-size: 12px; text-align: center; color: rgb(71, 120, 244); } .checkIn .list{ background-color : rgba(190,190,190,0.4); cursor: pointer; margin-bottom : 2.5%; } .checkIn .title{ color : white; background-color: rgba(50,92,135,0.8); padding : 2%; margin : 0px; text-align: left; } .checkIn .banner{ width: 100%; margin-bottom: -5px; } .checkIn .bold{ font-weight:bold !important; } .checkIn .off{ display: none; } </style> <div class="checkIn"> <div class="container"> <div class="header"> <p>체크인 프로모션</p> </div> <div class="tab"> <ul> <li class="bold" id="open">진행중인 프로모션</li> <li class="" id="close">종료된 프로모션</li> </ul> </div> <div class="article"> <p class="miniTitle"> 체크인 프로모션에 오신걸 환영합니다.</p> <p class="miniTitle">해당 포인트 체크인하고 추짐한 경품을 받아가세요</p> <div id="view"></div> </div> </div> </div> <script type="text/javascript"> $(function() { loadList("open"); $("#open").click(function(){ $("#open").toggleClass("bold"); $("#close").toggleClass("bold"); loadList("open"); }); $("#close").click(function(){ $("#open").toggleClass("bold"); $("#close").toggleClass("bold"); loadList("close"); }); }); function loadList(type){ $("#view").load("promotionView/"+type); } $(document).on("click", ".list", function(){ window.location.assign("<?=WEB_ROOT?>hotspot/hotspotListProm/"+$(this).attr("value")); }); </script> <file_sep><div comp_prop='marquee_main_2_comp' style="<?php if($str=="") echo "display:none;"; ?> background-color:#333;line-height:30px;height:30px;line-height:30px;"> <marquee><?=$str?></marquee> </div> <file_sep><style> .eventthumb{ margin: 10px auto; width: 50px; height: 50px; overflow: hidden; display: block; border-radius: 50px; text-align: center; position:absolute; left:4%; top:20%; } .eventthumb img{ width: 50px;height: 50px; } </style> <div class="list_box"> <div> <div class="table_container"> <table class="table_layer"> <tr> <td style="text-align:left;width:130px;"><b>나를 초대한 친구</td> <td style="text-align:left;border-bottom:1px solid #555"></td> </tr> </table> </div> <ul><?php foreach($friendIds as $friendId ) { ?> <li> <div class="friend_box" name="<?=$friendId->초대_id?>"> <div class="eventthumb"><img src="<?=경로_사용자?><?=$friendId->사진?>" alt=""></div> <div class="userName" style="margin:15px 0px;margin-left:70px;"><?=$friendId->이름?></div> <div class="eventId" v_id="<?=$friendId->걷기대회_id?>" style="margin:15px 0px;margin-left:70px;"><?=$friendId->제목?></div> <div class="accept_bt">참여하기</div> <div class="reject_bt">거절</div> </div> </li> <?php } ?> </ul> </div> <div> <div class="table_container"> <table class="table_layer"> <tr> <td style="text-align:left;width:130px;"><b>내가 초대한 친구</td> <td style="text-align:left;border-bottom:1px solid #555"></td> </tr> </table> </div> <ul><?php foreach($userIds as $userId ) { ?> <li> <div class="friend_box" name="<?=$userId->초대_id?>"> <div class="eventthumb"><img src="<?=경로_사용자?><?=$userId->사진?>" alt=""></div> <div class="userName" style="margin:15px 0px;margin-left:70px;"><?=$userId->이름?></div> <div class="subeventId" v_name="<?=$userId->걷기대회_id?>" style="margin:15px 0px;margin-left:70px;"><?=$userId->제목?></div> <div class="invite_bt" style="background-color:#d1f9b6;color:#b2b2b2;" disabled>초대중</div> <div class="cancel_bt">취소</div> </div> </li> <?php } ?> </ul> </div> <div id="pop_delete" class="pop-layer"> <div class="pop-container"> <div class="pop-conts"> <p>초대 거절</p> <p class="ctxt mb20"></p> <div class="btn-r"> <div id="ok">확인</div> <div id="cancel">취소</div> </div> </div> </div> </div> <div id="pop_accept" class="pop-layer2"> <div class="pop-container"> <div class="pop-conts"> <p>초대 수락</p> <p class="ctxt mb20"></p> <div class="btn-r"> <div id="ok">확인</div> <div id="cancel">취소</div> </div> </div> </div> </div> <div id="pop_cancel" class="pop-layer4"> <div class="pop-container"> <div class="pop-conts"> <p>초대 취소</p> <p class="ctxt mb20"></p> <div class="btn-r"> <div id="ok">확인</div> <div id="cancel">취소</div> </div> </div> </div> </div> </div> <script> $(document).ready(function() { var name_id_tmp = ""; var name_name_tmp = ""; var event_id_tmp = ""; <?php //수락하기 버튼 클릭 시 작동 ?> $('.accept_bt').click(function(){ event_id_tmp = $('.eventId').attr("v_id"); name_name_tmp = $(this).parent().find(".userName").html(); $('#pop_accept').show(); $('.ctxt').text(name_name_tmp+"님이 초대한 대회에 참여하시겠습니까?"); }); $('.pop-layer2 #cancel').click(function() { $('#pop_accept').hide(); }); $('.pop-layer2 #ok').click(function() { $('#pop_accept').hide(); $.ajax({ type:"POST", url: "/friends/acceptEvents", dataType:"text", data:{ "event_id" : event_id_tmp }, success: function(result){ friendsReload2(2); },error: function(result){ alert("오류가 발생했습니다."); } }); }); <?php //거절 버튼 클릭 시 작동 ?> $('.reject_bt').click(function(){ event_id_tmp = $('.eventId').attr("v_id"); name_id_tmp = $(this).parent().attr("name"); name_name_tmp = $(this).parent().find(".userName").html(); $('#pop_delete').show(); $('.ctxt').text(name_name_tmp+"님의 대회참여 초대를 거절하시겠습니까?"); }); $('.pop-layer #cancel').click(function() { $('#pop_delete').hide(); }); $('.pop-layer #ok').click(function() { $('#pop_delete').hide(); $.ajax({ type:"POST", url: "/friends/rejectEvents", dataType:"text", data:{ "mode" : '1', "invite_id" : name_id_tmp, "event_id" : event_id_tmp }, success: function(result){ friendsReload2(2); },error: function(result){ alert("오류가 발생했습니다."); } }); }); <?php //취소 버튼 클릭 시 작동 ?> $('.cancel_bt').click(function(){ event_id_tmp = $('.subeventId').attr("v_name"); name_id_tmp = $(this).parent().attr("name"); name_name_tmp = $(this).parent().find(".userName").html(); $('#pop_cancel').show(); $('.ctxt').text(name_name_tmp+"님에게 대회참여 초대를 취소하시겠습니까?"); }); $('.pop-layer4 #cancel').click(function() { $('#pop_cancel').hide(); }); $('.pop-layer4 #ok').click(function() { $('#pop_cancel').hide(); $.ajax({ type:"POST", url: "/friends/rejectEvents", dataType:"text", data:{ "mode" : '2', "invite_id" : name_id_tmp, "event_id" : event_id_tmp }, success: function(result){ alert(result); friendsReload2(2); },error: function(result){ alert("오류가 발생했습니다."); } }); }); }); </script> <file_sep><?php if (! defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' ); class Walk_model extends CI_Model { function __construct() { parent::__construct(); } /* * getLiveEventtTitle * 정수영 * 20170314 * 사용자의 해당 대회 상태와 현재 진행중인 대회 객체 리턴 */ function getLiveEvent($user) { $sql = "SELECT A.걷기대회_id, A.제목, A.주최, DATE_FORMAT(A.시작일시,'%Y-%m-%d') 시작일시, DATE_FORMAT(A.종료일시,'%Y-%m-%d') 종료일시, A.대회포스터, A.참가자수, A.완보자수, A.경품수, A.기념품수, if(B.사용자_id is null, '참가신청',C.코드명 ) 버튼상태 FROM 걷기대회 A LEFT OUTER JOIN 걷기대회_참가자 B on A.걷기대회_id = B.걷기대회_id and B.사용자_id =". "'". $user. "'". " LEFT OUTER JOIN 공통코드 C on B.상태 = C.공통코드_id WHERE A.사용유무 = 'Y' and A.종료일시 >= now() and A.시작일시 <= now() ORDER BY A.걷기대회_id DESC"; return $this->db->query( $sql )->result(); } /* * getOutdateEventTitle * 정수영 * 20170322 * 사용자의 해당 대회 상태와 현재 진행중이 아닌 대회 객체 리턴 */ function getOutdateEvent($user) { $sql = "SELECT A.걷기대회_id, A.제목, A.주최, DATE_FORMAT(A.시작일시,'%Y-%m-%d') 시작일시, DATE_FORMAT(A.종료일시,'%Y-%m-%d') 종료일시, A.대회포스터, A.참가자수, A.완보자수, A.경품수, A.기념품수, if(B.사용자_id is null, '종료',C.코드명 ) 버튼상태 FROM 걷기대회 A LEFT OUTER JOIN 걷기대회_참가자 B on A.걷기대회_id = B.걷기대회_id and B.사용자_id =". "'". $user. "'". " LEFT OUTER JOIN 공통코드 C on B.상태 = C.공통코드_id WHERE A.사용유무 = 'Y' and A.종료일시 <now() and A.사용유무='Y' ORDER BY A.걷기대회_id DESC"; return $this->db->query( $sql )->result(); } /* * getPredateEventTitle * 정수영 * 20170322 * 사용자의 해당 대회 상태와 앞으로 진행할 대회 객체 리턴 */ function getPredateEvent($user) { $sql = "SELECT A.걷기대회_id, A.제목, A.주최, DATE_FORMAT(A.시작일시,'%Y-%m-%d') 시작일시, DATE_FORMAT(A.종료일시,'%Y-%m-%d') 종료일시, A.대회포스터, A.참가자수, A.완보자수, A.경품수, A.기념품수, if(B.사용자_id is null, '참가신청',C.코드명 ) 버튼상태 FROM 걷기대회 A LEFT OUTER JOIN 걷기대회_참가자 B on A.걷기대회_id = B.걷기대회_id and B.사용자_id = ". "'". $user. "'". " LEFT OUTER JOIN 공통코드 C on B.상태 = C.공통코드_id WHERE A.사용유무 = 'Y' and A.시작일시 >= now() and A.사용유무='Y' ORDER BY A.걷기대회_id DESC"; return $this->db->query( $sql )->result(); } /* * getSelectedPageInfo * 정수영 * 20170322 * 사용자가 선택한 페이지에 대한 사용자 정보와 대회정보 load * walk_view에서 사용. */ function getSelectedPageInfo($event_id){ $sql = "SELECT( SELECT concat(group_concat(A.경품명),(select case when count(*) > 3 then '...' else '' end from 경품 B where B.걷기대회_id = A.걷기대회_id)) from 경품 A where A.걷기대회_id = AA.걷기대회_id limit 3) 경품 ,( SELECT concat(group_concat(A.기념품명),(select case when count(*) > 3 then '...' else '' end from 기념품 B where B.걷기대회_id = A.걷기대회_id)) from 기념품 A where A.걷기대회_id = AA.걷기대회_id limit 3 ) 기념품 , concat(DATE_FORMAT(AA.시작일시,'%Y-%m-%d'),' ~ ',DATE_FORMAT(AA.종료일시,'%Y-%m-%d')) 참여기간 , concat(FORMAT(AA.목표걸음수,0),'보') 완보걸음 , AA.걷기대회_id , AA.머릿말 , AA.제목 , AA.대회포스터, DATE_FORMAT(AA.`기념품/경품_추첨일`,'%Y-%m-%d') 추첨일, AA.주최, AA.협찬 FROM 걷기대회 AA WHERE AA.걷기대회_id =" .$event_id; return $this->db->query( $sql )->result(); } /* * getInfoEvent * 정수영 * 20170315 * 대회의 경품정보, 기념품정보를 얻기위한 join table 객체 리턴 */ function getInfoEvent($event_id) { $this->db->select ( "*" ); $this->db->from ( "걷기대회" ); $this->db->where ( "걷기대회_id", $event_id ); return $this->db->get()->result(); } /* * getInfoEventRandomPresent * 정수영 * 20170317 * 대회의 경품수, 경품명을 얻기위한 객체 리턴 */ function getInfoEventRandomPresent($event_id) { $this->db->select ( "경품명", "경품수" ); $this->db->from ( "경품" ); $this->db->where ( "걷기대회_id", $event_id ); return $this->db->get()->result(); } /* * getUserInfo * 정수영 * 20170323 * 사용자의 상태를 리턴 */ function getUserInfo($user_id){ $this-> db-> select("사용자_id,이름,암호,e-mail as 이메일,성별,핸드폰,사진,참여중대회_id,인증번호,인증번호요청시간,주소,우편번호"); $this-> db-> from("사용자"); $this-> db-> where("사용자_id",$user_id); return $this->db->get()->row(); } /* * getInfoEventPresent * 정수영 * 20170317 * 대회의 기념품수, 기념품명을 얻기 위한 객체 리턴 */ function getInfoEventPresent($event_id) { $this->db->select ( "기념품명", "기념품수" ); $this->db->from ( "기념품" ); $this->db->where ( "걷기대회_id", $event_id ); return $this->db->get()->result(); } /* * 조진근 * 20170321 * 하나의 걷기대회 정보를 가져옴 */ function getWishEvent($id){ $this->db->select("걷기대회_id, 머릿말, 제목, 주최, 시작일시, 종료일시, 대회포스터, 목표걸음수 목표걸음"); $this->db->select("FORMAT(목표걸음수,0) 목표걸음수, FORMAT(참가자수,0) 최대참여인원 , 참가자수, FORMAT(완보자수,0) 최대완보인원, 완보자수, FORMAT(경품수,0) 경품수, FORMAT(기념품수,0) 기념품수",FALSE); $this->db->select('date_format(시작일시,"%Y년") AS s_year, date_format(시작일시,"%m월 %d일") AS s_md, date_format(종료일시,"%Y년") AS e_year, date_format(종료일시,"%m월 %d일") AS e_md, CAST(UNIX_TIMESTAMP(종료일시) AS SIGNED) AS dDay, CAST(UNIX_TIMESTAMP(시작일시) AS SIGNED) AS sDay',FALSE); $this->db->from('걷기대회` as A'); $this->db->where("A.걷기대회_id",$id); return $this->db->get()->row(); } /* * 정수영 * 20170330 * 하나의 걷기대회 정보를 가져옴 */ function getToggleInfo($event_id){ $sql = "select T.*, T.d_total-T.d_day d_time , T.s_total-T.s_day s_time from ( select 걷기대회_id, 머릿말, 제목, 주최, 시작일시, 종료일시, 대회포스터, 목표걸음수 목표걸음 ,FORMAT(목표걸음수,0) 목표걸음수, FORMAT(참가자수,0) 최대참여인원 , 참가자수, FORMAT(완보자수,0) 최대완보인원, 완보자수, FORMAT(경품수,0) 경품수, FORMAT(기념품수,0) 기념품수 ,date_format(시작일시,'%Y년') s_year, date_format(시작일시,'%m월 %d일') s_md, date_format(종료일시,'%Y년') e_year ,date_format(종료일시,'%m월 %d일') e_md ,CAST(UNIX_TIMESTAMP(종료일시) as SIGNED) d_total ,CAST(UNIX_TIMESTAMP(시작일시) as SIGNED) s_total ,CAST(UNIX_TIMESTAMP(date_format(종료일시,'%y-%m-%d')) as SIGNED) d_day ,CAST(UNIX_TIMESTAMP(date_format(시작일시,'%y-%m-%d')) as SIGNED) s_day from 걷기대회 where 걷기대회_id='".$event_id."' ) T"; return $this->db->query( $sql )->row(); } /* * 조진근 * 20170324 * 걷기대회 참여자수를 셈 */ function getWishEntry($id){ $this->db->select("(SELECT count(*) FROM 사용자 WHERE 탈퇴코드 IS null) AS 참가자수 ",FALSE); return $this->db->get()->row(); } /* * 조진근 * 20170321 * 입력받은 걷기대회_id에 해당되는 행을 기념품 테이블에서 가져옴 */ function getWishMemento($id){ $this->db->select('*',FALSE); $this->db->from('기념품` as A'); $this->db->where("A.걷기대회_id",$id); return $this->db->get()->result(); } /* * 조진근 * 20170321 * 입력받은 걷기대회_id에 해당되는 행을 경품 테이블에서 가져옴 */ function getWishGift($id){ $this->db->select('*',FALSE); $this->db->from('경품` as A'); $this->db->where("A.걷기대회_id",$id); return $this->db->get()->result(); } /* * 조진근 * 20170321 * 입력받은 사용자 ID에 맞는 사용자 이름을 사용자 테이블에서 가져옴 */ function getUserName($user){ $this->db->select('이름', FALSE); $this->db->from('사용자 AS A'); $this->db->where('사용자_id', $user); return $this->db->get()->row(); } /* * 정수영 * 20170324 * 입력받은 사용자 ID에 맞는 ceremony화면에 data를 loading * 완보소요일 , 걷기대회_id, 완보자 랭킹, 목표걸음수 */ function getCereMony($user_id){ $sql = "select AA.*, concat(round(미션수행*100/미션수,0),'%') 미션완료율, concat(round(Wish*100/Wish수,0),'%') Wish완료율 ,case when Wish=Wish수 then '성공' else '실패' end 체크인성공여부 from ( select if(isnull(A.목표걸음수),0,FORMAT(목표걸음수,0)) 목표걸음수 ,if(isnull(A.목표걸음수),0,A.목표걸음수) 목표걸음 ,(select if(isnull(FORMAT(round(avg(걸음수),0),0)),0,isnull(FORMAT(round(avg(걸음수),0),0))) from 사용자통계 C where C.사용자_id = B.사용자_id and C.걷기대회_id = A.걷기대회_id) 평균걸음수 ,(select if(isnull(DATEDIFF(max(날짜),min(날짜))+1),1,DATEDIFF(max(날짜),min(날짜))+1) from 사용자통계 C where C.사용자_id = B.사용자_id and C.걷기대회_id = A.걷기대회_id) 소요일 ,(select count(*) + 1 from 걷기대회_참가자 C where C.걷기대회_id = A.걷기대회_id and C.완보일 < now()) 완보랭킹 ,(select count(*) from 미션_수행_삭제 C ,미션 D where C.사용자_id = B.사용자_id and C.미션_id = D.미션_id and D.걷기대회_id = A.걷기대회_id) 미션수행 ,(select count(*) from 위시_스템프 C ,위시 D where C.사용자_id = B.사용자_id and C.위시_id = D.위시_id and D.걷기대회_id = A.걷기대회_id) Wish ,(select count(*) from 미션 D where D.걷기대회_id = A.걷기대회_id) 미션수 ,(select count(*) from 위시 D where D.걷기대회_id = A.걷기대회_id) Wish수 ,concat(concat(DATE_FORMAT(A.시작일시,'%Y-%m-%d'),'~'),DATE_FORMAT(A.종료일시,'%Y-%m-%d')) 참가기간 ,(DATE_FORMAT(A.시작일시,'%Y-%m-%d')) 시작일시 ,(DATE_FORMAT(A.종료일시,'%Y-%m-%d')) 종료일시 ,(select if(C.완보여부='Y','완보성공','완보실패') from 걷기대회_참가자 C where C.걷기대회_id = B.참여중대회_id and C.사용자_id = B.사용자_id) 완보여부 ,DATE_FORMAT(A.`기념품/경품_추첨일`,'%Y-%m-%d') 추첨일 ,(select if(isnull(sum(C.걸음수)), 0 , sum(C.걸음수)) from 사용자통계 C where C.사용자_id=B.사용자_id and C.걷기대회_id=A.걷기대회_id) 누적걸음수 ,(A.목표걸음수 - (select if(isnull(sum(C.걸음수)), 0 , sum(C.걸음수)) from 사용자통계 C where C.사용자_id=B.사용자_id and C.걷기대회_id=A.걷기대회_id)) 남은걸음수 from 걷기대회 A, 사용자 B where B.사용자_id = '".$user_id."' and B.참여중대회_id = A.걷기대회_id )AA"; return $this->db->query( $sql )->row(); } /* * getCompleteSpot * 정수영 * 20170324 * 입력받은 사용자 ID가 완료한 핫스팟과 갯수 리턴 */ function getCompleteSpot($user_id){ $this->db->select('count(*) as 핫스팟수행수 ',FALSE); $this->db->from('위시_수행'); $this->db->where("사용자_id", $user_id); return $this->db->get()->row(); } /* * getTotalSpot * 정수영 * 20170327 * 입력받은 대회_id의 총핫스팟 개수를 리턴 */ function getTotalSpot($event_id){ $this->db->select('distinct count(*) as 핫스팟개수', False); $this->db->from('위시'); $this->db->where('걷기대회_id', $event_id); return $this->db->get()->row(); } /* * getCheckInStatus * 정수영 * 20170324 * 입력받은 사용자 ID가 완료한 체크인 상황과 갯수 리턴 */ function getCheckInStatus($user_id){ $this->db->select('count(*) as 체크인수행여부 ',FALSE); $this->db->from('핫스팟_체크인_삭제'); $this->db->where("사용자_id", $user_id); $this->db->where("상태", 23); return $this->db->get()->row(); } /* * getPreserveEvent * 정수영 * 20170327 * 입력받은 사용자가 찜한 이벤트 목록을 리턴 */ function getPreserveEvent($user_id){ $this->db->select('date_format(시작일시,"%Y년%m월 %d일 ") AS 시작일시, date_format(종료일시,"%Y년%m월 %d일 ") AS 종료일시, 대회포스터, 제목, if(완보여부 = "N", "진행중", "완료" ) AS 진행여부 ',FALSE); $this->db->from('걷기대회_참가자'); $this->db->join('걷기대회','걷기대회_참가자.걷기대회_id = 걷기대회.걷기대회_id' ,'left outer',False); $this->db->where("사용자_id", $user_id); $this->db->where("상태", '17'); $this->db->where("완보여부", 'N'); return $this->db->get()->result(); } /* * getPreserveEvent * 정수영 * 20170327 * 입력받은 사용자가 찜한 이벤트 목록을 리턴 */ function getDdaySday($event_id){ $this->db->select('datediff(시작일시,now()) as 남은참가신청일 , datediff(종료일시,now()) as 남은종료일',False); $this->db->from('걷기대회'); $this->db->where('걷기대회_id' , $event_id); return $this->db->get()->row(); } /* * getMissionState * 정수영 * 20170327 * 해당 유저의가 실행한 distinct한 핫스팟개수를 리턴 */ function getUserHotspot($user_id){ $this->db->select('distinct count(*) as 유저핫스팟개수', False); $this->db->from('위시_스템프'); $this->db->where('사용자_id', $user_id); return $this->db->get()->row(); } /* * getEventHotSpot * 정수영 * 20170327 * 해당 event의 핫스팟개수를 리턴 */ function getEventHotSpot($event_id){ $this->db->select('distinct count(*)',False); $this->db->from('위시'); $this->db->where('걷기대회_id', $event_id); return $this->db->get()->row(); } /* * getEventHotSpot * 정수영 * 20170327 * 해당 유저가 해당이벤트의 경품대상인지 확인 */ function getMissionStatus($user_id, $event_id){ $sql = "select count(*) as 개수 from 미션_수행_삭제 AS A, 미션 AS B where A.사용자_id='" . $user_id . "' and A.미션_id = B.미션_id and B.걷기대회_id='" . $event_id ."'"; return $this->db->query( $sql )->row(); } /* * getWalkComplete * 정수영 * 20170327 * 해당 유저가 해당이벤트를 완료했는지 여부 */ function getWalkComplete($user_id, $event_id){ $this->db->select("*"); $this->db->from('걷기대회_참가자'); $this->db->where('걷기대회_id', $event_id); $this->db->where('사용자_id', $user_id); return $this->db->get()->row(); } /* * getWalkCondition * 정수영 * 20170329 * walk_condition에 해당하는 data load */ function getWalkCondition($user_id){ $sql ="select AA.*, concat(round(유저미션수행개수*100/미션개수,0),'%') 미션완료율 ,concat(round(유저위시개수*100/위시개수,0),'%') 위시완료율 ,concat(round(유저핫스팟개수*100/핫스팟개수,0),'%') 핫스팟완료율 ,case when 유저미션수행개수=위시개수 then '성공' else '실패' end 체크인성공여부 ,concat(round(누적걸음수*100/목표걸음,1),'%') 진행률 from ( select if(isnull(FORMAT(목표걸음수,0)),0,isnull(FORMAT(목표걸음수,0))) 목표걸음수 ,if(isnull(A.목표걸음수),0,A.목표걸음수) 목표걸음 ,(select DATE_FORMAT(C.참가신청일시,'%Y.%m.%d') from 걷기대회_참가자 C where C.걷기대회_id=A.걷기대회_id and C.사용자_id=B.사용자_id) 유저참가신청일시 ,(select count(*) + 1 from 걷기대회_참가자 C where C.걷기대회_id = A.걷기대회_id and C.완보일 < now()) 완보랭킹 ,(select count(*) from 미션_수행_삭제 C ,미션 D where C.사용자_id = B.사용자_id and C.미션_id = D.미션_id and D.걷기대회_id = A.걷기대회_id) 유저미션수행개수 ,(select count(*) from 위시_스템프 C ,위시 D where C.사용자_id = B.사용자_id and C.위시_id = D.위시_id and D.걷기대회_id = A.걷기대회_id) 유저위시개수 ,(select count(*) from 핫스팟_체크인_삭제 C where C.사용자_id = B.사용자_id and C.상태='23') 유저핫스팟개수 ,(select count(*) from 미션 D where D.걷기대회_id = A.걷기대회_id) 미션개수 ,(select count(*) from 위시 D where D.걷기대회_id = A.걷기대회_id) 위시개수 ,(select count(*) from 핫스팟 C where C.걷기대회_id = A.걷기대회_id) 핫스팟개수 ,concat(concat(DATE_FORMAT(A.시작일시,'%Y-%m-%d'),'~'),DATE_FORMAT(A.종료일시,'%Y-%m-%d')) 대회기간 ,(DATE_FORMAT(A.시작일시,'%Y.%m.%d')) 시작일시 ,(DATE_FORMAT(A.종료일시,'%Y.%m.%d')) 종료일시 ,(select if(C.완보여부='Y','완보성공','완보실패') from 걷기대회_참가자 C where C.걷기대회_id = B.참여중대회_id and C.사용자_id = B.사용자_id) 완보여부 ,DATE_FORMAT(A.`기념품/경품_추첨일`,'%Y.%m.%d') 추첨일 ,(select if(isnull(sum(C.걸음수)), 0 , sum(C.걸음수)) from 사용자통계 C where C.사용자_id=B.사용자_id and C.걷기대회_id=A.걷기대회_id) 누적걸음수 ,(A.목표걸음수 - (select if(isnull(sum(C.걸음수)), 0 , sum(C.걸음수)) from 사용자통계 C where C.사용자_id=B.사용자_id and C.걷기대회_id=A.걷기대회_id)) 남은걸음수 ,(A.기념품수) 기념품수 ,(A.경품수) 경품수 ,(A.참가자수) 참가자수 ,(A.완보자수) 완보자수 ,(A.협찬로고) 로고 ,concat(round((A.완보자수*100/A.참가자수),1),'%') 완보율 from 걷기대회 A, 사용자 B where B.사용자_id = '".$user_id."' and B.참여중대회_id = A.걷기대회_id )AA"; return $this->db->query( $sql )->row(); } } ?> <file_sep><!DOCTYPE html> <html lang="ko" class=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,target-densitydpi=medium-dpi"/> <!-- 공통 스타일 --> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.colors.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7-icons.css"> <link rel="stylesheet" href="/mnt/walk/common/css/common.css?t=1"> <title>참가현황 통계</title> <style> .myPrize_wrapper .menu .active{ font-weight:bold !important; } .clear{clear:both;} .info_content table td{width:50%;} .myPrize .color_prize{color:RGB(0,176,240);text-decoration:underline;} .myPrize .color_card{color:RGB(84,130,53);text-decoration:underline;} .myPrize .pic_box:after{content:"";clear:both;display:block;} .myPrize{display:none;} </style> </head> <body style="overflow:auto;"> <div class="myPrize_wrapper"> <div class="navbar" style="background:#ababab;height:40px;line-height:40px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="center" > ← 내 주머니 </div> <div class="right"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> </div> </div> <div class="menu" style="height:25px;line-height:25px;border-bottom:1px solid #cdcdcd;"> <div style="height:20px;line-height:24px;margin-top:10px;"> <div class="tab active" style="margin-left:-1px;float:left;width:50%;text-align:center;">스탬프</div> <div class="tab" style="border-left:1px solid #cdcdcd;float:left;width:50%;text-align:center;">경품 추첨권</div> </div> </div> <div class="clear"></div> <div class="myPrize_1 myPrize"> <div style="text-align:center;font-weight:bold;margin:30px 10px 10px 10px;">참가자님의 스탬프 획득 갯수는 <span class="color_prize">2개</span> 입니다.</div> <?php //스탬프 미션 가변 갯수??? 최대 5개??10개??ㅋㅋ ?> <div style="pic_box"> <div style="margin:0px 5%"> <div style="width:25%;float:left;text-align:center;"><img style="width:100%;" src="mnt/walk/prize/stamp_yes.png"/></div> <div style="width:25%;float:left;text-align:center;"><img style="width:100%" src="mnt/walk/prize/stamp_no.png"/></div> <div style="width:25%;float:left;text-align:center;"><img style="width:100%" src="mnt/walk/prize/stamp_yes.png"/></div> <div style="width:25%;float:left;text-align:center;"><img style="width:100%" src="mnt/walk/prize/stamp_no.png"/></div> </div> </div> <div class="clear"></div> <div style="margin-top:15px"> <div> <div style="width:200px;line-height:25px;height:25px;background-color:#aeaeae;margin:auto;text-align:center;font-weight:bold;">기념품 당첨여부 확인하기</div> </div> </div> <div class="info_Box" style="border:1px solid #333;border-radius:5px;margin:15px 2% 10px 2%;"> <div class="info_title" style="color:white;background-color:RGB(0,176,240);padding:2px 0px 2px 10px;font-size:14px;">혜택</div> <div class="info_content" style="margin-top:20px 10px;line-height:25px;padding:10px 5px;"> <table> <tr><td>캐논 렌즈 교환권</td><td style="text-align:right">1명</td></tr> <tr><td>스타벅스 커피 교환권</td><td style="text-align:right">100명</td></tr> <tr><td>카카오톡 이모티콘</td><td style="text-align:right">500명</td></tr> </table> </div> </div> <div class="info_Box" style="border:1px solid #333;border-radius:5px;margin:8px 2%;"> <div class="info_title" style="color:white;background-color:RGB(0,176,240);padding:2px 0px 2px 10px;font-size:14px;">스탬프 획득방법</div> <div class="info_content" style="margin-top:20px 10px;line-height:25px;padding:10px 5px;">대회장 내 스팟 도착시 실행되는 핫스팟 미션을 보시면 스탬프를 획득하실 수 있습니다.</div> </div> </div> <div class="myPrize_2 myPrize"> <div style="text-align:center;font-weight:bold;margin:30px 10px 10px 10px;">참가자님의 경품 추첨권 획득 갯수는 <span class="color_card">2개</span> 입니다.</div> <?php //스탬프 미션 가변 갯수??? 최대 5개??10개??ㅋㅋ ?> <div style="pic_box"> <div style="margin:0px 5%"> <div style="width:25%;float:left;text-align:center;"><img style="width:100%;" src="mnt/walk/prize/card_yes.png"/></div> <div style="width:25%;float:left;text-align:center;"><img style="width:100%" src="mnt/walk/prize/card_no.png"/></div> <div style="width:25%;float:left;text-align:center;"><img style="width:100%" src="mnt/walk/prize/card_yes.png"/></div> <div style="width:25%;float:left;text-align:center;"><img style="width:100%" src="mnt/walk/prize/card_no.png"/></div> </div> </div> <div class="clear"></div> <div style="margin-top:15px"> <div> <div style="width:200px;line-height:25px;height:25px;background-color:#aeaeae;margin:auto;text-align:center;font-weight:bold;">경품 당첨여부 확인하기</div> </div> </div> <div class="info_Box" style="border:1px solid #333;border-radius:5px;margin:15px 2% 10px 2%;"> <div class="info_title" style="color:white;background-color:RGB(84,130,53);padding:2px 0px 2px 10px;font-size:14px;">혜택</div> <div class="info_content" style="margin-top:20px 10px;line-height:25px;padding:10px 5px;"> <table> <tr><td>쉐보레 스파크</td><td style="text-align:right">1대</td></tr> <tr><td>갤럭시 S7</td><td style="text-align:right">3대</td></tr> <tr><td>신일전자 선풍기</td><td style="text-align:right">50대</td></tr> </table> </div> </div> <div class="info_Box" style="border:1px solid #333;border-radius:5px;margin:8px 2%;"> <div class="info_title" style="color:white;background-color:RGB(84,130,53);padding:2px 0px 2px 10px;font-size:14px;">경품 추첨권 획득방법</div> <div class="info_content" style="margin-top:20px 10px;line-height:25px;padding:10px 5px;">대회장 진입 후 아래 버튼 중 ‘미션’ 항목에 들어가서 주어진 미션을 해결하시면 됩니다. 미션은 핫스팟의 미션을 성공해야 확인하실 수 있습니다. 경품추첨권이 많아질수록 당첨확률은 높아집니다.</div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js?timestamp=201512210800"></script> <script> $(document).ready(function(){ $(".myPrize_1").show(); $(".menu .tab").each(function(idx){ $(this).click(function(){ $(".menu .tab").removeClass("active"); $(this).addClass("active"); $(".myPrize").hide(); $(".myPrize_"+(idx+1)).fadeIn(); }); }); }); </script> </body> </html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Game extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('game_model'); } /* * NAME: 이민수 * DATE: 20170317 * Description: 마이페이지 -> 내가 참여한 대회 */ function myGameList(){ //$data["indexes"] = $this->index_model->getIndexInfo(); $data=""; $this->load->view("game/myGameList_view", $data); } } ?><file_sep><style> .user_event .top_vanner{ position: absolute; width: 96%; height: 60px; background: royalblue; text-align: -webkit-center; } .top_vanner #dday,#dtime,#dsec{ color: white; } .top_vanner #dtime{ font-size:20px; } .user_event #panorama_track{ position: absolute; width: 96%; color: white; top: 20%; background: black; height: 5%; text-align: -webkit-center; } .middle_content{ position: absolute; width: 96%; top: 25%; height: 75%; background: grey; } .middle_content #walk_state{ text-align: center; font-size : 25px; } .middle_content .prize_state{ position: relative; height: 25%; width:100%; } .prize_state .left_state, .right_state{ position: relative; width: 48%; float: left; padding-bottom: 10%; text-align: center; } .prize_user_show_btn{ text-align: center; background: #9f5959; cursor: pointer; } .user_info_detail{ margin: 10px; color: white; font-size: 13px; } </style> <div class="user_event"> <div class="top_vanner"> <span id="dday">D-<?= $diff_day?> </span> <span id="dtime"><?= $diff_time?></span> <span id="dsec"></span> <p>기념품/경품 추첨일</p> </div> <div id="panorama_track"> 파노라마 트랙 </div> <div class="middle_content"> <div class="walk_success_state"> <p id="walk_state"></p> </div> <div class="prize_state"> <div class="left_state"> <p style="margin: 0px;">기념품 추첨 대상</p> <p style="margin: 0px;"></p> <p style="margin: 0px;">47.5%</p> </div> <div class="right_state"> <p style="margin: 0px;">경품 추첨 대상</p> <p style="margin: 0px;"></p> <p style="margin: 0px;">30.5%</p> </div> </div> <div class="prize_user_show_btn"> 당첨자 발표보기 </div> <div class="user_info_detail"> <p style="margin:0px"> <span>완료번호 : </span> </p> <p style="margin:0px"> <span>참가자명 : </span> </p> <p style="margin:0px"> <span>참가기간 : </span> </p> <p style="margin:0px"> <span>걸음수 : </span> </p> <p style="margin:0px"> <span>스템프 : </span> </p> <p style="margin:0px"> <span>경품추첨권 : </span> </p> </div> </div> </div> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Prize extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('prize_model'); } /* * NAME: 이민수 * DATE: 20170317 * Description: 스탬프 및 경품 추첨권 */ function index(){ //$data["indexes"] = $this->index_model->getIndexInfo(); $temp = $this->session_common->getSession("user"); $data["prizes"] = $this->prize_model->getPrizeList($temp["contest_id"]); $data["gifts"] = $this->prize_model->getGiftList($temp["contest_id"]); $this->load->view("prize/prize_view", $data); } /* * 조진근 * 20170327 * 경품추첨 탭을 표시 */ function drawTab(){ $this->load->view("activity/header_p"); $this->load->view("prize/draw_tab"); $this->load->view("activity/footer"); } /* * 조진근 * 20170327 * 경품추첨 뷰페이지 * 탭 선택에 따라서 경품과 기념품을 보여줌 */ function drawView($state="prize"){ if($state == "prize"){ $data["prizes"] = $this->prize_model->getPrizeList(); $data["flag"] = "prize"; }else if($state == "gift"){ $data["prizes"] = $this->prize_model->getGiftList(); $data["flag"] = "gift"; } $this->load->view("prize/draw_view",$data); } /* * 조진근 * 20170328 * 경품추첨 관련 탭을 표시 */ function awardTab(){ $this->load->view("activity/header_p"); $this->load->view("prize/prize_award_tab"); $this->load->view("activity/footer"); } /* * 조진근 * 20170328 * 경품추첨 관련 내용을 표시함 */ function awardView($tag = "stamp"){ $temp = $this->session_common->getSession("user"); $data["user"] = $temp["name"]; if ($tag == "mission") { $data["spots"] = $this->prize_model->getMissionState($temp["user_id"],$temp["contest_id"]); $data["count"] = $this->prize_model->getCountMission($temp["user_id"],$temp["contest_id"]); $data["flag"] = "flag"; } else { $data["spots"] = $this->prize_model->getSpotState($temp["user_id"],$temp["contest_id"]); $data["count"] = $this->prize_model->getCountSpot($temp["user_id"],$temp["contest_id"]); $data["flag"] = "stamp"; } $this->load->view("prize/prize_award",$data); } } ?> <file_sep>$(function(){ //navi control $('#mOpen a').bind('click',function(){ var winWidth = $(window).width(); var winHeight = null; var wH = $(window).height(); var aH = $('#allwrap').height(); if (wH > aH){ winHeight = wH; } else { winHeight = aH;} if (winWidth > 540){ var gnbW = 510; } else if (winWidth < 541 && winWidth > 480 ){ var gnbW = 420; } else {var gnbW = 280;} $('#allBg').css('height',winHeight); $('#allBg').show(); $('#navi').css('height','5px'); $('#navi').stop().animate({'width':gnbW},600,'easeInQuad', function() { setTimeout( function(){ $('#navi').stop().animate({'height':winHeight},600); $("#topMenu ul").slideToggle(600); $("#msnb ul").slideToggle(600); },300); }); }); $('#mClose').bind('click',function(){ $('#navi').stop().animate({'height':'5'},600,'easeInQuad', function() { $('#navi').stop().animate({'width':'0'},600); setTimeout( function(){ $('#allBg').hide() },600); }); $("#topMenu ul").slideToggle(600); $("#msnb ul").slideToggle(600); }); // navi ani $("#topMenu ul li").each(function( index ) { $(this).css({'animation-delay': (index/10)+'s'}); }); $("#msnb ul li").each(function( index ) { $(this).css({'animation-delay': (index/10)+'s'}); }); $('#allBg').click(function(){ $('#mClose').click(); }); var $el, leftPos, newWidth, $mainNav = $("#topMenu ul"); $mainNav.prepend("<li id='magic-line'><span class='lt'></span><span class='rt'></span><span class='lb'></span><span class='rb'></span></li>"); var lineOpen = function(){ var winWidth = $(window).width(); var targetDiv = $(this); var $magicLine = $("#magic-line"); var lineHeight = targetDiv.height(); var lineTop = (targetDiv.parent().index() -1) * lineHeight; var lineLeft = null; if (winWidth > 480){ lineLeft = 30; } else { lineLeft = 15 }; var lineWidth = null; if (winWidth > 480){ lineWidth = targetDiv.width()+60; } else { lineWidth = targetDiv.width()+30; }; $magicLine.fadeIn(); $magicLine.stop().animate({ 'width': lineWidth, 'left': targetDiv.position().left - lineLeft, 'top': lineTop },200); } $('#topMenu ul').mouseleave(function(){ $("#magic-line").hide(); }); var filter = "win16|win32|win64|mac"; if(navigator.platform){ if(0 > filter.indexOf(navigator.platform.toLowerCase())){ // mobile } else { $("a[id^=topNavi]").each(function() { $(this).mouseover(lineOpen) .focus(lineOpen) }); } } });<file_sep><style> .ostitle{ font-weight:bold; font-size:20px; margin:20px; } .speechContents{ padding:20px; } </style> <div class="openSpeech_box" style="width:100% height:100%"> <?php foreach($speeches as $speech){ ?> <div class="speechContents"> <?= $speech -> 내용 ?> </div> <div align="center"> <video controls src="<?= 경로_메시지?><?= $speech -> 동영상경로 ?>" width="80%" height="20%"> </video> </div> <?php } ?> </div><file_sep><style> .adsChange_view{ width:100%; height:100%; } .adsChange_title { padding: 30px; padding-bottom:10%; font-size:20px; text-align:center; } div{ padding : 10px; } .adsChange{ border : 1px; background : lightskyblue; padding : 5px; color:white; cursor:pointer; width:70%; margin:100px auto; text-align:center; padding:15px 0; } </style> <div class="adsChange_view"> <div class="adsChange_title"> 주소 재설정 </div> <div class="adsChange_content" style="padding-bottom:70px"> <form action="/user/adsChange" method="post" class="newAddress"> <div> 아이디 : <?=$user_id?> </div> <div> 변경할 주소를 입력하세요. <input type="text" name="newAdd" id="newAdd" style="border:none;border-bottom:1px solid black"> </div> </form> </div> <div class="adsChange"> 변경완료 </div> </div> <script> $('.adsChange').click(function() { $('.newAddress').submit(); }); </script> <file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui"> <title>index</title> <style> table{ border-collapse: collapse; width: 100%; style="table-layout:fixed" } td, th{ border: 2px solid #dddddd; text-align: left; padding: 3px; } tr:nth-child(even){ background-color: #dddddd; } tr{ cursor:pointer; } span{ display:-webkit-inline-box; width:100%; } div h3{ background:#bbb; width:100%;" color:black; padding:10px;" } </style> </head> <body> <div><h3>개발 page목록</h3></div> <table> <tr> <th>이름</th> <th>url</th> <th>worker</th> </tr> <?php foreach ($indexes as $row){ ?> <tr> <td><?= $row->항목; ?></td> <td><a href="<?= $row->url?>" /><?= $row->url ?></a></td> <td><?= $row->작성자 ?></td> </tr> <?php } ?> </table> </body> </html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Question extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('question_model'); } function questionIndex(){ $this->load->view("activity/header_p"); $this->load->view("question/question_index"); $this->load->view("activity/footer"); } function questionIndex_sub($index){ if($index==41){ $data['faqs']=$this->question_model->questionIndex_sub($index); $this->load->view("activity/header_p"); $this->load->view("question/faq_view",$data); $this->load->view("activity/footer"); }else{ $data['questions']=$this->question_model->questionIndex_sub($index); $this->load->view("activity/header_p"); $this->load->view("question/question_view",$data); $this->load->view("activity/footer"); } } } ?><file_sep><style> .guide{ padding:15px; } .queKind{ float:right; margin-right:30px; font-size:15px; width:60%; padding:5px; background:#b7b5b5; } .question_content>div{ margin:5px; width:90%; } #contents{ width:90%; height:100px; margin:5px; } #name_t,#email_t{ width:35%; float:left; } #name_c, #email_c{ width:50%; float:left; } .adm{ margin:10px; } .inquiry{ width:90%; background:#ffc107; text-align:center; font-weight:bold; padding:5px; cursor:pointer; } </style> <div class="que" style="width:100%;height:100%;"> <div class="guide"> 서비스 이용에 궁금한 점이나 개선사항에 대해 알려주세요. <br> 보내주신 내용을 토대로 서비스 개선에 반영하겠습니다. </div> <div> <form action="/board/insertQue" method="post" class="question"> <div style="height:50px"> <select class="queKind" name="queKind"> <?php foreach($qnaTitles as $qnaTitle){ ?> <option value="<?= $qnaTitle -> 공통코드_id?>"> <?= $qnaTitle -> 코드명 ?> </option> <?php } ?> </select> </div> <div class="question_content"> <div id="name_t"> 이름 </div> <div id="name_c"> <input type="text" id="name" name="name" size="30"></div> <div id="email_t"> 이메일 </div> <div id="email_c"> <input type="text" id="email" name="email" size="30"> </div> <textarea id="contents" name="contents" placeholder="내용을 입력하세요"></textarea> </div> </form> </div> <div class="adm"> 포커스뉴스<br> 담당자 이메일 : <EMAIL> <br> 팩스 : 02-580-2900 </div> <div class="inquiry"> 문의하기 </div> </div> <script> $(document).ready(function(){ $(".inquiry").click(function(){ $('.question').submit(); }); }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Board_model extends CI_Model{ function __construct(){ parent::__construct(); } //공지사항 가져오기 function getNotices($count=2){ $this->db->select("a.*,b.코드명"); $this->db->from("게시판 as a"); $this->db->join('공통코드 as b', 'a.게시판종류 =b.공통코드_id','',FALSE); $this->db->where("a.게시판종류",29); $this->db->order_by("a.등록일 desc"); //$this->db->limit(2,0); //거꾸로 return $this->db->get()->result(); } /* * getCommentTags * 이소희 * 20170331 * 댓글 태그 정보 가져오기 */ function getCommentTags(){ $this->db->select("*"); $this->db->from("공통코드"); $this->db->where("코드분류_id","COMMENT_TAG"); return $this->db->get()->result(); } /* * commentCnt * 이소희 * 20170403 * 댓글 전체 개수 가져오기 */ function commentCnt(){ $this->db->select("count(*) cnt"); $this->db->from("댓글"); return $this->db->get()->row()->cnt; } /* * getTalkComments * 이소희 * 20170331 * 모든 댓글 가져오기 */ function getTalkComments(){ $this->db->select("댓글_id, 작성자, date_format(작성일, '%y-%m-%d') as 작성날짜, 댓글, 사진",false); $this->db->from("댓글"); $this->db->join('사용자', '댓글.작성자 = 사용자.사용자_id','',FALSE); $this->db->order_by("댓글_id","desc"); $this->db->limit(10); return $this->db->get()->result(); } /* * commentByTag * 이소희 * 20170331 * 태그에 따라 댓글 가져오기 */ function commentByTag($ctag_id){ $this->db->select("작성자, 댓글.태그, date_format(작성일, '%y-%m-%d') as 작성날짜, 공통코드.코드명, 댓글, 사진",false); $this->db->from("댓글"); $this->db->join('공통코드', '공통코드.공통코드_id=댓글.태그','',FALSE); $this->db->join('사용자', '댓글.작성자 = 사용자.사용자_id','',FALSE); $this->db->where("태그", $ctag_id); $this->db->order_by("댓글_id","desc"); $this->db->limit(10); return $this->db->get()->result(); } /* * commentTagCnt * 이소희 * 20170403 * 태그 기준 댓글 전체 개수 가져오기 */ function commentTagCnt($ctag_id){ $this->db->select("count(*) cnt"); $this->db->from("댓글"); $this->db->where("태그",$ctag_id); return $this->db->get()->row()->cnt; } /* * addComment * 이소희 * 20170404 * 덧글 더보기 추가 (내림차순으로 정렬) */ function addComment($firstIndex,$totalCnt){ /*$sql = "select 작성자, date_format(작성일, '%y-%m-%d') as 작성날짜, 댓글, 사진 from 댓글 join 사용자 on 댓글.작성자 = 사용자.사용자_id" ." order by 댓글_id desc limit ".$firstIndex.", 10";*/ $sql = "select 작성자, date_format(작성일, '%y-%m-%d') as 작성날짜, 댓글, 사진 from 댓글 join 사용자 on 댓글.작성자 = 사용자.사용자_id where 댓글.댓글_id<=".$totalCnt."-".$firstIndex." order by 댓글.댓글_id desc limit 10"; return $this->db->query( $sql )->result(); } /* * addCommentByTag * 이소희 * 20170404 * 덧글 더보기 추가 (내림차순으로 정렬) - addComment는 댓글_id기준으로 비교했지만 Tag를 통해 select한 거기 때문에 비교하기가 힘들다. */ function addCommentByTag($ctag_id, $firstIndex2){ $sql = "select 작성자, date_format(작성일, '%y-%m-%d') as 작성날짜, 댓글, 사진 from 댓글 join 공통코드 on 공통코드.공통코드_id=댓글.태그 join 사용자 on 댓글.작성자 = 사용자.사용자_id" ." where 태그=".$ctag_id." order by 댓글_id desc limit ".$firstIndex2.", 10"; return $this->db->query( $sql )->result(); } /* * insertComment * 이소희 * 20170331 * 모든 댓글 가져오기 */ function insertComment($user_id, $comment){ $this->db->set("작성자", $user_id); $this->db->set("댓글", $comment); $this->db->set("작성일","NOW()", FALSE); return $this->db->insert('댓글'); } /* * 이소희 * 20170329 * MainActivity_2 하위 컴포넌트 * 대회 댓글 컴포넌트 (댓글 3개) */ function getThreeComments(){ $this->db->select("*"); $this->db->from("focus_walk.댓글"); $this->db->join('사용자', '댓글.작성자 = 사용자.사용자_id','',FALSE); $this->db->order_by("작성일","desc"); $this->db->limit(3); return $this->db->get()->result(); } /* * faqType * 이소희 * 20170328 * FAQ 질문 분류(코드명) 불러오기 */ function faqType(){ $this->db->select("*"); $this->db->from("공통코드"); $this->db->where('코드분류_id','FAQ_TYPE'); $this->db->order_by('공통코드_id'); return $this->db->get()->result(); } /* * questionIndex_sub * 이소희 * 20170328 * FAQ질문을 머릿글 종류에 따라 불러오기 */ function questionIndex_sub($index){ $this->db->select("*"); $this->db->from("게시판"); $this->db->join('공통코드','게시판.머릿글종류=공통코드.공통코드_id','',FALSE); $this->db->where("게시판종류",$index); $this->db->order_by('게시판_id'); return $this->db->get()->result(); } /* * qnaType * 이소희 * 20170328 * QnA SELECT 박스(코드명) 불러오기 */ function qnaType(){ $this->db->select("*"); $this->db->from("공통코드"); $this->db->where('코드분류_id','QNA_TYPE'); $this->db->order_by('공통코드_id'); return $this->db->get()->result(); } /* * insertQue * 이소희 * 20170328 * 문의하기 */ function insertQue($info){ $data = array( '게시판종류' => 42 , '머릿글종류' => $info['queKind'], '글제목' => $info['contents'], '글내용' => null, '등록일' => date("Y-m-d"), '수정일' => null, '작성자_id' => $info['name'], '삭제여부' => 0 ); return $this->db->insert('게시판',$data); } } ?> <file_sep><style> .pwView{ width:100%; height:100%; } .pw_title { padding: 30px; padding-bottom:10%; font-size:20px; text-align:center; } .pw_content{ text-align:center; padding-top:10%; width:100%; height:100% } .sb{ position:absolute; width:100%; margin:0 auto; bottom:20%; } .pwView .nextBtn{ background:#60b9f0; margin:50px auto; width:70%; position:relative; padding:10px 0px; text-align:center; color:white; } </style> <div class="pwView"> <div class="pw_title"> 비밀번호 확인 </div> <div class="pw_content"> <form action="/user/<?=(($check==1)? "pwChange":"pwCheck")?>/<?=$check?> " method="post" class="pwinfo"> <div style="line-height:300px"> <input type="password" name="password" placeholder="현재 비밀번호를 입력하세요" style="padding-right:100px;,padding-left:100px; padding-bottom:10px;border:none; border-bottom:1px solid black; width:100%; text-align:center"> </div> <div style="color:red"> <?=$pw_error?> </div> </form> </div> <div class="nextBtn"> 다음 단계 </div> </div> <script> $(document).ready(function() { $('.nextBtn').click(function() { $('.pwinfo').submit(); }); }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class promotion extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('promotion_model'); } /* * 조진근 * 20170317 * checkinTab * 진행중인 프로모션과 종료된 프로모션을 로드 * checkinTab view에서 선택된 프로모션 리스트를 출력 */ function promotionTab(){ $this->load->view ( "activity/header_p" ); $this->load->view("promotion/promotion_tab"); $this->load->view ( "activity/footer" ); } /* * 조진근 * 20170322 * checkinPreview * 마이그레이션 페이지 내에 최신 2개의 리스트 2개만 출력 */ function checkinPreview(){ $data["count"] = $this->promotion_model->getPromoCount(); $data["events"] = $this->promotion_model->getOpenedList(0,2); $this->load->view ( "activity/header_p" ); $this->load->view("promotion/checkinPreview",$data); $this->load->view ( "activity/footer" ); } /* * 조진근 * 20170322 * checkinView * checkinTab 내에 진행중/종료된 프로모션 페이지자를 호출 */ function promotionView($state='open'){ if($state == "open"){ $data["checkInList"] = $this->promotion_model->getOpenedList(); }else if($state == "close"){ $data["checkInList"] = $this->promotion_model->getClosedList(); } $this->load->view("promotion/promotion_list", $data); } } ?> <file_sep><table style="z-index:100;position:fixed;width:100%;padding:10px 0 10px 0;background-color:#ffffff;"> <tr> <td style="text-align:left;width:130px;padding-left:5px;"><b>대화중인 쪽지방</td> <td style="text-align:left;border-bottom:1px solid #555;"></td> </tr> </table> <div class="list_box" id="mscheck" style="padding-top:35px;"> <form action="/friends/msRoom/" method="POST" id="form"> <input type="hidden" id="groupId" name="groupId" value=""/> </form> <ul class="msCheck_box"><?php foreach($friendIds as $friendId ) { ?> <?php $date_temp=date_create($friendId->전송일시); $date_time = date_format($date_temp,"h:i:s"); $date_ampm = date_format($date_temp,"A"); $date_ampm =$date_ampm =="AM"?"오전":"오후"; ?> <li> <div class="room_box" m_name="<?=$friendId->그룹_id?>"> <div class="room_btn" style="margin-right:60px;min-height:50px;" onclick="room_btn_click('<?=$friendId->그룹_id?>')"> <div class="mythumb2"> <img src="<?=경로_사용자?><?=$friendId->사진?>" alt=""> </div> <div style="margin-left:60px"> <div class="userName"><b><?=$friendId->이름?></b></div> <input type="hidden" class="find" value="<?=$friendId->전송_id?>"/> <div class="time"> <div style="position:relative"> <?php if($friendId->확인여부=="N" && $friendId->전송_id!=$userId){ ?> <img class="badge" src="/mnt/walk/friends/N.PNG" alt="확인하지 않은 메세지에서 나타남"> <?php } ?> <?=$date_ampm?> <?=$date_time?> </div> </div> <div class="text_over" v_id="<?=$friendId->쪽지_id?>"> <?=$friendId->내용?> </div> </div> </div> <div class="det2" name="<?=$friendId->전송_id?>">삭제</div> </div> </li> <?php } ?> </ul> </div> <div id="pop_delete" class="pop-layer"> <div class="pop-container"> <div class="pop-conts"> <p>쪽지 삭제</p> <p class="ctxt mb20"></p> <div class="btn-r" value=" "> <div id="ok">확인</div> <div id="cancel">취소</div> </div> </div> </div> </div> <script> $(document).ready(function() { var group_id_tmp = ""; var name_name_tmp = ""; var ms_id_tmp = ""; msCheckEvent(); setInterval(getNewCheck, 5000); <?php //5초마다 한번씩 getNewCheck 함수 발동 ?> }); function room_btn_click(id){<?php //post방식으로 파라미터 넘겨주기 위한 함수 ?> $("#groupId").val(id); <?php //room_btn 클릭시에 groupId라는 id를 가진 input 태그에 value를 넣어준다. ?> $("#form").submit(); } function getNewCheck(){ <?php //새로운 메세지 왔을 때 refresh ?> $.ajax({ type:"POST", url:"/friends/refreshCheck", dataType:"text", success: function(result){ $(".msCheck_box").html(result.trim()); msCheckEvent(); },error: function(result){ alert("오류가 발생했습니다."); } }); } function msCheckEvent(){ <?php //refresh할 때 이벤트 초기화를 방지하기 위한 함수 ?> $('.room_btn').each(function(){ $(this).click(function(){ $(this).parent().submit(); }); }); $('.room_box .det2').click(function(){ name_name_tmp=$(this).parent().find(".userName b").html(); $('#pop_delete').show(); $('.btn-r').attr("value",$(this).parent().attr("m_name")); $('.ctxt').text(name_name_tmp+" 님과의 쪽지를 삭제하시겠습니까?"); }); $('.pop-layer #cancel').click(function() { $('#pop_delete').hide(); }); $('.pop-layer #ok').click(function() { group_id_tmp = $(this).parent().attr("value"); $('#pop_delete').hide(); $.ajax({ type:"POST", url: "/friends/deleteMs", dataType:"text", data:{ "groupId" : group_id_tmp }, success: function(result){ friendsReload(3); },error: function(result){ alert("오류가 발생했습니다."); } }); }); } </script><file_sep><style> .pop-layer .pop-container { padding: 20px 25px; } .pop-layer { display: none; position: absolute; top: 20%; left: 10%; width: 310px; height: auto; background-color:white; z-index:10000; } .pop_bt, .check, .cancel{ border : 1px; background : lightskyblue; padding : 5px; margin:5px; color:white; } .drView{ width:100%; height:100%; } .drView .drView_title{ font-size:20px; text-align:center; padding:30px; padding-bottom:20%; color:#979797; } .drView .drView_content{ padding-left:5%; padding-bottom:30%; } drView.pop_bt:active{ background-color: black; } #mask { position:absolute; z-index:9000; background-color:#000; display:none; } .pop-container .pop-title{ border-bottom: 1px solid black; padding-bottom:5% } .pop-container .message{ padding-top:5%; } </style> <div id="mask"></div> <div class="drView"> <div class="drView_title"> 회원탈퇴 사유선택 </div> <div class="drView_content"> <form action=""> <?php foreach ($pwReasons as $pwReason ) { if($pwReason-> 공통코드_id==6){ ?> <div style="padding:5px; font-size:20px;"> <input type="radio" name="reason" value="<?=$pwReason-> 공통코드_id?>"><?=$pwReason-> 코드명?> <input type="text" name="etc" style="border:none; border-bottom:1px solid black; width:70%"> </div> <?php } else { ?> <div style="padding:5px; font-size:20px;"> <input type="radio" name="reason" value="<?=$pwReason-> 공통코드_id?>"><?=$pwReason-> 코드명?> </div> <?php } } ?> </form> </div> <div class="pop_bt" style="background:#60b9f0; margin:0px auto; width:70%; position:relative; padding:10px 0px; text-align:center; color:white"> 확인 </div> </div> <div id="layer1" class="pop-layer"> <div class="pop-container"> <div class="pop-conts"> <div class="pop-title" align="center">회원탈퇴 유의사항 </div> <?php //content ?> <div class="message" align="center" style="">회원탈퇴 시 대회 참여이력, 친구 정보, 쪽지, 경품 획득 정보 등 개인정보가 삭제되면 복구 및 이용이 불가능합니다. </div> <div class="btn-r"> <div class="check" style="cursor:pointer; display:inline"> 확인하고 탈퇴하겠습니다. </div> <div class="cancel" style="cursor:pointer; display:inline"> 취소 </div> </div> </div> </div> </div> <script> $(document).ready(function() { $('.pop_bt').click(function() { <?php //validation 선택 된것이 없거나 ?> if($(":input:radio[name=reason]").is(':checked')==false){ alert("체크하지 않았습니다."); return; } <?php //기타인 경우 값이 없을 때 ?> if($(":input:radio[name=reason]:checked").val()==6 && $(":input:text[name=etc]").val()==""){ alert("기타 내용을 입력하세요"); return; } //화면 팝업 처리 wrapWindowByMask(); }); $('.cancel').click(function() { $('#mask, #layer1').hide(); }); $('.check').click(function() { $('#mask,#layer1').hide(); $.ajax({ type:"POST", url: "/user/deleteInfo", dataType:"json", data:{"reason" : $(":input:radio[name=reason]:checked").val(), "etc" : $(":input:text[name=etc]").val() }, success: function(result){ alert("삭제 완료"); location.href="/user/loginIndex" },error: function(result){ } }); }); function wrapWindowByMask(){ //화면의 높이와 너비를 구한다. var maskHeight = $(document).height(); var maskWidth = $(window).width(); //마스크의 높이와 너비를 화면 것으로 만들어 전체 화면을 채운다. $("#mask").css({"width":maskWidth,"height":maskHeight}); $("#mask").fadeTo("slow",0.6); $(".pop-layer").show(); } }); </script><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Message extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('message_model'); $this->load->library('session_common'); } /* * celMessage_comp * 이소희 * 20170327 * MainActitiy에서 개회사 및 축하메시지 하나만 출력 */ function celMessage_comp(){ $data['speech'] = $this->message_model->celMessage_comp(1); $data['celMessage'] = $this->message_model->celMessage_comp(2); $this->load->view("message/celMessage_comp",$data); } /* * celeIndex * 이소희 * 20170324 * 축하메시지 메뉴 초기화면 */ function celeIndex($index){ $data['index'] = $index; $this->load->view("activity/header_p"); $this->load->view("message/celeIndex",$data); $this->load->view("activity/footer"); } /* * celeIndex_sub * 이소희 * 20170327 * 개회사 및 축하메시지 출력 */ function celeIndex_sub($index){ if($index==1){ $data['speeches'] = $this->message_model->celeIndex_sub($index); $this->load->view("activity/header_p"); $this->load->view("message/openSpeech",$data); $this->load->view("activity/footer"); }else{ $data['celMessages'] = $this->message_model->celeIndex_sub($index); $this->load->view("activity/header_p"); $this->load->view("message/celMessage",$data); $this->load->view("activity/footer"); } } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Hotspot_model extends CI_Model{ function __construct(){ parent::__construct(); } /* * 조진근 * 20170316 * getHotspotList * 핫스팟과 핫스팟상품 핫스팟체크인의 연관데이터 호출 * 기간이 얼마 남지 않은 순으로 정렬 */ function getHotSpotList($user){ $this->db->select('B.핫스팟_id, B.제목, B.배너, B.위도, B.경도, B.추첨권수, C.분류, E.코드명',FALSE); $this->db->select('CONCAT(date_format(체크인_종료일시,"%Y년 %m월 %d일"),"까지") AS 체크인_종료시간, CAST(UNIX_TIMESTAMP(체크인_종료일시) AS SIGNED) AS 종료시간', FALSE); $this->db->from('사용자` as A'); $this->db->join("핫스팟 as B", "A.참여중대회_id = B.걷기대회_id","",FALSE); $this->db->join("경품추첨권 as C", "C.사용자_id = A.사용자_id AND B.핫스팟_id = C.분류_id","LEFT OUTER",FALSE); $this->db->join("공통코드 AS E", "C.분류 = E.공통코드_id ","LEFT OUTER",FALSE); $this->db->order_by("체크인_종료일시 DESC"); $this->db->where("A.사용자_id",$user); return $this->db->get()->result(); } /* * 조진근 * 20170316 * getPromotionList * 프로모션_id와 연관된 핫스팟 데이터를 선택 * 기간이 얼마 남지 않은 순으로 정렬 */ function getPromotionList($user, $id){ $this->db->select("*, A.제목, A.배너,date_format(체크인_종료일시,'%Y년 %m월 %d일') AS 체크인_종료시간, CAST(UNIX_TIMESTAMP(체크인_종료일시) AS SIGNED) AS 종료시간, ,case when 코드명 is null then '참여가능' else 코드명 end ",FALSE); $this->db->from("핫스팟 as A",FALSE); $this->db->join("경품추첨권 B "," A.핫스팟_id = B.핫스팟_id and B.사용자_id = '$user'" ,"LEFT OUTER",FALSE); $this->db->join("공통코드 as C", " C.공통코드_id = B.상태","LEFT OUTER",FALSE); $this->db->where("A.프로모션_id",$id); return $this->db->get()->result(); } /* * 조진근 * 20170316 * getHotspotView * 지정된 핫스팟의 정보를 호출 */ function getHotspotView($user , $id){ $this->db->select('*,A.제목, A.배너 as banner, C.분류',FALSE); $this->db->from('핫스팟 as A'); $this->db->join("프로모션 as B", "A.프로모션_id = B.프로모션_id","right",FALSE ); $this->db->join("경품추첨권 as C", "A.핫스팟_id = C.분류_id and C.사용자_id = '$user'","left outer",FALSE ); $this->db->where("A.핫스팟_id",$id); return $this->db->get()->row(); } /* * 조진근 * 20170405 * getHotspotState * 핫스팟의 총 경품추첨권 */ function getHotspotState($user, $id){ $this->db->select("concat(count(case when B.분류 = 50 then A.핫스팟_id end),' / ', count(A.핫스팟_id)) as checkIn", FALSE); $this->db->select("concat(sum(case when B.분류 = 50 then A.추첨권수 end) ,' / ', sum(A.추첨권수)) as prize",FALSE); $this->db->from("핫스팟 as A", FALSE); $this->db->join("경품추첨권 as B","A.핫스팟_id = B.분류_id and B.사용자_id = '$user'","LEFT OUTER",FALSE); $this->db->where("A.걷기대회_id",$id); return $this->db->get()->row(); } /* * 조진근 * 20170405 * insertDB * 경품추첨권 테이블에 핫스팟에 체크인한 유저 정보를 삽입 */ function insertDB($user_id, $contest_id){ $sql = "insert into 경품추첨권(사용자_id, 분류, 분류_id, 획득일) values('".mysql_real_escape_string($user_id)."', 50, '".mysql_real_escape_string($contest_id)."', now()) ON DUPLICATE KEY UPDATE 사용자_id = '".mysql_real_escape_string($user_id)."', 분류_id = '".mysql_real_escape_string($contest_id)."'"; $this->db->query($sql); } } ?> <file_sep><div class="list_box"> <div class="invite_container"> 나와 친구를 맺고 있는 참가자 입니다. </div> <ul> <?php foreach($invitefriends as $invitefriend ) { ?> <li> <div class="invite_box"> <div class="mythumb"><img src="<?=경로_사용자?><?=$invitefriend->사진?>" alt=""></div> <div class="userName" style="margin:15px 0px;margin-left:70px;"><?=$invitefriend->이름?></div> <?php if($invitefriend->상태 == '초대'){ ?> <div class="id_box" v_id="<?=$invitefriend->친구_id?>" v_name="<?=$invitefriend->이름?>"> <div class="invite_bt" name="<?=$invitefriend->이름?>"><?=$invitefriend->상태?></div> </div> <?php }else{ ?> <div class="notinvite_bt"style="background-color:#d1f9b6; color:#cdcdcd;"><?=$invitefriend->상태?></div> <?php } ?> </div> </li> <?php } ?> </ul> </div> <div id="pop_delete" class="pop-layer"> <div class="pop-container"> <div class="pop-conts"> <p>친구 초대</p> <p class="ctxt mb20"></p> <div class="btn-r"> <div id="ok">확인</div> <div id="cancel">취소</div> </div> </div> </div> </div> <script> $(document).ready(function() { var name_id_tmp = ""; var name_name_tmp=""; $('.invite_bt').click(function() { name_name_tmp = $(this).parent().attr("v_name"); name_id_tmp = $(this).parent().attr("v_id"); $('#pop_delete').show(); $('.ctxt').text(name_name_tmp+" 친구를 참여 중인 대회에 초대하시겠습니까?"); }); $('.pop-layer #cancel').click(function() { $('#pop_delete').hide(); }); $('.pop-layer #ok').click(function() { $('#pop_delete').hide(); $.ajax({ type:"POST", url: "/friends/insertInvite", dataType:"text", data:{ "friend_id" : name_id_tmp }, success: function(result){ inviteReload(1); },error: function(result){ alert("오류가 발생했습니다."); } }); }); }); </script><file_sep><div class="cmt_comm"> <?php foreach($comments as $comment){ ?> <div class="list_cmt"> <div><img class="cmt_head" src="<?=경로_사용자?><?=$comment->사진 ?>" alt=""/></div> <div class="cmt_body"> <p class="txt_desc"> <?= $comment -> 댓글?> </p> <div class="info_append"> <div class="txt_name"><?= $comment -> 작성자?></div> <div class="txt_time"><?= $comment -> 작성일?></div> </div> </div> <div class="cmt_foot" style="display:none"> <a href="#none">답글</a><span class="txt_bar">|</span><a href="#none">수정</a><span class="txt_bar">|</span><a href="#none">삭제</a><span class="txt_bar">|</span><a href="#none">신고</a> </div> </div> <?php }?> </div> <div style="height:30px;line-height:30px;background-color:RGB(171,171,171);color:black;"><strong class="screen_out">모두보기</strong></div> <file_sep><style> #message{ width:100%; height:100% } .messageTab{ border-bottom:1px solid black; padding-bottom:15px } </style> <div class="message"> <div class="messageTab" align="center"> <div id="os" style="display:inline; border-right:1px solid black;font-weight:bold; font-size:25px" onclick="pageloading(1)"> 개회사 </div> <div id="message" style="display:inline; margin-left:10px; font-size:25px" onclick="pageloading(2)">축하메시지 </div> </div> <div class="contents"> </div> </div> <script type="text/javascript"> $(document).ready(function() { pageloading(<?= $index?>); }); function pageloading(index){ switch(index){ case 1 : $("#os").css("font-weight","bold"); $(".messageTab #message").css("font-weight",""); $(".contents").load("/message/celeIndex_sub/"+index); break; case 2: $("#os").css("font-weight",""); $(".messageTab #message").css("font-weight","bold"); $(".contents").load("/message/celeIndex_sub/"+index); break; } } </script><file_sep><?php /* * Walk_common * 최재성 * 20170314 * 공통라이브러리 */ class Walk_common { public function __construct(){ $this->CI =& get_instance(); } /* * func_getData * 최재성 * 20170314 * t_code테이블의 데이터 return */ public function func_getCode($code){ $result = null; $this->CI->db->select("*"); $this->CI->db->from("공통코드"); $this->CI->db->where("코드분류_id" , $code); $this->CI->db->order_by("순서"); $this->CI->db->order_by("코드명"); $result = $this->CI->db->get()->result(); return $result; } public function readHtmlFile($fileName){ $htmlFile = FILE_ROOT.$fileName; if(!file_exists($htmlFile)) return ""; $fm = fopen( $htmlFile, "rb" ); $fileSize = filesize ( $htmlFile ); $cur=0; //remote_file_size 웹에서 불러온 파일은 filesize가 인식을 못함 따라서 위와 같은 함수를 hotspot_model에 정의 $html = ""; while(!feof($fm)&&$cur<$fileSize){ $html .= fread($fm,min(1024 *16,$fileSize-$cur)); $cur+=1024 * 16; } fclose($fm); return $html; } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Message_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->helper('date'); } /* * celMessage_comp * 이소희 * 20170327 * MainActitiy에서 개회사 및 축하메시지 하나만 출력 */ function celMessage_comp($index){ $this->db->select("*"); $this->db->from("메시지"); $this->db->where("type",$index); $this->db->order_by('메시지_id'); $this->db->limit(1); return $this->db->get()->row(); } /* * celeIndex_sub * 이소희 * 20170327 * 개회사 및 축하메시지 출력 (ALL) */ function celeIndex_sub($index){ $this->db->select("*"); $this->db->from("메시지"); $this->db->where("type",$index); $this->db->order_by('메시지_id'); return $this->db->get()->result(); } } ?> <file_sep><link rel="stylesheet" href="<?=ADMIN_PATH?>css/MainActivity_2/init.css"> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/jcanvas.min.js"></script> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/calc.js"></script> <script type="text/javascript" src="<?=ADMIN_PATH?>js/common/tracker.js"></script> <!-- Views --> <div class="views"> <div class="view view-main"> <div class="pages"> <!-- page --> <div data-page="MainActivity_2" class="page" style="background:#fff;overflow:hidden;"> <div class="page-content" style="background:#0d0d0d;overflow-x:hidden;"> <div class="page2"> <!-- navbar --> <div class="navbar" style="background:#0d0d0d;height:50px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="left"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> <div class="center"> <a href="#" class="link" style="font-size:14px;"> <?=$event_info[0]->제목?> </a> </div> <div class="right"> <a href="#" class="link" style="font-size:14px;"> 닫기 </a> </div> </div> </div> <!-- navbar END --> <!-- 토글 박스 내용 --> <div comp_prop="toggle_comp"> </div> <!-- 트랙 --> <div comp_prop="contest_comp"> </div> <!-- 대회 댓글 --> <div comp_prop="comment" style="margin:5px;"> </div> <!-- 축하메시지 --> <div comp_prop="cm_msg" class="cm_box" style="background:RGB(127,127,127);padding-bottom:5px;margin-top:15px;"> </div> <div style="clear:both;"></div> <!-- 매거진 --> <div comp_prop="magazine_comp" class="book_box" style="background:RGB(127,127,127);padding-bottom:5px;margin-top:15px;"> </div> <div style="clear:both;"></div> <!-- 대회 간략 정보 --> <div comp_prop="summary" class="summary_box"> </div> </div> </div> </div> <div comp_prop="stamp_sheet_get" class="picker-modal picker-get-stamp" style="height:auto;background:#515151;color:white;"> </div> <div comp_prop="stamp_sheet_set" class="picker-modal picker-set-stamp" style="height:auto;background:#515151;color:white;"> </div> <div comp_prop="prize_sheet_get" class="picker-modal picker-get-prize" style="height:auto;background:#515151;color:white;"> </div> <div comp_prop="prize_sheet_set" class="picker-modal picker-set-prize" style="height:auto;background:#515151;color:white;"> </div> <div class="custom-toolbar toolbar toolbar-bottom" style="overflow:hidden"> <div class="toolbar-inner toolbar1" style="transition:1s;"> <a href="#" class="link external">공지사항</a> <a href="/walk/condition/" class="link external">대회현황</a> <a href="/activity/MainActivity_2/" class="link external"><i class="f7-icons size-22">home_fill</i></a> <a href="#" class="link external">커뮤니티</a> <a href="/hotspot/hotspotListWithGoogleMap" class="link external">핫스팟</a> </div> <div class="toolbar-inner toolbar2" style="top:50px;transition:1s;"> <a href="/activity/MainActivity_2/index/1" class="link external">진행중</a> <a href="/activity/MainActivity_2/index/0" class="link external">완보시</a> <a href="#" class="link external" onClick="temp_Mission();">미션받기</a> <a href="/content/deleteWish/" class="link" onClick="setTimeout(function(){ location.reload(); },300);">초기화</a> <a href="#" class="link external" onClick="temp_Move();">걸음수+10</a> </div> <a href="#" class="link customlink"><i class="f7-icons">more_vertical</i></a> </div> </div> </div> </div> <script> var myApp = new Framework7({ material: true, pushState : true, }); var mainView = myApp.addView('.view-main'); var $$ = Dom7; var w_width = $(window).width(); var w_height = $(window).height(); var poster_info_anim_flag = true; </script> <script> var isVisible_toggle_box=false; var contest_state = <?=$contest_state?>; $(document).ready(function(){ $.post("/walk/toggle_comp/", { contest_state : contest_state }, function(response){ $("div[comp_prop='toggle_comp']").html(response); $(".toggle_btn").click(function(){ if(!isVisible_toggle_box){ isVisible_toggle_box=true; $(".toggle_box_content").slideDown(); $(".info_box").css("display","none"); } else{ isVisible_toggle_box=false; $(".toggle_box_content").slideUp(); $(".info_box").css("display","table"); } }); }); if(contest_state==0){ $.post("/activity/MainActivity_2/contest_comp/", { contest_state : contest_state }, function(response){ $("div[comp_prop='contest_comp']").html(response); }); } else if(contest_state==1){ $.post("/activity/MainActivity_2/contest_comp/", { contest_state : contest_state }, function(response){ $("div[comp_prop='contest_comp']").html(response); }); } $.post("/actionsheet/getstamp_sheet/", {}, function(response){ $("div[comp_prop='stamp_sheet_get']").html(response); }); $.post("/actionsheet/getprize_sheet/", {}, function(response){ $("div[comp_prop='prize_sheet_get']").html(response); }); $.post("/board/comment_comp/", {}, function(response){ $("div[comp_prop='comment']").html(response); }); // $.post("/message/celMessage_comp/", {}, function(response){ // $("div[comp_prop='cm_msg']").html(response); // }); // $.post("/magazine/magazine_comp/", { type : "v" }, function(response){ // $("div[comp_prop='magazine_comp']").html(response); // }); // $.post("/walk/summary_comp/", {}, function(response){ // $("div[comp_prop='summary']").html(response); // $(".summary_box .btn_info").each(function(idx){ // $(this).click(function(){ // $(".summary_box .content_box").hide(); // $(".summary_box .content_box:eq("+idx+")").fadeIn(); // }); // }); // }); var toolbar_flag = true; $(".customlink").on("click",function(){ if(toolbar_flag){ $(".toolbar1").css("top","-50px"); $(".toolbar2").css("top","0px"); toolbar_flag = false; }else{ $(".toolbar1").css("top","0px"); $(".toolbar2").css("top","50px"); toolbar_flag = true; } }); }); function temp_Mission(){ $.post("/actionsheet/setprize_sheet/", {}, function(response){ $("div[comp_prop='prize_sheet_set']").html(response); myApp.pickerModal('.picker-set-prize'); $("#set_prize").on("click",function(){ /*location.href = "/content/mission/"+obj.id;*/ }); }); } var cnt = 0; function temp_Move(){ var temp_rate = tracker.params.progress.step; var temp_stemp = tracker.params.pin.arr; tracker.drawPin(temp_rate+10,temp_stemp); cnt += 1000; $("#step_cnt").text(cnt); } </script><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Prize_model extends CI_Model{ function __construct(){ parent::__construct(); } //스탬프 정보 //위시 성공여부 및 획득 갯수 //혜택 //스탬프 획득방법 function getStampInfo(){ } //경품추천권 정보 //미션 성공여부 및 획득 갯수 //혜택 //경품 추첨권 획득방법 function getCardInfo(){ } /* * 조진근 * 20170327 * 경품 리스토 호출 */ function getPrizeList($contest_id = ""){ $this->db->select("경품_id, 경품명, 경품사진, 걷기대회_id, 경품수"); if($contest_id != ""){ $this->db->where("걷기대회_id", $contest_id); } $this->db->order_by("경품수"); $this->db->from("경품"); return $this->db->get()->result(); } /* * 조진근 * 20170327 * 기념품 리스토 호출 */ function getGiftList($contest_id = ""){ $this->db->select("기념품_id as 경품_id, 기념품명 as 경품명, 기념품사진 as 경품사진 , 걷기대회_id, 기념품수"); if($contest_id != "") $this->db->where("걷기대회_id", $contest_id); $this->db->order_by("기념품수"); $this->db->from("기념품"); return $this->db->get()->result(); } /* * 조진근 * 20170328 * 위시 수행상태를 가져옴 */ function getSpotState($user,$contest_id){ $this->db->select("A.위시_id as ID , A.위시명 as title", NULL); $this->db->select("case when B.위시_id is null then 0 else 1 end checkFlag",FALSE); $this->db->from("위시 as A"); $this->db->join("위시_스템프 as B", "A.위시_id = B.위시_id and B.사용자_id = '$user'", "LEFT OUTER", NULL); $this->db->where("A.걷기대회_id",$contest_id); return $this->db->get()->result(); } /* * 조진근 * 20170328 * 현재 이용자의 스탬프 완료갯수를 가져옴 */ function getCountSpot($user,$contest_id){ $this->db->select("COUNT(*) cnt", NULL); $this->db->from("위시 as A"); $this->db->join("위시_스템프 as B", "A.위시_id = B.위시_id and B.사용자_id = '$user'", "LEFT OUTER", NULL); $this->db->where("A.걷기대회_id",$contest_id); return $this->db->get()->row()->cnt; } /* * 조진근 * 20170328 * 마션 수행상태를 가져옴 */ function getMissionState($user,$contest_id){ $this->db->select("A.미션_id as ID, A.미션명 as title"); $this->db->select("case when B.미션_id is null then 0 else 1 end checkFlag",FALSE); $this->db->from("미션 as A"); $this->db->where("A.걷기대회_id",$contest_id); $this->db->join("미션_수행 as B", "A.미션_id = B.미션_id and B.사용자_id = '$user'","LEFT OUTER", NULL); return $this->db->get()->result(); } /* * 조진근 * 20170328 * 현재 이용자의 미션 완료갯수를 가져옴 * 현재 이용자가 얻은 경품의 갯수 */ function getCountMission($user,$contest_id){ $this->db->select("COUNT(*) cnt", NULL); $this->db->from("미션 as A"); $this->db->where("A.걷기대회_id",$contest_id); $this->db->join("미션_수행 as B", "A.미션_id = B.미션_id and B.사용자_id = '$user'","LEFT OUTER", NULL); return $this->db->get()->row()->cnt; } /* * 조진근 * 20170328 * 총 스탬프의 갯수와 성공한 스탬프 갯수를 표시 */ function getStampRate($user_id,$contest_id){ $sql = " select 총스탬프, 얻은스탬프, ROUND((얻은스탬프/총스탬프)*100) 원본비율, CONCAT(ROUND((얻은스탬프/총스탬프)*100),'%') 비율 from (select count(*) 총스탬프, (select count(*) from 위시 A JOIN 위시_스템프 B ON A.위시_id = B.위시_id AND A.걷기대회_id = '".$contest_id."' AND B.사용자_id ='".$user_id."' ) 얻은스탬프 from 위시 where 걷기대회_id = '".$contest_id."' ) c "; $query = $this->db->query($sql); return $query->result(); } /* * 이종호 * 20170329 * 트랙에 표출한 스탬프 정보 */ function getTrackStamp($contest_id){ $sql = " select a.*,b.목표걸음수 FROM focus_walk.위시 a, focus_walk.걷기대회 b where a.걷기대회_id = '".$contest_id."' and a.걷기대회_id = b.걷기대회_id order by a.위시기준; "; return $this->db->query( $sql )->result(); } /* * 이종호 * 20170329 * 사용자가 통과한 스탬프 정보 */ function getTrackCheckedStamp($user,$contest_id){ $sql = " select a.위시_id FROM focus_walk.위시 a, focus_walk.걷기대회 b, focus_walk.위시_스템프 c where a.걷기대회_id = '".$contest_id."' and a.걷기대회_id = b.걷기대회_id and c.사용자_id = '".$user."' and a.위시_id = c.위시_id order by a.위시기준; "; return $this->db->query( $sql )->result(); } /* * 정수영 * 20170403 * 사용자가 얻은 경품추첨권 개수 */ function getUserPrizeCount($user,$contest_id){ $sql= " select count(*) cnt from( select B.걷기대회_id as 미션_걷기대회_id, C.걷기대회_id as 핫스팟_걷기대회_id, A.분류 as 분류 from 경품추첨권 A left outer join 미션 B on A.분류_id = B.미션_id left outer join 핫스팟 C on A.분류_id = C.핫스팟_id where A.사용자_id = '".$user."' ) AA where AA.미션_걷기대회_id='".$contest_id."' or AA.핫스팟_걷기대회_id='".$contest_id."' "; return $this->db->query( $sql )->result(); } } ?> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Marquee extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('statistics_model'); } /* * 이종호 * 20170328 * Main_1 상단 컴포넌트 * 참가중인대회 */ function main_1_comp(){ $name = $this->session_common->getSession("user")['name']; $contest_id = $this->session_common->getSession("user")['contest_id']; $result = $this->statistics_model->main_1_marquee($contest_id); if(!$result){ $data["str"] = ""; } else{ $date_a = new DateTime(); $date_b = new DateTime($result->종료일시); $date_diff = date_diff($date_a, $date_b); $data["str"] = $name."님은 ".$result->제목."에 참가중입니다. (D-".$date_diff->days."일)"; } $this->load->view("marquee/main_1_comp",$data); } /* * 이종호 * 20170328 * Main_2 상단 컴포넌트 * 걸음수, 추천걸음 */ function main_2_comp(){ $user = $this->session_common->getSession("user")['user_id']; $name = $this->session_common->getSession("user")['name']; $contest_id = $this->session_common->getSession("user")['contest_id']; $result = $this->statistics_model->main_2_marquee($user, $contest_id); // var_dump($result); if(!$result){ $data["str"] = ""; } else{ $flag_step = $result["대회"] -> 목표걸음수; $date = $result["대회"] -> 종료일시; $contest = $result["통계"]; $date_a = new DateTime(); $date_b = new DateTime($date); $date_diff = date_diff($date_a, $date_b)->days; $total_step = 0; foreach ($contest as $val) { $total_step += $val->걸음수; } if(count($contest)==0){ $data["str"] = $name."님은 걸은 이력이 없습니다."; } else{ if(count($contest)==0) $rate = 0; else $rate = ($total_step/$flag_step) *100; // $rate = ( ($total_step/count($contest)) / (($flag_step - $total_step)/$date_diff) ) * 100; $data["str"] = $name."님은 평균걸음보다 ".(int)$rate."% 많이 걸어야 FINAL에 도착하실 수 있습니다. 조금만 더 힘내세요!"; } } $this->load->view("marquee/main_2_comp",$data); } }<file_sep><style> .tenIncrease, .hunIncrease, .thouIncrease{ border : 1px solid black; float:left; text-align: center; cursor:pointer; width:20%; } .userInfo_box , tr, th, td{ border:1px solid black; } </style> <table class="userInfo_box"> <tr> <th> 사용자 아이디 </th> <th> 사용자 이름 </th> <th> 총 걸음수 </th> <th style="width:200px"> 걸음수 증가</th> </tr> <?php foreach($userInfos as $userInfo) { ?> <tr> <td class="user_id"><?= $userInfo-> 사용자_id ?> </td> <td class="name"><?= $userInfo -> 이름 ?> </td> <td class="walkcount"><?= $userInfo -> 총걸음수 ?> </td> <td class="incButton" style="width:200px" value="<?= $userInfo-> 사용자_id ?>"> <div class="tenIncrease" style="margin-left:15px" value="10"> +10 </div> <div class="hunIncrease" style="margin-left:15px" value="100"> +100 </div> <div class="thouIncrease" style="margin-left:15px; width:50px" value="1000"> +1000 </div> </td> </tr> <?php } ?> </table> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(".tenIncrease").click(function(){ var user_id = $(this).parent().attr("value"); var count = $(this).attr("value"); increaseCount(user_id, count); }); $(".hunIncrease").click(function(){ var user_id = $(this).parent().attr("value"); var count = $(this).attr("value"); increaseCount(user_id, count); }); $(".thouIncrease").click(function(){ var user_id = $(this).parent().attr("value"); var count = $(this).attr("value"); increaseCount(user_id, count); }); function increaseCount(user_id, count){ $.ajax({ type:"POST", url: "/test/increaseCount", dataType:"json", data:{ "user_id" : user_id, "count" : count }, success: function(result){ location.href="/test/getUsersInfo" },error: function(result){ } }); } </script><file_sep><?php class Walk extends CI_Controller { function __construct() { parent::__construct (); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model ( 'walk_model' ); } /* * index * 정수영 * 20170314 * walk_model data load * 초기화면 */ function index() { $this->load->view ( "activity/header_p" ); $this->load->view ( "walk/walk_tab" ); $this->load->view ( "activity/footer" ); } /* * getWalkList * 정수영 * 20170315 * 원하는 태그(진행중, 진행예정, 종료된대회)클릭시 원하는 데이터 로드 * 초기화면 */ function getWalkList($index = "") { $this->load->view ( "activity/header_p" ); $user_id = $this->session_common->getSession("user")['user_id']; switch ($index) { case "close" : $data ["walkLists"] = $this->walk_model->getOutdateEvent($user_id); // 종료된 대회 객체 break; case "predate" : $data ["walkLists"] = $this->walk_model->getPredateEvent($user_id); // 예정 대회 객체 break; default : $data ["walkLists"] = $this->walk_model->getLiveEvent($user_id); // 진행중인 대회 객체 break; } $this->load->view ( "walk/walk_list", $data ); $this->load->view ( "activity/footer" ); } /* * getSelectedWalkEvent * 정수영 * 20170319 * 참가신청 버튼 클릭후, 대회 상세페이지로 이동 * 대회 상세정보, 대회기념품정보, 경품정보 객체를 리턴 */ function getSelectedWalkEvent($event_id) { $this->load->view ( "activity/header_p" ); $data ["selectEvent"] = $this->walk_model->getInfoEvent( $event_id ); $data ["alldata"] = $this->walk_model->getSelectedPageInfo($event_id); $this->load->view ( "walk/walk_view", $data ); $this->load->view ( "activity/footer" ); } /* * getApplyWalkEvent * 정수영 * 20170320 * 대회신청하기 버튼 클릭후, 대회 신청하기페이지로 이동 * 대회 상세정보 객체, 유저 정보 객체를 리턴 */ function applyWalkEvent($event_id, $user_id="") { $user_id = $this->session_common->getSession("user")['user_id']; $this->load->view ( "activity/header_p" ); $data ["selectEvent"] = $this->walk_model->getInfoEvent($event_id); $data ["selectUser"] = $this->walk_model->getUserInfo($user_id); $this->load->view ( "walk/apply_walk_event", $data ); $this->load->view ( "activity/footer" ); } /* * 조진근 * 20170320 * getWalkInfo * 대회정보 페이지로 이동 */ function summary_comp(){ $temp = $this->session_common->getSession("user"); $id = $temp["contest_id"]; $data["event"] = $this->walk_model->getWishEvent($id); $data["mementos"] = $this->walk_model->getWishMemento($id); $data["gifts"] = $this->walk_model->getWishGift($id); $this->load->view("walk/summary_comp",$data); } /* * 조진근 * 20170320 * getWishTrack * WISH TRACK 페이지로 이동 */ function getWishTrack(){ $temp = $this->session_common->getSession("user"); $user = $temp["user_id"]; $id = $temp["contest_id"]; $data["name"] = $this->walk_model->getUserName($user); $data["event"] = $this->walk_model->getWishEvent($id); $data["user"] = $this->walk_model->getWishEntry($id); $this->load->view ("activity/header_p"); $this->load->view("walk/walk_wish_track",$data); $this->load->view ("activity/footer"); } /* * 정수영 * 20170323 * toggle_comp * 메인페이지 상단토글에 data load */ function toggle_comp(){ $user_id = $this->session_common->getSession("user")['user_id']; //user_id $event_id = $this->session_common->getSession("user")['contest_id']; //참여중 대회 $data['user_info'] = $this->session_common->getSession("user"); //사용자정보 $data["current_event"] = $this->walk_model->getToggleInfo($event_id); //진행중 대회 정보 $data["alldata"] = $this->walk_model-> getCereMony($user_id); $now = new DateTime(date("Y-m-d")); //현재 --> 현재도 월/일 만 $endday = new DateTime($data['alldata']->종료일시); //종료일 $date_diff_day = date_diff($now, $endday)->days; //차이 D-day $data['date_diff_day'] = $date_diff_day; $data['flag'] = 0; //1->대회진행중, 0->대회종료 $contest_state = $this->input->post('contest_state'); if($contest_state=='1'){ //대회 진행중 $data['flag']=1; } if($data['alldata']->소요일<=0){ $data["per_day_walking"] = number_format($data['alldata']->누적걸음수); //일평균걸음수 }else{ $data["per_day_walking"] = number_format(round($data['alldata']->누적걸음수 / $data['alldata']->소요일, 2)); //일평균걸음수 } if($data['alldata']->목표걸음<=0){ $data["complete_percent"]= '100%'; }else{ $data["complete_percent"] = round($data['alldata']->누적걸음수 * 100 / $data['alldata']->목표걸음, 2); //진행률 } if($date_diff_day<=0){ $data["recommand_per_walking"] = number_format($data['alldata']->남은걸음수); }else{ $data["recommand_per_walking"] = number_format(round($data['alldata']->남은걸음수 /$date_diff_day, 2)); //일평균 추천걸음수 } $data['alldata']->남은걸음수 = number_format($data['alldata']->남은걸음수); $data['alldata']->누적걸음수 = number_format($data['alldata']->누적걸음수); $this->load->view ("walk/toggle_comp", $data); } /* * 정수영 * 20170324 * ceremony_popup * 목표 걸음수 완료시 팝업창띄우기 */ function ceremony_popup(){ $user_id = $this->session_common->getSession("user")['user_id']; $this->load->view ("activity/header_p"); $data['middle_view'] = $this->walk_model->getCereMony($user_id); $data['preserveEvent'] = $this->walk_model->getPreserveEvent($user_id); $data['count'] = count($data['preserveEvent']); if( $this->walk_model->getCheckInStatus($user_id)->체크인수행여부 == "0"){ $data['checkin'] = "실패"; }else{ $data['checkin'] = "성공"; } $this->load->view("walk/ceremony_popup",$data); } /* * 정수영 * 20170327 * posterlist_comp * posterlist view 안에 data load 하기 (사용자가 참가중인 이벤트 받아와야함.) */ function posterlist_comp(){ $user_id = $this->session_common->getSession("user")['user_id']; $event_id = $this->session_common->getSession("user")['contest_id']; $data ["walkLists"] = $this->walk_model->getLiveEvent($user_id); // 진행중인 대회 객체 $data ["diffdate"] = $this->walk_model->getDdaySday($event_id); $this->load->view("walk/posterlist_comp", $data ); $this->load->view ("activity/footer"); } /* * 정수영 * 20170327 * userEventState * 한 유저의 특정 이벤트에 대한 상태 페이지 */ function userEventState(){ $user_id = $this->session_common->getSession("user")['user_id']; $this->load->view ("activity/header_p"); $data['alldata'] = $this->walk_model->getCereMony($user_id); //필요한 데이터 load $now = new DateTime(); //현재 $prizeday = new DateTime($data['alldata']->추첨일); //추첨일 $date_diff_day = date_diff($now, $prizeday)->days; //차이 D-day $date_diff_time = date_diff($now, $prizeday)->format('%h:%i:%s'); //echo ($date_diff_time); $data['diff_day'] = $date_diff_day; $data['diff_time'] = $date_diff_time; if($now < $prizeday){ }else{ $data['diff_day'] = 0; } $this->load->view("walk/user_event", $data); $this->load->view ("activity/footer"); } /* * 정수영 * 20170329 * condition * walk_condition 화면 load */ function condition(){ $user_id = $this->session_common->getSession("user")['user_id']; $event_id = $this->session_common->getSession("user")['contest_id']; $user_name = $this->session_common->getSession("user")['name']; $data['alldata'] = $this->walk_model->getWalkCondition($user_id); $data['user_id'] = $user_id; $data['user_name'] = $user_name; $start = new DateTime(str_replace('.','-',$data['alldata']->시작일시)); //대회시작일 $end = new DateTime(str_replace('.','-',$data['alldata']->종료일시)); //대회마지막일 $user_part = new DateTime(str_replace('.','-',$data['alldata']->유저참가신청일시)); //user참가신청일시 $now = new DateTime(date("Y-m-d")); //현재 --> 현재도 월/일 만 $data['user_prt_day'] = date_diff($now, $user_part)->days; //user가 참가기간 -> 참가일로부터 지금까지 (대회가 안끝났을때) $data['end_state']=0; if(date_diff($end, $now)->days < 0){ //대회가 끝남 $data['user_prt_day'] = date_diff($now, $end)->days; $data['end_state']=1; } $data['date_diff_day'] = date_diff($start, $end)->days; //시작일, 끝일 차이 $this->load->view("activity/header_p"); $this->load->view("walk/walk_condition",$data); $this->load->view("activity/footer"); } /* * 정수영 * 20170329 * prizeConfirm * 경품화면을 보여줌 */ function prizeConfirm(){ $user_id = $this->session_common->getSession("user")['user_id']; $user_name = $this->session_common->getSession("user")['name']; $this->load->view("activity/header_p"); $this->load->view("walk/prize_confirm"); $this->load->view("activity/footer"); } } ?> <file_sep><style> body{background:#000;} .login_view{ width:100%; height:100%; } .login_title { padding: 30px; padding-bottom:5%; font-size:20px; text-align:center; } .login_content{ padding:10%; padding-bottom:15px; } .login_view .errMessage{ color:red; height:30px; font-size:15px; font-weight:bold; } .login_view .login_bt{ border : 1px; padding-left : 5%;padding-right:5%; color:white; cursor:pointer; width:100%; padding:0px; margin:40px auto; position:relative; } .funcs{ padding:5%; color:#979797; } .funcs #register{ display:inline; border-right:1px solid #979797; padding-right:5px; } .funcs #findId{ display:inline; border-right:1px solid #979797; padding-left:5px; } .funcs #findPw{ display:inline; padding-left:5px; } </style> <div class="splash" style="height:100vh;background:#000000;transition:1s;display:table;width:100%;"> <span style="font-size:40px;font-weight:bold;color:white;display:table-cell;vertical-align:middle;text-align:center;">WISH WALK</span> </div> <div class="login_view" style="opacity:0;transition:1s;background:#000;color:white;"> <div class="login_title"> 로그인 하기 </div> <div class="login_content"> <form action="/index" class="logininfo" method="post"> <input type="text" id="user_id" placeholder="아이디" style="border:none; border-bottom: 1px solid #979797; margin-bottom:5%; padding-bottom:10px; width:100%"> <input type="password" id="password" placeholder="<PASSWORD>" style="width:100%; border:none; border-bottom:1px solid #9<PASSWORD>; padding-bottom:10px;"> </form> </div> <div class="errMessage" align="center"> </div> <div class="login_bt" align="center" style=""> <div style="background:#60b9f0; margin:0px 10%; height:100%; position:relative; padding:20px 0px;"> 로그인 </div> </div> <div class="funcs" align="center"> <div id="register"> 회원가입 </div> <div id="findId"> 아이디 찾기 </div> <div id="findPw"> 비밀번호 찾기 </div> </div> </div> <script> $(document).ready(function() { $(".splash").find("span").animate({ opacity: 0, }, 500, function() { $(".splash").find("span").animate({ opacity: 1, }, 500, function() { $(".splash").css("height","30vh"); setTimeout(function () { $(".login_view").css("opacity",1); start(); }, 1000); }); }); }); function start(){ $('.login_bt').click(function() { $user_id = $("#user_id").val(); $.ajax({ type:"POST", url: "/user/loginCheck", dataType:"json", data:{ "user_id" : $("#user_id").val(), "password" : $("#password").val() }, success: function(result){ <?php // result가 1이면 로그인이 성공한 경우 , result가 0이면 실패?> if(result==1){ <?php if(ENVIRONMENT=="mig"||ENVIRONMENT=="stage"){ echo "location.href='/activity/MainActivity_1'"; } else{ echo "$('.logininfo').submit()"; }?> }else{ $("#user_id").val(""); $("#password").val(""); $('.errMessage').html("아이디 또는 비밀번호가 일치하지 않습니다"); } },error: function(result){ } }); }); $('#register').click(function() { location.href="/user/registerIndex"; }); $('#findId').click(function() { location.href="/user/findIdIndex"; }); $('#findPw').click(function() { location.href="/user/findPwIndex"; }); } </script><file_sep><div class="track_content" style="background:url(<?=IMG_PATH?>MainActivity_2/track_bg.png);background-size:cover;height:100%;"> <div style="background:rgba(0, 0, 0, 0.8);height:100%;padding:0px 10%;"> <div class="walk_box" style="color:white;font-size:12px;color:#ababab;padding-top:15px;"> <div style="position:relative;padding:10px 0px;"> <div style="font-size:25px;color:RGB(255,205,51)"><?=$event_info->완보여부?></div> </div> </div> <div style="color:white;font-size:12px;color:white;display:-webkit-box;padding-top:15px;line-height:3em;"> <div style="width:50%;"> <div style="font-size:20px;color:white;">기념품추첨대상</div> <div style="font-size:20px;color:RGB(255,205,51)"><?=$event_info->미션완료율=="0%" ? "NO":"YES"?></div> <div style="font-size:25px;color:white;"><?=$event_info->미션완료율?></div> </div> <div style="width:50%;"> <div style="font-size:20px;color:white;">경품품추첨대상</div> <div style="font-size:20px;color:RGB(255,205,51)"><?=$event_info->Wish완료율=="0%" ? "NO":"YES"?></div> <div style="font-size:25px;color:white;"><?=$event_info->Wish완료율?></div> </div> </div> <div style="font-size:12px;color:white;height:50px;padding-top:15px;"> <a href="/walk/prizeConfirm/" class="button button-raised button-fill color-pink external link" style="color:white;">당첨자 발표</a> </div> <div style="font-size:14px;color:white;padding-top:15px;text-align:left;line-height:1.5em;"> <ul> <li>완보번호 : <?=$user_info['user_id']?></li> <li>참가자명 : <?=$user_info['name']?></li> <li>참가기간 : <?=$event_info->참가기간?></li> <li>걸음수 : <?=$event_info->평균걸음수?></li> <li>스탬프 : <?=$event_info->Wish?>/<?=$event_info->Wish수?></li> <li>경품추첨권 : <?=$event_info->미션수행?>/<?=$event_info->미션수?></li> </ul> </div> <div style="font-size:12px;color:white;margin-top:15px;border-top:1px solid #929292;"> <a href="#" class="button button-raised color-gray" style="color:white;">세부내역더보기</a> </div> <div style="font-size:12px;color:white;margin-top:15px;max-height:50px;"> <div class="carousel-wrapper" style="color:white;"> <div class="owl-carousel owl-theme"> <div class="item"><img src="<?=IMG_PATH?>MainActivity_2/banner1.png" style="width:100%;"/></div> <div class="item" style="display:none"><img src="<?=IMG_PATH?>MainActivity_2/banner2.png" style="width:100%"/></div> <div class="item" style="display:none"><img src="<?=IMG_PATH?>MainActivity_2/banner3.png" style="width:100%"/></div> </div> </div> </div> </div> </div> <script> $(".owl-carousel").owlCarousel({ items:1, loop:false, nav:false, dots:true, margin:0, onInitialized :function(){ $(".owl-carousel .item").show(); } }); setTimeout(function(){ $(".track_content").css("height", $(window).height() - $('.track_content').offset().top); },100); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Test_model extends CI_Model{ function __construct(){ parent::__construct(); } /* * getUsersInfo * 이소희 * 20170323 * 사용자 정보들을 불러온다. */ function getUsersInfo(){ $this->db->select("SUM(사용자통계.걸음수) as 총걸음수, 사용자통계.사용자_id, 사용자.이름"); $this->db->from("사용자통계"); $this->db->join('사용자','사용자.사용자_id=사용자통계.사용자_id','',FALSE); $this->db->group_by("사용자통계.사용자_id"); $this->db->order_by("사용자.사용자_id asc"); return $this->db->get()->result(); } /* * dateCheck * 이소희 * 20170324 * 사용자 아이디에 해당하는 DB 행 유무 확인 */ function dateCheck($user_id){ $this->db->select("*"); $this->db->from("사용자통계"); $this->db->join('사용자','사용자.사용자_id=사용자통계.사용자_id','',FALSE); $this->db->where("날짜",date("Y-m-d")); $this->db->where("사용자통계.사용자_id",$user_id); return $this->db->get()->result(); } /* * insertCount * 이소희 * 20170324 * 오늘 날짜에 해당하는 내용 삽입 */ function insertCount($user_id,$count){ $this->db->set("사용자_id", $user_id); $this->db->set("날짜", date("Y-m-d")); $this->db->set("걸음수", $count); echo $this->db->insert("사용자통계"); } /* * increaseCount * 이소희 * 20170324 * 오늘날짜O -> 걸음수만 증가 */ function increaseCount($user_id,$count){ $this->db->set('걸음수','걸음수+'.$count,false); $this->db->where("날짜", date("Y-m-d")); $this->db->where("사용자_id",$user_id); echo $this->db->update('focus_walk.사용자통계'); } } ?><file_sep><style media="screen"> .hotspotList ul { padding-left: 0; list-style-type: none; } .hotspotList .header{ font-size: 16px; background-color: rgba(201, 201, 201, 0.8); padding : 3%; position: relative; margin-bottom: 1.5%; text-align: center; } .hotspotList .header p{ margin: 0; } .hotspotList .toMap{ padding : 2%; position: relative; background-color: rgb(119, 218, 254); text-align: center; margin-bottom: 1.5%; } .hotspotList .toMap p{ margin: 0; } .hotspotList .sub { font-weight: bold; color: white; background-color: rgba(50,92,135,0.8); display: inline-block; width: 100%; padding : 5px 0; } .hotspotList .gps{ border-radius: 5px; position: relative; text-align: center; float : right; background-color: rgba(119, 242, 146,0.7); width: 35%; padding: 1px; margin-bottom: 2.5%; } .article ul{ margin: 0; margin-bottom: 2.5%; width: 100%; } .hotspotList .gps p{ margin : 0; padding : 5px; font-size: 12px; } .hotspotList .list{ background-color: rgba(190,190,190,0.4); display: inline-table; width: 100%; margin-bottom: 2.5%; } .hotspotList .sub span{ padding: 5px; } .hotspotList .state{ font-size: 12px; padding : 5px; float: right; } .hotspotList .title{ font-size: 12px; padding : 5px; float: left; text-align: left; } .hotspotList .banner{ margin-top: -4px; margin-bottom:-4px; width: 100%; } .hotspotList .info{ font-size: 12px; padding: 1.5%; margin: 0; } </style> <div class="hotspotList"> <div class="container"> <div class="header"> <p>[캐논] 캐논 파노라마 걷기대회 핫스팟</p> </div> <div class="toMap" style="cursor: pointer;" onclick="location.href='<?=WEB_ROOT?>hotspot/hotspotListWithGoogleMap'"> <p>지도로 보기</p> </div> <div class="gps"> <p>GPS정보 수신 중</p> </div> <div class="article"> <ul> <?php foreach ($hotspots as $hotspot){ ?> <li class='list' value="<?=$hotspot->핫스팟_id?>"> <div class="sub"> <div class="title">Location : <?=$hotspot->제목 ?></div> <div class="state"> <?php if(!($hotspot->상태 == NULL)) { ?> <span style="color : rgb(11, 33, 56);"><?=$hotspot->코드명?></span> <?php } else if ($hotspot->종료시간 >= time()) { ?> <span style="color : azure;"> 참여가능 </span> <?php } else { ?> <span style="color : rgb(214,50,50);"> 종료됨 </span> <?php }?> </div> </div> <img class="banner" src="<?=경로_핫스팟.$hotspot->배너?>" alt=""> <p class="info">체크인 가능시간 | <?= $hotspot->체크인_종료시간?></p> <p class="info">상품 | <?=$hotspot->상품명?></p> </li> <?php } ?> </ul> </div> </div> </div> <script type="text/javascript"> $(".list").on("click",function(){ window.location.assign("<?=WEB_ROOT?>hotspot/hotspotView/"+$(this).attr("value")); })} </script> <file_sep><!DOCTYPE html> <html lang="ko" class=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,target-densitydpi=medium-dpi"/> <!-- 공통 스타일 --> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.colors.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7-icons.css"> <link rel="stylesheet" href="/mnt/walk/common/css/common.css?t=1"> <title>참가현황 통계</title> <style> .myStaticPage_wrapper .menu .active{ font-weight:bold !important; } .myStaticPage{display:none;} .myStaticPage_1 .mythumb {margin:10px auto;width:80px;height:80px;overflow:hidden;display:block;border-radius:80px;text-align:center;} .myStaticPage_1 .mythumb img{width:80px;height:80px;} .myStaticPage_1 .myName {font-size:20px;text-align:center;} .clear{clear:both;} .history table{border-collapse: collapse;} .history table td{border:1px solid #cdcdcd;line-height:15px;width:16.6666%;padding:5px 0px;} .step_down { padding-left:10px; color:#005de4; background: url(http://img.focus.kr/mnt/webdata/SERVICE/cdn/b2c/images/stockinfo/ico_down1.gif) no-repeat 0 5px; } .step_up { padding-left:10px; color:#fb261a; background: url(http://img.focus.kr/mnt/webdata/SERVICE/cdn/b2c/images/stockinfo/ico_up1.gif) no-repeat 0 5px; } .myBanner{font-weight:normal;margin:5px;background-color:RGB(91,155,213);color:white;font-size:18px;padding:10px 0px;text-align:center;} .detail_info table{border-collapse: collapse;width:100%;font-size:12px;color:#ababab;} .detail_info table td{border:1px solid white;line-height:15px;width:50%;padding:5px 0px;text-align:left;} </style> </head> <body style="overflow:auto;"> <div class="myStaticPage_wrapper"> <div class="navbar" style="background:#ababab;height:40px;line-height:40px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="center" > ← 참가현황 통계 </div> <div class="right"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> </div> </div> <div class="menu" style="height:25px;line-height:25px;border-bottom:1px solid #cdcdcd;"> <div style="height:20px;line-height:20px;margin-top:10px;"> <div class="tab active" style="margin-left:-1px;float:left;width:50%;text-align:center;">나의 대회 참여 통계</div> <div class="tab" style="border-left:1px solid #cdcdcd;float:left;width:50%;text-align:center;">대회 참가 현황 통계</div> </div> </div> <div class="clear"></div> <?php $for_i=0; $마지막걸은날짜; $남은걸음수; $기준날짜; $누적걸음수; $진행률; $걷기시작일="-"; $테이블데이터="<tr> <td>날짜</td> <td>걸음 수</td> <td><div>누적</div><div>걸음 수</div></td> <td><div>남은</div><div>걸음 수</div></td> <td>진행률</td> <td><div>전일</div><div>대비</div><div>증감</div></td> "; foreach($myTable_Step_Data as $item){ $updown=""; if($item->증감<0) $updown='<span class="step_down">'.abs($item->증감)."</span>"; else{ $updown='<span class="step_up">'.abs($item->증감)."</span>"; } if($for_i==0){ $updown="-"; $걷기시작일= @$item->원본날짜; } $테이블데이터 .='<tr> <td>'.$item->날짜.'</td> <td>'.$item->걸음수.'</td> <td>'.$item->누적걸음수.'</td> <td>'.$item->남은걸음수.'</td> <td>'.$item->진행률.'</td> <td>'.$updown.'</td> </tr>'; $남은걸음수 = $item->원본남은걸음수; $누적걸음수 = $item->누적걸음수; $진행률 = $item->원본진행률; $기준날짜 = $item->원본날짜; $마지막걸은날짜 = $item->무형식원본날짜; $for_i++; } ?> <div class="myStaticPage_1 myStaticPage"> <div class="myInfo"> <div class="mythumb"><img src="<?=$myInfo["USER_PIC"]?>" alt=""/></div> <div class="myName"><?=$myInfo["USER_NAME"]?></div> <div class="myDate" style="margin-top:10px;"> <div style="margin-left:-1px;float:left;width:50%;"> <div style="margin-left:10%;text-align:center;border-bottom:1px solid #555;padding-bottom:6px;"> <div>참가신청일</div> <div style="color:RGB(42,189,242);"> <?php if(@$myTable_TournamentStart[0] ===NULL){ echo "-"; } else{ echo @$myTable_TournamentStart[0]->참가신청일시; } ?></div> </div> </div> <div style="float:left;width:50%;"> <div style="margin-right:10%;border-left:1px solid #555;text-align:center;border-bottom:1px solid #555;padding-bottom:6px;"> <div>걷기시작일</div> <div style="color:RGB(42,189,242);"><?=$걷기시작일?></div> </div> </div> </div> </div> <div class="clear"></div> <div class="history" style="text-align:center;margin:10px 5px;"> <table style="table-layout:fixed;width:100%;"> <?=$테이블데이터?> </table> <div style="margin-top:15px"> <?php $대회종료일시 = $myTable_TournamentInfo[0]->종료일시; //echo $대회종료일시; //echo "<br>"; //echo $마지막걸은날짜; $시작일 = @new DateTime(@$마지막걸은날짜===NULL?$대회종료일시:$마지막걸은날짜); // 20120101 같은 포맷도 잘됨 $종료일 = @new DateTime($대회종료일시); // $차이 는 DateInterval 객체. var_dump() 찍어보면 대충 감이 옴. $남은일자 = date_diff($시작일, $종료일); echo "대회 종료일까지 <span style='color:red;font-weight:bold;font-size:16px;'>". $남은일자->days."</span>일 남았습니다."; echo "<br>"; echo "하루에 <span style='color:blue;font-weight:bold;font-size:16px;'>".@number_format(ceil($남은걸음수/$남은일자->days),0)."</span>을 걸으시면 완주가 예상됩니다."; ?> </div> <div> <div style="margin:10px;font-size:12px;text-align:left;"> <div> * 금일 이후의 수치는 참가자님의 평균 걸음 데이터를 분석하여 대회 종료일까지의 일일 추천 걸음수를 안내해 드립니다. </div> <div style="margin-top:5px"> * 일일 데이터는 전일 자정~금일 자정까지의 걸음데이터로 반영됩니다. </div> </div> </div> </div> </div> <div class="myStaticPage_2 myStaticPage"> <div > <div class="myBanner"><?=$myTable_TournamentInfo[0]->제목?></div> </div> <?php //echo $남은걸음수 ; //echo $기준날짜 ; ?> <div style="text-align:center;padding:10px 0px;"> <div style="width:33.333333%;float:left"> <div>목표걸음 수</div> <div style="color:#ababab;font-size:20px;"><?=number_format($myTable_TournamentInfo[0]->목표걸음수)?><span class="unit" style="font-size:12px">보</span></div> </div> <div style="width:33.333333%;float:left"> <div>누적걸음 수</div> <div style="color:#ababab;font-size:20px;"><?=@$누적걸음수===NULL?'- ':$누적걸음수?><span class="unit" style="font-size:12px">보</span></div> </div> <div style="width:33.333333%;float:left"> <div>진행률</div> <div style="color:#ababab;font-size:20px;"><?=@$진행률===NULL?'- ':$진행률?><span class="unit" style="font-size:12px">%</span></div> </div> </div> <div class="clear"></div> <div style="border-top:1px solid #ababab;margin-top:10px;"> <div class="detail_info" style="margin-top:15px;margin:10px 8%;"> <table> <tr> <td style="font-size:16px">참가인원</td> <td style="text-align:right;font-size:16px"><?=number_format($myTable_TournamentInfo[0]->참가자수)?>명</td> </tr> <?php $spot_data=""; $total_stamp=0; foreach($myTable_Stamp_Data as $item){ $spot_data .= '<tr><td >- '.$item->위시제목.'</td><td style="text-align:center;">'.$item->위시성공여부.'</td></tr>'; if($item->위시성공여부 ==="성공") $total_stamp++; } ?> <tr><td style="font-size:16px">획득한 스탬프</td><td style="text-align:right;font-size:16px"><?=$total_stamp?>개</td></tr> <?=$spot_data?> <?php $total_card=0; foreach($myTable_Card_Data as $item){ if($item->미션성공여부 ==="성공") $total_card++; } ?> <tr><td style="font-size:16px">획득한 경품추천권</td><td style="text-align:right">11112개</td></tr> <tr><td>-미션</td><td style="text-align:center"><?=$total_card?>개</td></tr> <tr><td>-체크인 프로모션</td><td style="text-align:center">111110개</td></tr> </table> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js?timestamp=201512210800"></script> <script> $(document).ready(function(){ $(".myStaticPage_1").show(); $(".menu .tab").each(function(idx){ $(this).click(function(){ $(".menu .tab").removeClass("active"); $(this).addClass("active"); $(".myStaticPage").hide(); $(".myStaticPage_"+(idx+1)).fadeIn(); }); }); }); </script> </body> </html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Menu extends CI_Controller { function __construct(){ parent::__construct(); } function _header(){ $this->load->view('activity/header'); } function _header_no(){ $this->load->view('activity/header_no'); } function _header_p(){ $this->load->view('activity/header_p'); } function _footer(){ $this->load->view('activity/footer'); } function _footer_no(){ $this->load->view('activity/footer_no'); } } ?> <file_sep><!DOCTYPE html> <html lang="ko" class=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,target-densitydpi=medium-dpi"/> <!-- 공통 스타일 --> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.colors.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7-icons.css"> <link rel="stylesheet" href="/mnt/walk/common/css/common.css?t=1"> <title>내가 참여한 대회</title> <style> .myGame_wrapper .menu .active{ font-weight:bold !important; } .clear{clear:both;} .info_content table td, .item_bottom table td{width:50%;font-size:12px;} .detail_box table{width:100%;margin-top:20px;} .detail_box table td:nth-child(odd){text-align:left;width:60%;} .detail_box table td:nth-child(even){text-align:center;width:40%;} .item_bottom table td{text-align:left;padding-left:10px;color:RGB(141,117,42);font-size:12px;} .myGame{display:none;} .myGame .color_prize{color:RGB(0,176,240);text-decoration:underline;} .myGame .color_card{color:RGB(84,130,53);text-decoration:underline;} .myGame .pic_box:after{content:"";clear:both;display:block;} .color_ing{color:green;} .color_success{color:blue;} .color_fail{color:red;} .i_tit{ text-overflow:ellipsis; white-space:nowrap; word-wrap:normal; width:100%; overflow:hidden; } .i_status{position:absolute;right:20px;bottom:0px;font-size:12px;} .myGame_1 .list_box .item{margin-top:5px;} .myGame_2 .list_box .item{margin-top:5px;} .myGame_2 .item_bottom table{width:calc(100% - 70px);} .myGame_2 .item_bottom table td{width:50%;font-size:12px;} </style> </head> <body style="overflow:auto;"> <div class="myGame_wrapper"> <div class="navbar" style="background:#ababab;height:40px;line-height:40px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="center" > ← 내가 참여한 대회 </div> <div class="right"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> </div> </div> <div class="menu" style="border-bottom:1px solid #cdcdcd;margin-top:10px;"> <div style="height:20px;line-height:20px;border-top:1px solid #cdcdcd;padding:5px 0px;"> <div class="tab active" style="margin-left:-1px;float:left;width:33.333%;text-align:center;">참가 대회</div> <div class="tab" style="border-left:1px solid #cdcdcd;float:left;width:33.3333%;text-align:center;">찜대회</div> <div class="tab" style="border-left:1px solid #cdcdcd;margin-left:-1px;float:left;width:33.333%;text-align:center;">완보증</div> </div> </div> <div class="clear"></div> <div class="myGame_1 myGame"> <div class="list_box"> <div style="margin:10px">총 6개의 대회에 참가하셨습니다.</div> <div style="margin-top:10px;"> <div class="item"> <div style="position:relative;overflow:hidden;"> <div style="position:absolute;left:5px;top:0px"><img src="" style="width:80px;height:80px"/></div> <div style="margin-left:100px;min-height:81px;margin-top:5px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> <div class="i_status color_ing">진행중</div> </div> </div> </div> </div> <div class="item_bottom" style="background-color:#cdcdcd;"> <table> <tr><td>1,256명</td><td>1000개 (70% 이하)</td></tr> <tr><td>565명</td><td>20개(10% 이상)</td></tr> </table> </div> </div> <div class="item"> <div style="position:relative;overflow:hidden;"> <div style="position:absolute;left:5px;top:0px"><img src="" style="width:80px;height:80px"/></div> <div style="margin-left:100px;min-height:81px;margin-top:5px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> <div class="i_status color_success">완보성공</div> </div> </div> </div> </div> <div class="item_bottom" style="background-color:#cdcdcd;"> <table> <tr><td>1,256명</td><td>1000개 (70% 이하)</td></tr> <tr><td>565명</td><td>20개(10% 이상)</td></tr> </table> </div> </div> <div class="item"> <div style="position:relative;overflow:hidden;"> <div style="position:absolute;left:5px;top:0px"><img src="" style="width:80px;height:80px"/></div> <div style="margin-left:100px;min-height:81px;margin-top:5px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> <div class="i_status color_fail">완보실패</div> </div> </div> </div> </div> <div class="item_bottom" style="background-color:#cdcdcd;"> <table> <tr><td>1,256명</td><td>1000개 (70% 이하)</td></tr> <tr><td>565명</td><td>20개(10% 이상)</td></tr> </table> </div> </div> </div> </div> <div class="showInfo_box" style="display:none"> <div style="position:relative;overflow:hidden;margin-top:10px;padding-bottom:5px;border-bottom:1px solid #ababab;"> <div style="position:absolute;left:5px;top:0px"><img src="" style="width:80px;height:80px"/></div> <div style="margin-left:90px;min-height:76px;margin-top:5px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> </div> </div> </div> </div> <div class="detail_box" style="margin:20px"> <div style="text-align:center;font-size:20px;font-weight:bold;" class="color_success">완보성공</div> <table> <tr><td>총 걸음 수</td><td>50,000보</td></tr> <tr><td>일일 평균 걸음 수</td><td>4,500보</td></tr> </table> <table style="margin-top:20px"> <tr><td>총 소요시간</td><td>10일</td></tr> <tr><td>성공 미션 수</td><td>3개/4개</td></tr> <tr><td>체크인 성공여부</td><td>실패</td></tr> <tr><td>수령한 기념푸</td><td>4개</td></tr> <tr><td>총 참여인원</td><td>12,345명</td></tr> </table> <div class="btn_goStage" style="background-color:RGB(255,192,0);margin-top:20px;padding:5px 0px;text-align:center;font-weight:bold;"> 대회장 바로가기 </div> </div> </div> </div> <div class="myGame_2 myGame"> <div class="list_box"> <div style="margin:10px">총 2개의 대회를 찜하셨습니다.</div> <div style="margin-top:10px;"> <div class="item"> <div style="position:relative;overflow:hidden;"> <div style="position:absolute;left:5px;top:0px"><img src="" style="width:80px;height:80px"/></div> <div style="margin-left:100px;min-height:81px;margin-top:5px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> <div class="i_status color_ing">대회 종료 시 까지 D-2</div> </div> </div> </div> </div> <div class="item_bottom" style="background-color:#cdcdcd;position:relative;"> <table style="margin-right:50px"> <tr><td>1,256명</td><td>1000개 (70% 이하)</td></tr> <tr><td>565명</td><td>20개(10% 이상)</td></tr> </table> <div style="position:absolute;right:5px;bottom:7px;border-radius:5px;padding:5px 0px; background-color:RGB(255,192,0);text-align:center;width:45px;"> 삭제 </div> </div> </div> <div class="item"> <div style="position:relative;overflow:hidden;"> <div style="position:absolute;left:5px;top:0px"><img src="" style="width:80px;height:80px"/></div> <div style="margin-left:100px;min-height:81px;margin-top:5px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> <div class="i_status color_fail">종료</div> </div> </div> </div> </div> <div class="item_bottom" style="background-color:#cdcdcd;position:relative;"> <table style="margin-right:50px"> <tr><td>1,256명</td><td>1000개 (70% 이하)</td></tr> <tr><td>565명</td><td>20개(10% 이상)</td></tr> </table> <div style="position:absolute;right:5px;bottom:7px;border-radius:5px;padding:5px 0px; background-color:RGB(255,192,0);text-align:center;width:45px;"> 삭제 </div> </div> </div> </div> </div> </div> <div class="myGame_3 myGame"> <div class="list_box"> <div style="margin:10px">총 3개의 완보증이 있습니다.</div> <div style="margin-top:10px;border-top:1px solid #cdcdcd;"> <div class="item" style="border-bottom:1px solid #cdcdcd;padding-bottom:10px;"> <div style="position:relative;overflow:hidden;"> <div style="margin-left:15px;min-height:81px;margin-top:20px;font-size:12px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회11111111111111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> </div> </div> </div> <div class="show_certificate" style="position:absolute;right:10px;bottom:0px;border-radius:5px;padding:5px 0px; background-color:RGB(255,192,0);text-align:center;width:100px;"> 완보증보기 </div> </div> </div> <div class="item" style="border-bottom:1px solid #cdcdcd;padding-bottom:10px;"> <div style="position:relative;overflow:hidden;"> <div style="margin-left:15px;min-height:81px;margin-top:20px;font-size:12px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> </div> </div> </div> <div class="show_certificate" style="position:absolute;right:10px;bottom:0px;border-radius:5px;padding:5px 0px; background-color:RGB(255,192,0);text-align:center;width:100px;"> 완보증보기 </div> </div> </div> <div class="item" style="border-bottom:1px solid #cdcdcd;padding-bottom:10px;"> <div style="position:relative;overflow:hidden;"> <div style="margin-left:15px;min-height:81px;margin-top:20px;font-size:12px;"> <div> <div class="i_tit">제1회 CANON과 함께하는 파노라마 걷기대회111111111</div> <div class="i_day">YYYY.MM.DD ~ YYYY’.MM’.DD’</div> <div style="position:relative"> <div class="i_com">(주)캐논</div> </div> </div> </div> <div class="show_certificate" style="position:absolute;right:10px;bottom:0px;border-radius:5px;padding:5px 0px; background-color:RGB(255,192,0);text-align:center;width:100px;"> 완보증보기 </div> </div> </div> </div> </div> </div> </div> <?php //완보증 ?> <div class="popup_box" style="z-index:99999;width:100%;height:100%;position:fixed;left:0px;top:0px;display:none;"> <div style="position:absolute;left:0px;top:0px;width:100%;height:100%;background-color:black;opacity:0.7;"></div> <div style="position:absolute;left:0;top:0;right:0;bottom:0;margin:auto; width:90%;height:90%;background-color:white; max-width:320px;max-height:400px; border:1px solid #cdcdcd;border-radius:10px; "> <div style="position:relative;height:100%;"> <div style="position:relative;font-size:18px;text-align:center;border-bottom:1px solid #cdcdcd;line-height:40px;height:40px;"> 완보증 <div id="pop_close" style="position:absolute;bottom:0px;right:10px;">X</div> </div> <div style="width:100%;height:calc(100% - 80px);overflow:auto;"> <div class="i_box certificate"> <img src="/mnt/walk/certificate/test.png" style="width:100%;height:100%;"/> </div> <div class="i_box email" style="text-align:center;margin-top:50px;"> <div>완보증을 수령할 이메일을 입력해주세요.</div> <div style="margin:30px 20px"><input type="text" style="width:100%"/></div> <div style="font-size:12px;width:220px;margin:30px auto;">완보증 이메일 발송은 1회로 제한하며 최대 1일이상 소요될 수 있습니다.</div> </div> </div> <div id="send_mail" style="border-radius:0px 0px 10px 10px;width:100%;position:absolute;left:0px;bottom:0px;background-color:RGB(255,192,0);text-align:center;padding:8px 0px;font-weight:bold;"> 이메일 완보증 신청하기 </div> <div id="send_ok" style="display:none;border-radius:0px 0px 10px 10px;width:100%;position:absolute;left:0px;bottom:0px;background-color:RGB(255,192,0);text-align:center;padding:8px 0px;font-weight:bold;"> 확인 </div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js?timestamp=201512210800"></script> <script> $(document).ready(function(){ $(".myGame_1").show(); $(".myGame_1 .list_box .item").each(function(){ $(this).click(function(){ $(".myGame_1 .list_box").hide(); $(".myGame_1 .showInfo_box").show(); }); }); $(".menu .tab").each(function(idx){ $(this).click(function(){ $(".menu .tab").removeClass("active"); $(this).addClass("active"); $(".myGame").hide(); $(".myGame_"+(idx+1)).fadeIn(); $(".myGame_1 .list_box").show(); $(".myGame_1 .showInfo_box").hide(); $(".myGame_2 .list_box").show(); $(".myGame_2 .showInfo_box").hide(); }); }); $(".show_certificate").click(function(){ $(".popup_box").show(); $(".popup_box #send_mail").show(); $(".popup_box #send_ok").hide(); $(".popup_box .i_box").hide(); $(".popup_box .certificate").show(); <?php //이메일로 완보증 보내기 ?> $("#send_mail").click(function(){ $(".popup_box .i_box").hide(); $(".popup_box .email").show(); $(".popup_box #send_mail").hide(); $(".popup_box #send_ok").show(); $(".popup_box #send_ok").click(function(){ $(".popup_box").hide(); alert("이메일로 완보증이 전송되었습니다"); }); }); }); $("#pop_close").click(function(){ $(".popup_box").hide(); }); }); </script> </body> </html><file_sep><style media="screen"> .walkWishTrack .container{ background-color: rgb(51, 63, 80); width: 100%; padding-bottom: 5px; } .walkWishTrack .article{ padding: 5px; position: relative; color: white; text-align: center; } .walkWishTrack #greeting { margin: 5px auto; width: 60%; font-size: 10px; } .walkWishTrack #dDay{ margin: 2.5%; padding: 10px auto; } .walkWishTrack .info{ margin-bottom: 10px; position:relative; height: auto; width: 100%; } .walkWishTrack .info p{ margin-top: 5px; margin-bottom: 5px; padding-left: 5px; } .walkWishTrack .info sup{ padding-left: 5px; font-size: 9px; color: rgb(132 , 128, 134); } .walkWishTrack .left{ padding-top: 5px; border: 1px solid rgb(89, 89, 89); float: left; text-align: left; width: 45%; margin-left: 3%; margin-right: 1%; min-height: 110px; font-size: 12px; margin-bottom: 1px } .walkWishTrack .right{ padding-top: 5px; border: 1px solid rgb(89, 89, 89); display: inline-block; text-align: left; width: 45%; margin-left: 1%; margin-right: 3%; min-height: 110px; font-size: 12px; } .walkWishTrack #bottom { color: rgb(89, 89, 89); font-size: 12px; } .walkWishTrack .footer{ position: relative; width: 100%; } .walkWishTrack .footer p{ background-color: rgb(31, 78, 121); width: 80%; padding-top: 10px; padding-bottom: 10px; margin: auto; font-size: 10px; } .walkWishTrack .#d-day{ background-color: rgb(31, 78, 121); width: 80%; padding-top: 10px; padding-bottom: 10px; margin: auto; font-size: 10px; } </style> <div class="walkWishTrack"> <div class="container"> <div class="article"> <p id="greeting"> <?=$event->제목?>가 <span id="going"> </span></p> <p id="d-day" value="<?=$event->dDay?>"> </p> <div class="info"> <div class="left"> <p id="entry" value="<?=$event->참가자수?>">참가자수 : <?=$event->참가자수?>명</p> <sup id = "entry_per" value="<?=$user->참가자수?>" ></sup> <p id="finish" value="<?=$event->완보자수?>">완보자수 : <?=$event->완보자수?>명</p> <sup id="finish_per" value="<?=$event->참가자수?>"></sup> </div> <div class="right"> <p>기념품수 : <?=$event->기념품수?>개</p> <sup>획득률 : 80%</sup> <p>경품수 : <?=$event->경품수?>개</p> <sup>획득률 : 10%</sup> </div> <br> <p id="bottom"> </p> </div> <div class="footer"> <p><?=$name->이름?>님의 참가현황</p> </div> </div> </div> </div> <script language="javascript"> $(document).ready(function() { $("#d-day").html("<span style='font-size: 13pt;'> D-day 계산중 </span>"); $("#entry_per").html("참가율 : 집계중") $("#finish_per").html("완보율 : 집계중%"); nowTime(); setViewTime = function (){ //함수로 만들어 준다. var date_end = $("#d-day").attr("value"); //현재날짜 var date_now = parseInt(new Date().getTime()/1000); //월에서 1 빼줘야 함 var diff = date_end - date_now; //날짜 빼기 var currSec = 1; // 밀리세컨 var currMin = 60 ; // 초 * 밀리세컨 var currHour = 60 * 60 ; // 분 * 초 * 밀리세컨 var currDay = 24 * 60 * 60 ; // 시 * 분 * 초 * 밀리세컨 var day = parseInt(diff/currDay); //d-day 일 var hour = parseInt(diff/currHour); //d-day 시 var min = parseInt(diff/currMin); //d-day 분 var sec = parseInt(diff/currSec); //d-day 초 var viewHour = hour-(day*24); var viewMin = min-(hour*60); var viewSec = sec-(min*60); var viewStr = day+"일 "+viewHour+"시 "+viewMin+"분 "+viewSec+"초"; if(diff > 0){ $("#going").html("진행중입니다"); $("#d-day").html("<span style='font-size: 13pt;'><b>"+viewStr+"</b></span>"); } else{ $("#going").html("종료되었습니다."); $("#d-day").html("<span style='font-size: 13pt;'><b>종료되었습니다.</b></span>"); clearInterval(leftTime); clearInterval(realTimeUser); } } getEntry = function(){ var entry = parseInt($("#entry").attr("value")); var totalEntry = parseInt($("#entry_per").attr("value")); var getEntryPercent = (entry/totalEntry)*100; var finish = parseInt($("#finish").attr("value")); var totalfinish = parseInt($("#finish_per").attr("value")); var getFinishPercent = (finish/totalfinish)*100; $("#entry_per").html("참가율 : "+getEntryPercent.toFixed(0)+"%") $("#finish_per").html("완보율 : "+getFinishPercent.toFixed(0)+"%"); } function nowTime(){ var nowDate = new Date(); var date = [nowDate.getFullYear(),nowDate.getMonth()+1,nowDate.getDate()]; $("#bottom").html("*"+date[0]+". "+date[1]+". "+date[2]+" 기준"); } var realTimeUser = setInterval('getEntry()',1000); var leftTime = setInterval('setViewTime()',1000); }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Test extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('test_model'); } /* * getUsersInfo * 이소희 * 20170323 * 사용자 정보들을 불러온다. */ function getUsersInfo(){ $data['userInfos'] = $this->test_model->getUsersInfo(); $this->load->view("activity/header_p"); $this->load->view("test/test_index",$data); $this->load->view("activity/footer"); } /* * increaseCount * 이소희 * 20170324 * 걸음 수 추가하기 */ function increaseCount(){ $user_id = trim($this->input->post('user_id')); $count = trim($this->input->post('count')); $data['result'] = $this->test_model->dateCheck($user_id); //현재 해당하는 날짜가 DB에 존재하지 않으면 insert if($data['result']==null){ $this->test_model->insertCount($user_id, $count); }else{ $this->test_model->increaseCount($user_id, $count); } } } ?><file_sep><style> .user{ width:100%; height:100%; } .userinfo, li{ padding : 10px; } .userInfo_title{ padding:15px; } .image{ background-color:lightgrey; width: 100%; height: 150px; } .pwChange, .adsChange, .imgChange{ border : 1px; background : lightskyblue; width:5%; padding : 5px; color:white; } .userDelete{ border : 1px solid black; text-align: center; cursor:pointer; width:50%; margin:0 auto; padding:5px; } .logout{ background:#60b9f0; margin:50px; margin-left:200px; width:40%; position:relative; padding:10px 0px; text-align:center; color:white; } .userInfo_title{ font-weight:bold; font-size:20px; } .image_thumb{ width: 100px; height: 100px; overflow: hidden; border-radius: 100px; clear:both; margin-top:30px; } </style> <div class="user"> <div class="image" align="center"> <div style="display:inline"><img class="image_thumb" src="<?=경로_사용자?><?=$info->사진 ?>" alt=""/></div> <div class="imgChange" style="cursor:pointer; display:inline"> 변경 </div> </div> <div class="userInfo"> <div class="userInfo_title"> 내 정보 </div> <ul> <li> 이름 : <?=$info-> 이름?> </li> <li> 성별 : <?=$info-> 성별?> </li> <li> 아이디 : <?=$info-> 사용자_id?> </li> <li> 비밀번호 : ******** <div class="pwChange" style="cursor:pointer; display:inline"> 변경 </div> <li> 이메일: <a href=""> <?=$info-> email?> </a> </li> <li> 주소 : <?=$info-> 주소?> <div class="adsChange" style="cursor:pointer; display:inline"> 변경 </div> </li> </ul> </div> <div class="userDelete" align="center"> 회원탈퇴 </div> <div class="logout"> 로그아웃 </div> </div> <script> $(document).ready(function() { $('.pwChange').click(function() { location.href="/user/indexPw/1" }); $('.adsChange').click(function() { location.href="/user/adsChangeIndex"; }); $('.userDelete').click(function() { location.href="/user/indexPw/2" }); $('.logout').click(function(){ alert("로그아웃 성공!!"); location.href="/user/logout" }); }); </script><file_sep><div class="gift_draw"> <div class="subtitle"> <p>이미지를 클릭하시면 <br> 당첨여부를 확인하실 수 있습니다.</p> <div class="gift_button">경품추첨 안내사항</div> </div> <div class="info"> <p>내가 획득한 경품 획득권 : 2개</p> </div> <div class="draw"> <ul> <?php foreach ($prizes as $prize) { ?> <li class="gift_list" id="<?=$prize->경품_id?>"> <img class="img" src="<?=WEB_ROOT.경로_경품.$prize->경품사진?>" alt=""> <p><?=$prize->경품명?></p> </li> <?php } ?> </ul> </div> </div> <file_sep><style> .findIdResult_view{ width:100%; height:100%; } .findIdResult_title{ font-size:20px; text-align:center; padding:30px; padding-bottom:5%; color:#979797 } .findIdResult_view .msg2{ padding:5%; padding-bottom:15%; text-align:center; color:#979797; } .findIdResult_content{ padding:5%; padding-bottom:15px; border:1px solid black; margin-bottom : 150px; } .findIdResult_view .login{ background:#60b9f0; margin:10px auto; width:70%; position:relative; padding:10px 0px; text-align:center; color:white; } .findIdResult_view .findpwBtn{ background:#60b9f0; margin :10px auto; width:70%; position:relative; padding:10px 0px; text-align:center; color:white; } </style> <div class="findIdResult_view"> <div class="findIdResult_title"> 아이디 찾기 </div> <div class="msg2"> 입력하신 정보와 일치하는 아이디 목록입니다. </br> 아이디를 확인한 후, 로그인 또는 비밀번호 찾기버튼을 눌러주세요. </div> <div class="findIdResult_content"> <div style="display:inline"> <?=$fid -> 사용자_id?> </div> <div style="float:right;"> 가입일 : <?=$fid -> 가입일?> </div> </div> <div class="login"> 로그인 </div> <div class="findpwBtn"> 비밀번호 찾기 </div> </div> <script> $(document).ready(function() { $('.login').click(function() { location.href="/user/loginIndex"; }); $('.findpwBtn').click(function() { location.href="/user/findPwIndex"; }); }); </script><file_sep><style media="screen"> .checkinPreview .container{ border : 1px solid black; width : 100%; background-color: gray; } .checkinPreview ul { padding: 5px 0; list-style-type: none; background-color: gray; position: relative; } .checkinPreview .header{ position: relative; background-color: gray; margin: 5px; border: 1px solid gray; padding-left: 1%; width: auto; } .checkinPreview .list{ width: 44%; height: 140px; display: inline-flex; margin: 2.5%; } .checkinPreview .article { position: relative; margin: 5px; height: auto; } .checkinPreview .title{ padding: 5px; color: white; width: 30%; } .checkinPreview #thumbnail{ width: 100%; height: 100%; position: relative; } .checkinPreview #more { color: black; padding-right: 5px; float: right; } </style> <div class="checkinPreview"> <div class="container"> <div class="header"> <span class="title">체크인</span> <?php if( $count > 2 ){ ?> <a id="more" href="<?=WEB_ROOT?>checkin/checkinTab"> 더보기</a> <?php } ?> </div> <div class="article"> <ul> <?php foreach ($events as $event){ ?> <li class='list' value="<?=$event->프로모션_id?>"> <img id="thumbnail" src="/mnt/walk/checkin/<?=$event->배너?>" > </li> <?php } ?> </ul> </div> </div> </div> <script type="text/javascript"> $(document).ready(function(){ $(".list").on("click",function(){ window.location.assign("<?=WEB_ROOT?>hotspot/hotspotList/"+$(this).attr("value")); }) }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Magazine_model extends CI_Model{ function __construct(){ parent::__construct(); } /* getMagazineListCount * 조진근 * 리스트 갯수 조회 */ function getMagazineListCount(){ $this->db->select("count(*) cnt"); $this->db->from("매거진"); $this->db->where("시작일시 <= now()",NULL,FALSE); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용여부","Y"); return $this->db->get()->row()->cnt; } /* * getMagazineList * 조진근 * 20170314 * 매거진 List 조회 * 최신순 정렬 * $count : record 개수 * $start : record 시작 */ function getMagazineList($count='',$start=''){ $this->db->select("*"); $this->db->from("매거진"); $this->db->where("시작일시 <= now()",NULL,FALSE); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용여부","Y"); $this->db->order_by("배포일시 DESC"); if($count !='' || $start !='') $this->db->limit($start,$count); return $this->db->get()->result(); } /* * 조진근 * 20170314 * ID값에 따른 문서조회 * $id : 페이지 링크에서 넘어오는 id값 */ function getIdMatch($id){ $this->db->select("*"); $this->db->from("매거진"); $this->db->where("시작일시 <= now()",NULL,FALSE); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용여부","Y"); $this->db->where("매거진_id",$id); return $this->db->get()->row(); } } <file_sep><div class="article"> <div class="get_item"> <p> <?=$user?>님의 스탬프 획득 갯수는 <?= $count ?>개입니다.</p> <table id="sticker"> <tr> <?php foreach ($spots as $spot): ?> <?php if ($spot->checkFlag == 1 ):?> <td><img src="<?=경로_경품?>stamp_yes.png" alt=""></td> <?php else: ?> <td><img src="<?=경로_경품?>stamp_no.png" alt=""></td> <?php endif ;?> <?php endforeach; ?> </tr> </table> </div> <div class="info"> <?php if($flag == "stamp"): ?> 대회장 내 스팟 도착시 콘텐츠를 확인하시면 스탬프를 획득 하실 수 있습니다. 획득한 스탬프는 기념품 추첨에 사용됩니다. <?php else:?> 대회 참여후 일정시간이 지나면 미션이 생성됩니다. 미션을 수행하시면 경품추첨권을 휙득하실 수 있습니다. 경품추첨권이 많아질수록 당첨확률은 높아집니다. <?php endif; ?> </div> <div class="success"> <ul> <?php foreach ($spots as $spot): ?> <?php if ($spot->checkFlag == 1 ):?> <li class="check on"><?=$spot->title?> <span class="right">완료</span></li> <?php else: ?> <li class="check"><?=$spot->title?> <span class="right">미완료</span></li> <?php endif ;?> <?php endforeach; ?> </ul> </div> </div> <file_sep><style media="screen"> .magazineView ul { padding-left: 1%; align-items: left; list-style-type: none; } .magazineView hr{ margin: 5px 5px; } .magazineView .container{ } .magazineView .header{ margin-bottom: 2.5%; position: relative; background-color: gray; border: 1px solid gray; padding-left: 1%; width: auto; } .magazineView .header p{ padding: 2.5%; margin: 0; } .magazineView .photo{ margin-top: -5%; position: relative; width: auto; } .magazineView .content{ position: relative; } .magazineView .content p{ padding: 0 1%; margin: 0; } .magazineView .footer{b position: relative; } .magazineView .footer p{ margin: 2% 0; padding: 0 1%; } .magazineView #more { padding-right: 1%; float: right; } .magazineView #img { position: relative; width: 100%; } .magazineView #title{ background: rgba(50,92,135,0.4); color: #ffffff; padding : 2%; position: absolute; transform: translateY(-110%); margin: auto; width: 96%; } </style> <div class="magazineView"> <div class="container"> <div class="header"> <p><a href="<?=WEB_ROOT?>magazine/magazineList">매거진</a></p> </div> <div class="article"> <?=$article?> </div> <hr> <div class="footer"> <p>에디터 : <?=$magazine->에디터?></p> <p>작성자 : <?=$magazine->작성자?></p> </div> </div> </div> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Magazine extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library(array('session_common','walk_common')); $this->session_common->checkSession("user"); $this->load->model('magazine_model'); } /* * magazineMainSimple * 조진근 * 20170315 * magazineMainSiple페이지표시 * 최대 2개 까지 최신순으로 리스트 표시 * 2개가 넘을경우 더보기 보이기 */ function magazine_comp(){ $type = $this->input->POST("type"); $data["count"] = $this->magazine_model->getMagazineListCount(); $data["magazines"] = $this->magazine_model->getMagazineList(0,2); if( $type == "v"){ $this->load->view("magazine/magazine_comp_v", $data); }else{ $this->load->view("magazine/magazine_comp_h", $data); } } /* * magazineMain * 조진근 * 20170315 * magazineMain 화면으로 이동 */ function magazineList(){ $data["magazines"] = $this->magazine_model->getMagazineList(); $this->load->view ("activity/header_p"); $this->load->view("magazine/magazine_list", $data); $this->load->view ("activity/footer"); } /* * moveToText * 조진근 * 20170315 * magazineView로 이동 */ function magazineView($id){ $data["magazine"] = $this->magazine_model->getIdMatch($id); $data["article"] = $this->walk_common->readHtmlFile($data["magazine"]->매거진_html); $this->load->view ("activity/header_p" ); $this->load->view("magazine/magazine_view", $data); $this->load->view ("activity/footer" ); } } ?> <file_sep><?php foreach($friendIds as $friendId ) { ?> <?php $date_temp=date_create($friendId->전송일시); // $date_val=substr($date_temp,10,15); $date_time = date_format($date_temp,"h:i:s"); $date_ampm = date_format($date_temp,"A"); $date_ampm =$date_ampm =="AM"?"오전":"오후"; ?> <li> <div class="room_box" m_name="<?=$friendId->그룹_id?>"> <div class="room_btn" style="margin-right:60px;min-height:50px;" onclick="room_btn_click('<?=$friendId->그룹_id?>')"> <div class="mythumb2"> <img src="<?=경로_사용자?><?=$friendId->사진?>" alt=""> </div> <div style="margin-left:60px"> <div class="userName"><b><?=$friendId->이름?></b></div> <input type="hidden" class="find" value="<?=$friendId->전송_id?>"/> <div class="time"> <div style="position:relative"> <?php if($friendId->확인여부=="N" && $friendId->전송_id!=$userId){ ?> <img class="badge" src="/mnt/walk/friends/N.PNG" alt="확인하지 않은 메세지에서 나타남"> <?php } ?> <?=$date_ampm?> <?=$date_time?> </div> </div> <div class="text_over"> <?=$friendId->내용?> </div> </div> </div> <div class="det2" name="<?=$friendId->전송_id?>">삭제</div> </div> </li> <?php } ?><file_sep><div style="color:RGB(255,205,51);background:RGB(12,12,12);padding:10px 0px;">축하메시지</div> <div class="thumb_box" style="overflow: hidden;"> <div style="margin:5px 2px 0px 5px;"> <a href="/message/celeIndex/1" class="external"> <div style="position: relative; padding: 0px 0px 5px; background-color: RGB(61,61,61);"> <img class="thumb_img" src="<?= 경로_메시지?><?= $speech -> 대표이미지경로 ?>" style="width:100%;max-height:96px;"> <div class="thumb_title" style="width: 144px;margin:auto;"> <div>개회사</div> </div> </div> </a> </div> </div> <div class="thumb_box" style="overflow: hidden;"> <div style="margin:5px 5px 0px 3px;"> <a href="/message/celeIndex/2" class="external"> <div style="position: relative; padding: 0px 0px 5px; background-color: RGB(61,61,61);"> <img class="thumb_img" src="<?= 경로_메시지?><?= $celMessage -> 대표이미지경로 ?>" style="width:100%;max-height:96px;"> <div class="thumb_title" style="width: 144px;margin:auto;"> <div>축하메시지</div> </div> </div> </a> </div> </div> <file_sep><!DOCTYPE html> <html lang="ko" class=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,target-densitydpi=medium-dpi"/> <!-- 공통 스타일 --> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7.material.colors.min.css"> <link rel="stylesheet" href="/mnt/walk/common/css/framework7-icons.css"> <link rel="stylesheet" href="/mnt/walk/common/css/common.css?t=1"> <title>대회톡</title> <style> .clear{clear:both;} .menu{border-top:1px solid #cdcdcd;margin-top:10px;padding-top:5px;border-bottom:1px solid #cdcdcd;margin-bottom:5px;padding-bottom:5px;} .menu:after {content:"";clear:both;display:block;} .list_box{display:block;} .contentBox{display:none;margin:2px;} .notice_item{ padding:10px 0px; } .notice_item:after{ content:"";clear:both;display:block; } .color_32{background-color:RGB(146,208,80);} .color_31{background-color:RGB(0,176,240);} body{margin:0px} .comment_image{ width: 50px; height: 50px; overflow: hidden; border-radius: 100px; clear:both; } </style> </head> <body style="overflow:auto;"> <div class="talkComments_wrapper"> <div class="navbar" style="background:#ababab;height:40px;line-height:40px;box-shadow:0 3px 6px rgba(255, 255, 255, 0.1)"> <div class="navbar-inner"> <div class="center" > ← 대회톡 </div> <div class="right"> <a href="#" class="link"> <i class="icon icon-bars"></i> </a> </div> </div> </div> </div> <div style="margin:5px;background-color:#ababab;border-radius:5px;padding:10px;"> <div style="font-weight:bold;margin:0px 0px 5px 0px;font-size:16px;">이런 태그는 어때요?</div> <style> .tag{ margin-top:5px;display:inline-block;line-height:15px;border:1px solid #555;padding:5px 3px;background-color:white;border-radius:5px; } </style> <?php foreach($commentTags as $commentTag){ ?> <span class="tag" value=<?=$commentTag->공통코드_id?>>#<?= $commentTag -> 코드명 ?></span> <?php } ?> </div> <div class="comment_list"> <?php foreach($comments as $index => $comment){ ?> <div class="item" style="border:1px solid #cdcdcd;margin:5px;border-radius:5px;padding:5px 10px;"> <div style="display:inline-table;width:100%;height:100%"> <img class="comment_image" src="<?=경로_사용자?><?=$comment->사진?>"/> <span style="display: table-cell; vertical-align: middle;width:100px;"><?=$comment->작성자?></span> <span style="padding-left:30%;display:table-cell; vertical-align: middle;"><?= $comment->작성날짜?></span> </div> <div> <span style="padding-left:60px;" class="content"><?=$comment->댓글?></span> </div> </div> <?php } ?> </div> <div style="height:80px"></div> <div class="more" style="position:fixed;bottom:40px;left:0px;width:100%;background-color:white;height:40px;line-height:40px;text-align:center;border-top:1px solid #cdcdcd;"> 더보기(전체) </div> <div class="more2" style="position:fixed;bottom:40px;left:0px;width:100%;background-color:white;height:40px;line-height:40px;text-align:center;border-top:1px solid #cdcdcd;"> 더보기(태그) </div> <div style="position:fixed;bottom:0px;left:0px;width:100%;"> <div style="border:1px solid #555;position:relative;height:40px;overflow:hidden;background-color:#cdcdcd;"> <span style="margin-left:10px">#</span><input type="text" id="comment" name="comment" style="width:calc(100% - 120px);height:34px;border-width:0px;margin-left:10px;margin-top:2px;" value=""/> <div style="margin:auto;position:absolute;right:2px;top:2px;text-align:center;border-radius:5px;background-color:RGB(255,192,0);width:80px;line-height:35px;height:35px" class="com_insert">글쓰기</div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js?timestamp=201512210800"></script> <script> $(document).ready(function(){ <?php //태그 기준으로 더보기를 하기 위한 변수들 초기화 ?> var totalTagCnt=0; var firstIndex2 = 9; <?php //기본 load화면 - 전체 댓글 더보기 ?> $(".more").css("display","block"); $(".more2").css("display","none"); <?php // 태그 기준으로 불러오기 - 공통코드Table에 있는 공통코드_id 값을 value에 넣어서 가져감 ?> $(".tag").each(function(idx){ $(this).click(function(){ removeCss(); $index = $(".tag").eq(idx); $.ajax({ type:"POST", url: "/board/commentByTag", dataType:"json", data:{ "ctag_id" : $index.attr("value") }, success: function(data){ <?php // 태그 기준 누를 때마다 인덱스 초기화 / 인덱스는 0부터시작이므로 9?> firstIndex2 = 9; <?php //태그 기준 더보기 총 개수 구하기 ?> totalTagCnt = data.totalTagCnt; var str =""; $.each(data.commentByTags , function (index, value) { str += "<div class='item' style='border:1px solid #cdcdcd;margin:5px;border-radius:5px;padding:5px 10px;'><div style='display:inline-table;width:100%;height:100%'>" +"<img class='comment_image' src='<?=경로_사용자?>"+ value.사진 + "'/>" +"<span style='display: table-cell; vertical-align: middle;width:100px;'>" + value.작성자 + "</span><span style='padding-left:30%;display: table-cell; vertical-align: middle;'>" + (value.작성날짜) + "</span>" +"</div><div><span style='padding-left:60px;' class='tag_id' value=" + value.태그+ ">" + value.댓글 +"</span> </div></div>"; }); $(".comment_list").html(str); <?php //태그기준으로 더보기 추가 ?> $(".more").css("display","none"); $(".more2").css("display","block"); $(".tag").eq(idx).css("background-color","#00d2ff"); <?php // 태그 눌렀을 때 css효과 ?> },error: function(result){ alert("실패"); } }); }); }); <?php // 태그 눌렀을 때 css효과 ?> function removeCss(){ $(".tag").each(function(idx){ $(".tag").eq(idx).css("background-color","white"); }); } <?php // 전체 댓글 더보기 를 위한 변수 2개 (firstIndex : 더보기 누를 때마다 시작되는 첫번째 index / totalCnt : 댓글 전체 개수 )?> var firstIndex = 10; var totalCnt = "<?=$totalCnt?>"; $(".more").click(function(){ if(firstIndex>= totalCnt){ alert("이전 댓글이 없습니다."); $(".more").css("display","none"); }else{ $.ajax({ type:"POST", url: "/board/addComment", dataType:"json", data:{ "firstIndex" : firstIndex, "totalCnt" : totalCnt }, success: function(data){ var str =""; $.each(data.addcomments, function (index, value) { str += "<div class='item' style='border:1px solid #cdcdcd;margin:5px;border-radius:5px;padding:5px 10px;'><div style='display:inline-table;width:100%;height:100%'>" +"<img class='comment_image' src='<?=경로_사용자?>"+ value.사진 + "'/>" +"<span style='display: table-cell; vertical-align: middle;width:100px;'>" + value.작성자 + "</span><span style='padding-left:30%;display: table-cell; vertical-align: middle;'>" + (value.작성날짜) + "</span>" +"</div><div><span style='padding-left:60px;' class='content'>" + value.댓글 +"</span> </div></div>"; }); $(".comment_list").append(str); <?php // 더보기 10개가 추가되었으면 더보기 다시 눌렀을 때 firstIndex 10개를 추가함?> firstIndex = firstIndex+10; },error: function(result){ alert("실패"); } }); } }); $(".more2").click(function(){ <?php //index는 0에서 시작 / id는 1에서 시작 ?> if(parseInt(firstIndex2)+1>= totalTagCnt){ alert("이전 댓글이 없습니다."); $(".more2").css("display","none"); }else{ $.ajax({ type:"POST", url: "/board/addCommentByTag", dataType:"json", data:{ <?php //현재 나와있는 마지막 index 다음부터 10개를 select해야 해서 1를 추가함 ?> "firstIndex2" : parseInt(firstIndex2)+1, "ctag_id" : $(".tag_id").attr("value") }, success: function(data){ var str =""; $.each(data.addcommentByTags , function (index, value) { str += "<div class='item' style='border:1px solid #cdcdcd;margin:5px;border-radius:5px;padding:5px 10px;'><div style='display:inline-table;width:100%;height:100%'>" +"<img class='comment_image' src='<?=경로_사용자?>"+ value.사진 + "'/>" +"<span style='display: table-cell; vertical-align: middle;width:100px;'>" + value.작성자 + "</span><span style='padding-left:30%;display: table-cell; vertical-align: middle;'>" + (value.작성날짜) + "</span>" +"</div><div><span style='padding-left:60px; class='content' value='"+ value.태그 + "'>" + value.댓글 +"</span> </div></div>"; }); $(".comment_list").append(str); firstIndex2 = firstIndex2+10; },error: function(result){ alert("실패"); } }); } }); $(".com_insert").click(function(){ $.ajax({ type:"POST", url: "/board/insertComment", dataType:"json", data:{ "comment" : $("#comment").val() }, success: function(result){ <?php // result가 1이면 로그인이 성공한 경우 , result가 0이면 실패?> if(result==1){ alert("성공"); $("#comment").val(""); }else{ alert("삽입되지 않음"); $("#comment").val(""); } },error: function(result){ } }); }); }); </script> </body> </html><file_sep><style> .pwChange_view{ width:100%; height:100%; } .pwChange_title { padding: 30px; padding-bottom:10%; font-size:20px; text-align:center; } div{ padding : 10px; } .pwChange{ border : 1px; background : lightskyblue; padding : 5px; color:white; cursor:pointer; width:70%; margin:100px auto; text-align:center; padding:15px 0; } </style> <div class="pwChange_view"> <div class="pwChange_title"> 비밀번호 재설정 </div> <div class="pwChange_content" style="padding-bottom:70px"> <form action="" method="post" id="newPassword"> <div> 아이디 : <?=$info-> 사용자_id?> </div> <div> 새 비밀번호 <input type="password" id="<PASSWORD>" style="border:none;border-bottom:1px solid black"> </div> <div style="margin-left:20%"> 7~8자, 영문, 숫자, 특수문자 사용 </div> <div> 새 비밀번호 확인 <input type="password" id="<PASSWORD>" style="border:none;border-bottom:1px solid black"> </div> </form> </div> <div class="pwChange"> 변경완료 </div> </div> <script> $(document).ready(function() { $('.pwChange').click(function() { if($("#newpw").val()!= $("#newpw2").val()){ alert("비밀번호가 서로 일치하지 않습니다"); $("#newpw").val(""); $("#newpw2").val(""); }else{ $.ajax({ type:"POST", url: "/user/newPwSet", dataType:"json", data:{ "password" : <PASSWORD>").val() }, success: function(result){ alert("변경 완료"); location.href="/user/userInfo" },error: function(result){ } }); } }); }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Friends_model extends CI_Model{ function __construct(){ parent::__construct(); } /* * myFriends * 최재성 * 20170315 * 친구목록 조회 */ function myFriends($user_id){ $this->db->select("*"); $this->db->from("친구"); $this->db->join('사용자','친구.친구_id=사용자.사용자_id','',FALSE); $this->db->where("친구.사용자_id",$user_id); $this->db->where("친구.상태",14); $this->db->where('사용자.탈퇴코드 is null'); $this->db->order_by("이름"); return $this->db->get()->result(); } /* * cntFriends * 최재성 * 20170315 * 친구 카운트 */ function cntFriends($user_id){ $this->db->select("COUNT(*) 친구_id"); $this->db->from("친구"); $this->db->join('사용자','친구.친구_id=사용자.사용자_id','',FALSE); $this->db->where("친구.사용자_id",$user_id); $this->db->where('사용자.탈퇴코드 is null'); $this->db->where("친구.상태",14); return $this->db->get()->row()->친구_id; } /* * msCheck * 최재성 * 20170404 * 쪽지보기 화면 조회 */ function msCheck($user_id){ $sql = "select * from 쪽지사용자그룹 A join ( select AA.* from focus_walk.쪽지 AA where AA.쪽지_id in ( SELECT max(BB.쪽지_id) FROM focus_walk.쪽지 BB group by BB.그룹_id ) ) B on A.그룹_id = B.그룹_id join ( select * from 쪽지사용자그룹 where 그룹_id in ( select 그룹_id from 쪽지사용자그룹 where 사용자_id = '".mysql_real_escape_string($user_id)."' ) and 사용자_id != '".mysql_real_escape_string($user_id)."' ) C on A.그룹_id = C.그룹_id join 사용자 D on D.사용자_id = C.사용자_id where A.사용자_id = '".mysql_real_escape_string($user_id)."' and D.탈퇴코드 is null order by B.쪽지_id desc"; return $this->db->query($sql)->result(); } /* * newMsChecker * 최재성 * 20170315 * 채팅방 채팅내용 조회 (로드시) */ function newMsChecker($user_id,$msId){ $this->db->select("쪽지.쪽지_id"); $this->db->from("쪽지"); $this->db->join("쪽지사용자그룹","쪽지.그룹_id = 쪽지사용자그룹.그룹_id",'',FALSE); $this->db->where("쪽지사용자그룹.사용자_id in ('".mysql_real_escape_string($user_id)."')"); $this->db->where("쪽지.쪽지_id",$msId); return $this->db->get()->row(); } /* * msRoom * 최재성 * 20170315 * 채팅방 채팅내용 조회 (로드시) */ function msRoom($group_id){ $this->db->select("A.*"); $this->db->from("(select * from 쪽지 join 사용자 on 쪽지.전송_id=사용자.사용자_id where 쪽지.그룹_id=".mysql_real_escape_string($group_id)." order by 쪽지.쪽지_id desc limit 10 ) A"); $this->db->order_by("A.쪽지_id","asc"); return $this->db->get()->result(); } /* * minMs * 최재성 * 20170331 * 로드된 쪽지 중 가장 윗글의 쪽지_id 받아오기 */ function minMs($group_id){ $this->db->select("min(A.쪽지_id) as upperMsId"); $this->db->from("(select * from 쪽지 join 사용자 on 쪽지.전송_id=사용자.사용자_id where 쪽지.그룹_id=".mysql_real_escape_string($group_id)." order by 쪽지.쪽지_id desc limit 10 ) A"); $this->db->order_by("A.쪽지_id","asc"); return $this->db->get()->row()->upperMsId; } /* * totalMinMs * 최재성 * 20170403 * 로드된 전체쪽지 중 가장 윗 글의 쪽지 id 받아옴 */ function totalMinMs($group_id){ $this->db->select("min(A.쪽지_id) as totalMinMs"); $this->db->from("(select * from 쪽지 where 쪽지.그룹_id=".mysql_real_escape_string($group_id)." order by 쪽지.쪽지_id desc ) A"); $this->db->order_by("A.쪽지_id","asc"); return $this->db->get()->row()->totalMinMs; } /* * msRoomCnt * 최재성 * 20170331 * 쪽지 갯수 조회 (로드시) */ function msRoomCnt($group_id){ $this->db->select("count(*) as 쪽지개수"); $this->db->from("쪽지"); $this->db->join('쪽지사용자그룹','쪽지.그룹_id=쪽지사용자그룹.그룹_id and 쪽지.전송_id=쪽지사용자그룹.사용자_id','',FALSE); $this->db->join('사용자','쪽지사용자그룹.사용자_id = 사용자.사용자_id','',FALSE); $this->db->where("쪽지.그룹_id",$group_id); $this->db->order_by("쪽지.쪽지_id","asc"); return $this->db->get()->row()->쪽지개수; } /* * addMs * 최재성 * 20170331 * 채팅방 더보기 버튼 클릭시 메세지 조회 */ function addMs($group_id,$upperMsId){ $this->db->select("*"); $this->db->from("(select * from 쪽지 join 사용자 on 쪽지.전송_id=사용자.사용자_id where 쪽지.그룹_id=".mysql_real_escape_string($group_id)." and 쪽지.쪽지_id<".mysql_real_escape_string($upperMsId)." order by 쪽지.쪽지_id desc limit 10 ) A"); $this->db->order_by("A.쪽지_id","asc"); return $this->db->get()->result(); } /* * checkYN * 최재성 * 20170329 * 쪽지 확인여부 체크 */ function checkYN($user_id,$group_id){ $this->db->set("확인여부","Y"); $this->db->where('그룹_id',$group_id); $this->db->where("전송_id not in ('".$user_id."')"); return $this->db->update('쪽지'); } /* * refreshMs * 최재성 * 20170329 * 쪽지 통신(새로 DB에 입력된 값을 3초마다 페이지에 뿌려준다.) */ function refreshMs($group_id,$msId){ $this->db->select("*"); $this->db->from("쪽지"); $this->db->join('쪽지사용자그룹','쪽지.그룹_id=쪽지사용자그룹.그룹_id and 쪽지.전송_id=쪽지사용자그룹.사용자_id','',FALSE); $this->db->join('사용자','쪽지사용자그룹.사용자_id = 사용자.사용자_id','',FALSE); $this->db->where("쪽지.그룹_id",$group_id); $this->db->where("쪽지.쪽지_id > ".mysql_real_escape_string($msId)." ",NULL,FALSE); $this->db->order_by("쪽지.쪽지_id","asc"); return $this->db->get()->result(); } /* * msRoomOther * 최재성 * 20170324 * 채팅방 채팅내용 조회 */ function msRoomOther($friend_id,$user_id){ $this->db->select("max(그룹_id) as 그룹_id"); $this->db->from("쪽지사용자그룹"); $this->db->where("사용자_id in ('".$user_id."','".mysql_real_escape_string($friend_id)."')"); $this->db->where("사용유무","Y"); $this->db->where("그룹_id in (select 그룹_id from 쪽지사용자그룹 group by 그룹_id having count(*)=2)"); $this->db->group_by("그룹_id"); $this->db->having("count(*)=2"); return $this->db->get()->row(); } /* * msRoomNew * 최재성 * 20170321 * 새 채팅방 만들고 채팅방 Row return */ function msRoomNew($friend_id,$user_id){ $this->db->set("그룹_id","0"); $this->db->insert("쪽지그룹"); $그룹_id = $this->db->insert_id(); $this->db->set("그룹_id",$그룹_id); $this->db->set("사용자_id",$user_id); $this->db->set("생성일","now()",FALSE); $this->db->insert("쪽지사용자그룹"); $this->db->set("그룹_id",$그룹_id); $this->db->set("사용자_id",$friend_id); $this->db->set("생성일","now()",FALSE); $this->db->insert("쪽지사용자그룹"); $this->db->select("max(그룹_id) as 그룹_id"); $this->db->from("쪽지사용자그룹"); $this->db->where("사용자_id in ('".$user_id."','".mysql_real_escape_string($friend_id)."')"); $this->db->where("사용유무","Y"); $this->db->where("그룹_id in (select 그룹_id from 쪽지사용자그룹 group by 그룹_id having count(*)=2)"); $this->db->group_by("그룹_id"); $this->db->having("count(*)=2"); return $this->db->get()->row(); } /* * insertContents * 최재성 * 20170321 * 쪽지 내용 삽입 */ function insertContents($group_id,$user_id,$contents,$msId){ $this->db->set("전송일시","now()",FALSE); $this->db->set("그룹_id",$group_id); $this->db->set("전송_id",$user_id); $this->db->set("내용",$contents); $this->db->insert('쪽지'); $this->db->select("*"); $this->db->from("쪽지"); $this->db->join('쪽지사용자그룹','쪽지.그룹_id=쪽지사용자그룹.그룹_id and 쪽지.전송_id=쪽지사용자그룹.사용자_id','',FALSE); $this->db->join('사용자','쪽지사용자그룹.사용자_id = 사용자.사용자_id','',FALSE); $this->db->where("쪽지.그룹_id",$group_id); $this->db->where("쪽지.쪽지_id > ".mysql_real_escape_string($msId)." ",NULL,FALSE); $this->db->order_by("쪽지.쪽지_id","asc"); return $this->db->get()->result(); } /* * inviteFriend * 최재성 * 20170317 * 나를 초대한 친구 조회 */ function inviteFriend($user_id){ $this->db->select("*"); $this->db->from("친구"); $this->db->join('사용자','친구.사용자_id=사용자.사용자_id','',FALSE); $this->db->where('친구.친구_id',$user_id); $this->db->where('사용자.탈퇴코드 is null'); $this->db->where('친구.상태',13); $this->db->order_by("이름"); return $this->db->get()->result(); } /* * inviteFriend2 * 최재성 * 20170317 * 내가 초대한 친구 조회 */ function inviteFriend2($user_id){ //내가 초대한 친구 검색 $this->db->select("*"); $this->db->from("친구"); $this->db->join('사용자','친구.친구_id=사용자.사용자_id','',FALSE); $this->db->where('친구.사용자_id',$user_id); $this->db->where('사용자.탈퇴코드 is null'); $this->db->where('친구.상태',13); $this->db->order_by("이름"); return $this->db->get()->result(); } /* * inviteEvents * 최재성 * 20170320 * 대회참여 초대 조회 */ function inviteEvents($mode,$user_id){ $this->db->select("*"); $this->db->from("걷기대회_초대"); $this->db->join('걷기대회','걷기대회_초대.걷기대회_id=걷기대회.걷기대회_id','',FALSE); if($mode==1){ $this->db->join('사용자','걷기대회_초대.사용자_id=사용자.사용자_id','',FALSE); $this->db->where('걷기대회_초대.초대자_id',$user_id); }else if($mode==2){ $this->db->join('사용자','걷기대회_초대.초대자_id=사용자.사용자_id','',FALSE); $this->db->where('걷기대회_초대.사용자_id',$user_id); } $this->db->where('사용자.탈퇴코드 is null'); $this->db->where('사용여부','Y'); $this->db->order_by("사용자.이름"); return $this->db->get()->result(); } /* * acceptEvents * 최재성 * 20170328 * 대회참여 초대 수락(나를 초대한 친구) */ function acceptEvents($event_id,$user_id){ $timeStamp = now(); $data = array( '걷기대회_id' => $event_id , '사용자_id' => $user_id , '상태' => 18, '완보여부' => 'N', '참가신청일시' => $timeStamp, '완보일' =>null ); return $this->db->insert('걷기대회_참가자',$data); } /* * deletetEvents * 최재성 * 20170328 * 대회참여 초대 수락(나를 초대한 친구) */ function deletetEvents($event_id,$user_id){ $this->db->where("걷기대회_id",$event_id); $this->db->where("초대자_id",$user_id); return $this->db->delete('걷기대회_초대'); } /* * rejectEvents * 최재성 * 20170328 * 대회참여 초대 거부(나를 초대한 친구) */ function rejectEvents($invite_id){ $this->db->set("사용여부","N"); $this->db->where("초대_id",$invite_id); return $this->db->update('걷기대회_초대'); } /* * deleteFriends * 최재성 * 20170315 * 친구삭제 */ function deleteFriends($user_id,$friend_id,$state){ $this->db->where("사용자_id",$user_id); $this->db->where("친구_id",$friend_id); $this->db->set("상태",$state); return $this->db->update("focus_walk.친구"); } /* * deleteMs * 최재성 * 20170316 * 채팅방 삭제 */ function deleteMs($group_id,$user_id){ $this->db->where("그룹_id",$group_id); $this->db->where("전송_id",$user_id); $this->db->delete('쪽지'); $this->db->where("그룹_id",$group_id); $this->db->where("사용자_id",$user_id); $this->db->delete('쪽지사용자그룹'); return ; } /* * rejectFriends * 최재성 * 20170321 * 친구초대 거절 */ function rejectFriends($user_id,$friend_id,$state){//나를 초대한 친구 거절 $this->db->where("사용자_id",$friend_id); $this->db->where("친구_id",$user_id); $this->db->set("상태",$state); return $this->db->update("focus_walk.친구"); } /* * rejectFriends2 * 최재성 * 20170321 * 친구초대 거절 */ function rejectFriends2($user_id,$friend_id,$state){//내가 초대한 친구 취소 $this->db->where("사용자_id",$user_id); $this->db->where("친구_id",$friend_id); $this->db->set("상태",$state); return $this->db->update("focus_walk.친구"); } /* * acceptFriends * 최재성 * 20170321 * 친구초대 수락 */ function acceptFriends($friend_id,$user_id,$state){ $sql = "insert into focus_walk.친구 (사용자_id, 친구_id ,상태,승인일) select '".mysql_real_escape_string($friend_id)."','".$user_id."',14, now() from dual union all select '".$user_id."','".mysql_real_escape_string($friend_id)."',14, now() from dual ON DUPLICATE KEY UPDATE 상태=14"; return $this->db->query($sql); } /* * inviteList * 최재성 * 20170321 * 내친구 중 걷기대회 초대자 */ function inviteList($user_id,$event_id){ $this->db->select("*,case when E.공통코드_id is not null then E.코드명 when C.초대자_id is null then '초대' else '초대중' end 상태",FALSE); $this->db->from("친구 A"); $this->db->join('사용자 B','A.친구_id = B.사용자_id','',FALSE); $this->db->join('걷기대회_초대 C','A.친구_id = C.초대자_id AND C.사용자_id = A.사용자_id AND C.걷기대회_id='.$event_id." and C.사용여부='Y'" ,'left outer',FALSE); $this->db->join('걷기대회_참가자 D','A.친구_id = D.사용자_id AND D.걷기대회_id = '.mysql_real_escape_string($event_id),'left outer',FALSE); $this->db->join('공통코드 E','E.공통코드_id = D.상태','left outer',FALSE); $this->db->where('A.사용자_id',$user_id); $this->db->where('A.상태',14); $this->db->where('B.탈퇴코드 is null'); $this->db->order_by("B.이름"); return $this->db->get()->result(); } /* * insertInvite * 최재성 * 20170327 * 초대한 친구 삽입 */ function insertInvite($event_id, $user_id, $friend_id){ $data = array( '걷기대회_id' => $event_id , '사용자_id' => $user_id , '초대자_id' => $friend_id, '초대일시' => now() ); $this->db->insert('걷기대회_초대',$data); } /* * avgStepInfo * 최재성 * 20170327 * 일일평균걸음수 조회 */ function avgStepInfo($friend_id){ $this->db->select("사용자.이름 as 이름, round(avg(사용자통계.걸음수)) as 일일평균걸음수",FALSE); $this->db->from("사용자"); $this->db->join('사용자통계','사용자.사용자_id = 사용자통계.사용자_id','left outer',FALSE); $this->db->where('사용자.사용자_id',$friend_id); return $this->db->get()->row(); } /* * joinInfo * 최재성 * 20170327 * 참여중인대회수 조회 */ function joinInfo($friend_id){ $this->db->select("사용자.사진,count(걷기대회_id) as 참여대회수",FALSE); $this->db->from("사용자"); $this->db->join('걷기대회_참가자',"사용자.사용자_id = 걷기대회_참가자.사용자_id and 사용자.사용자_id='".mysql_real_escape_string($friend_id)."'",'',FALSE); $this->db->where("사용자.사용자_id in(select 걷기대회_참가자.사용자_id from 걷기대회_참가자 where 걷기대회_참가자.상태=18 or 19 or 21)"); return $this->db->get()->row(); } /* * recentEventInfo * 최재성 * 20170327 * 최근 참여 대회 3개 조회 */ function recentEventInfo($friend_id){ $this->db->select("*"); $this->db->from("걷기대회"); $this->db->join('걷기대회_참가자',"걷기대회.걷기대회_id=걷기대회_참가자.걷기대회_id and 걷기대회_참가자.사용자_id ='".mysql_real_escape_string($friend_id)."'",'left outer',FALSE); $this->db->where("걷기대회_참가자.상태",18); $this->db->or_where("걷기대회_참가자.상태",19); $this->db->or_where("걷기대회_참가자.상태",21); $this->db->order_by('걷기대회_참가자.참가신청일시','desc'); $this->db->limit(3); return $this->db->get()->result(); } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Index_model extends CI_Model{ function __construct(){ parent::__construct(); } /* * getIndexInfo * 정수영 * 20170313 * t_index table의 모든 record return */ function getIndexInfo(){ $this->db->select("*"); $this->db->from("개발목록"); $this->db->order_by("항목 asc"); return $this->db->get()->result(); } } ?> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Board extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('board_model'); } /* * index * 이민수 * 20170316 * 게시판 */ function index(){ } //공지사항,이벤트 게시판 function myBoard(){ //로그인한 정보 $myLogin = array('USER_ID' => "gildong", 'USER_NAME' => "홍길동","USER_PIC"=>경로_사용자."hong.jpg"); $data["notices"] = $this->board_model->getNotices(); $this->load->view("board/myBoard_notice_view", $data); } /* * talkBoard * 이소희 * 20170331 * 댓글 게시판 */ //대회톡 게시판(댓글) function talkBoard(){ //댓글 태그 정보 가져오기 $data["commentTags"] = $this->board_model->getCommentTags(); // 공통코드에 있는 태그 정보들 가져오기 $data["totalCnt"] =$this->board_model->commentCnt(); //댓글 전체 개수 가져오기 (더보기 - 갯수 체크) $data["comments"] = $this->board_model->getTalkComments(); // 댓글 가져오기 $this->load->view ( "activity/header_p" ); $this->load->view("board/talkBoard_view", $data); $this->load->view ( "activity/footer" ); } /* * commentByTag * 이소희 * 20170331 * 태그 기준으로 댓글 가져오기 */ function commentByTag(){ $ctag_id=trim($this->input->post('ctag_id')); $data['commentByTags'] =$this->board_model->commentByTag($ctag_id); $data["totalTagCnt"] =$this->board_model->commentTagCnt($ctag_id); //태그 기준 댓글 전체 개수 가져오기 (더보기 - 갯수 체크) echo json_encode($data); } /* * addComment * 이소희 * 20170404 * 덧글 더보기 추가 */ function addComment(){ $firstIndex=trim($this->input->post('firstIndex')); $totalCnt=trim($this->input->post('totalCnt')); $data['addcomments'] =$this->board_model->addComment($firstIndex,$totalCnt); echo json_encode($data); } /* * addCommentByTag * 이소희 * 20170404 * 태그 기준 더보기 추가 */ function addCommentByTag(){ $ctag_id=trim($this->input->post('ctag_id')); $firstIndex2=trim($this->input->post('firstIndex2')); $data['addcommentByTags'] =$this->board_model->addCommentByTag($ctag_id,$firstIndex2); echo json_encode($data); } /* * insertComment * 이소희 * 20170331 * 댓글 추가 */ function insertComment(){ $user_id = $this->session_common->getSession("user")["user_id"]; $comment = $this->input->post('comment'); $result = $this->board_model->insertComment($user_id, $comment); echo $result; } /* * 이소희 * 20170329 * MainActivity_2 하위 컴포넌트 * 대회 댓글 컴포넌트 (댓글 3개) */ function comment_comp(){ $data['comments'] = $this->board_model->getThreeComments(); $this->load->view ("board/comment_comp",$data); } /* * questionIndex * 이소희 * 20170328 * 질문게시판 초기화면 */ function questionIndex(){ $this->load->view("activity/header_p"); $this->load->view("board/question_index"); $this->load->view("activity/footer"); } /* * questionIndex_sub * 이소희 * 20170328 * 질문게시판 분기 (FAQ/문의): index 41 : FAQ / 42: 문의 */ function questionIndex_sub($index){ if($index==41){ //FAQ 질문 분류(코드명) 불러오기 $data['listTitles'] = $this->board_model->faqType($index); $data['faqs']=$this->board_model->questionIndex_sub($index); $this->load->view("activity/header_p"); $this->load->view("board/faq_view",$data); $this->load->view("activity/footer"); }else{ $data['qnaTitles'] = $this->board_model->qnaType(); $this->load->view("activity/header_p"); $this->load->view("board/question_view",$data); $this->load->view("activity/footer"); } } /* * insertQue * 이소희 * 20170328 * 문의하기 */ function insertQue(){ $name=trim($this->input->post('name')); $email=trim($this->input->post('email')); $contents=trim($this->input->post('contents')); $queKind =trim($this->input->post('queKind')); $info = array( 'name' => $name, 'email' => $email, 'contents' => $contents, 'queKind' => $queKind ); $result = $this->board_model->insertQue($info); //저장후 FAQ로 이동 header('Location : /board/questionIndex'); } } ?><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Content extends CI_Controller { function __construct(){ parent::__construct(); $this->load->library('session_common'); $this->session_common->checkSession("user"); $this->load->model('content_model'); } /* * 홍익표 * 20170330 * wish 페이지 열기 * $id wish id */ function wish($id = ""){ $user_id = $this->session_common->getSession("user")["user_id"]; $wish = $this->content_model->getWishInfo($user_id,$id); redirect(WEB_ROOT.$wish->위시_html); } function finishWish(){ header("Content-Type:application/json"); $user_id = $this->session_common->getSession("user")["user_id"]; if($this->content_model->issueWish($user_id)['result']){ redirect("/activity/MainActivity_2/"); } else{ redirect("/index/"); } } function mission($id = ""){ $user_id = $this->session_common->getSession("user")["user_id"]; $wish = $this->content_model->getMissionInfo($user_id,$id); redirect(WEB_ROOT.$wish->위시_html); } function finishMission(){ header("Content-Type:application/json"); $user_id = $this->session_common->getSession("user")["user_id"]; if($this->content_model->issueMission($user_id)['result']){ redirect("/activity/MainActivity_2/"); } else{ redirect("/index/"); } } function deleteWish(){ $user_id = $this->session_common->getSession("user")['user_id']; $event_id = $this->session_common->getSession("user")['contest_id']; $this-> content_model -> deleteWishStamp($user_id, $event_id); } function deleteMission(){ $user_id = $this->session_common->getSession("user")['user_id']; $event_id = $this->session_common->getSession("user")['contest_id']; $this-> content_model -> deleteMissionState($user_id, $event_id); } } ?> <file_sep><div class="owl-carousel owl-theme" style="padding-top:10px" > <?php foreach($walkLists as $key=>$walkList) {?> <div class="item" style="position:relative;"> <div class="" style=""> <div class="card-content"> <div class="card-content-inner" style="padding:0px;"> <div style="text-align:center;position:relative;display:table;background:#191919;" class="pic_wrapper"> <div style="display:table-cell;vertical-align:middle;"> <a href="/walk/getSelectedWalkEvent/<?= $walkList->걷기대회_id?>" class="external"> <div class="pic_box" style="position:relative;" > <span style="position:absolute;top:5px;right:5px;padding:5px 10%;background:rgba(0, 0, 0, 0.8);z-index:99999;font-size:10px;color:#c7c7c7;border-radius:20px;">1. 종료일 <?= $diffdate->남은종료일?>일 남음</span> <img src="<?= 경로_걷기대회.$walkList->대회포스터?>" style="width:100%;"> </div> </a> </div> </div> <div class="swp_text" > <div comp_prop="poster_info" style="width:70%;float:left;"> <div style="padding:10px 0px"> <div comp_prop="poster_info_a" style="display:block;"> <div style="text-align:left;"> <h4><?= $walkList->제목?></h4> <div style="font-weight:normal;font-size:14px;"><?= substr($walkList->시작일시,0,10)?> ~ <?=substr($walkList->종료일시,0,10)?></div> <div style="display:-webkit-inline-box;"> <div style="margin-right:10px;"><i class="f7-icons size-20">person</i><span style="color:#727219;"><?=number_format($walkList->참가자수)?>명</span></div> <div ><i class="f7-icons size-20">flag</i><span style="color:#727219;"><?=number_format($walkList->완보자수)?>명</span></div> </div> </div> </div> <div comp_prop="poster_info_b" style="display:none;"> <div style="text-align:left;padding-left:10px;"> <div style="display:flex;"><i class="f7-icons size-20 ">bag</i><span style="font-size:13px;font-weight:bold;"><?=number_format($walkList->경품수)?>개 (70% 이하)</span></div> <div style="display:flex;"><i class="f7-icons size-20 ">bag_fill</i><span style="font-size:13px;font-weight:bold;"><?=number_format($walkList->기념품수)?>개 (10% 이상)</span></div> <div style="display:flex;"><span style="font-size:11px;color:#727219;">스파크자동차, 서울랜드 자유이용권 등</span></div> </div> </div> </div> </div> <div style="width:30%;float:left;position:relative;"> <div style="padding:0px 0px;margin-top:10px;"> <a href="/walk/getSelectedWalkEvent/<?= $walkList->걷기대회_id?>" class="button button-big button-fill button-raised external" style="height:40px;background-color:#3a3737;width:100%;"> <div style="margin:0px 0px;line-height:20px;"> <div style="color:#ff0;font-size:12px;">참가신청</div> <div style="color:#827d7d;font-size:12px;">D<?= $diffdate->남은참가신청일?></div> </div> </a> </div> </div> <div style="clear:both"></div> </div> </div> </div> </div> </div> <?php } ?> </div> <!-- ENTRANCE BUTTON --> <div comp_prop="entrance_button" style="height:60px;"> <a href="#" class="button button-big button-fill button-raised external" style="background-color:#141031;width:100%;height:100%;border-radius:0px;"> <div style="line-height:15px;height:100%;padding:10px 0px;"> <span style="display:block;width:100%;color:#ff0;font-size:1.5em;margin-bottom:10px;">WISH TRACK 입장하기</span> <span class="walk_tit" style="display:block;width:100%;color:#ed8300;margin:0px;"></span> </div> </a> </div> <!-- ENTRANCE BUTTON END--> <file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>event</title> </head> <body> <?php foreach ( $events as $event ) { ?> <img src="<?=경로_이벤트.$event->배너파일?>" alt="<?=htmlspecialchars($event->제목,ENT_QUOTES)?>" width="100%"/> <?php } ?> </body> </html><file_sep><style media="screen"> .magazineWalkMain ul { padding: 5px 0; list-style-type: none; background-color: #282828 } .magazineWalkMain .container{ width : 100%; background-color: gray; } .magazineWalkMain .header{ position: relative; background-color: gray; width: auto; } .magazineWalkMain .header p{ text-align: left; padding: 3%; margin: 0; } .magazineWalkMain .list{ display : table; position: relative ; width: auto; min-height: 100px; } .magazineWalkMain .article { position: relative; height: auto; } .magazineWalkMain .subtitle{ text-align: left; padding-right: 10px; display: table-cell; vertical-align: middle; color: gray; position: relative; } .magazineWalkMain #thumbnail{ display: table-cell; vertical-align: middle; float: left; padding : 10px; } .magazineWalkMain #more { padding-right: 5px; float: right; } .magazineWalkMain .article li:last-child hr{ display: none; } </style> <div class="magazineWalkMain"> <div class="container"> <div class="header"> <p>매거진 <?php if( $count > 2 ){ ?> <a class="external" id="more" href="<?=WEB_ROOT?>magazine/magazineList"> 더보기</a> <?php } ?> </p> </div> <div class="article"> <ul> <?php foreach ($magazines as $magazine){ ?> <li value="<?=$magazine->매거진_id?>" > <p class='list' value="<?=$magazine->매거진_id?>"> <img id="thumbnail" src="<?=경로_매거진.$magazine->섬네일?>" > <span class="subtitle"><?= $magazine->제목 ?></span> </p> <hr> </li> <?php } ?> </ul> </div> </div> </div> <script type="text/javascript"> $(document).ready(function(){ $(".list").on("click",function(){ window.location.assign("<?=WEB_ROOT?>magazine/magazineView/"+$(this).attr("value")); }) }); </script> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Index extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('index_model'); } /* * Activity Index * * */ function index(){ $data["indexes"] = $this->index_model->getIndexInfo(); $this->load->view("index/index_view", $data); } } ?><file_sep> <?php foreach($walkLists as $key=>$walkList) {?> <div id="event_lists"> <img class="event_poster" src="<?=경로_걷기대회.$walkList->대회포스터?>"></img> <div class="event_items" value="<?=$walkList->걷기대회_id?>"> <ul class="event_items_details" style="list-style: none;"> <li> <?= $walkList->제목?> </li> <li><?= $walkList->시작일시?> ~ <?=$walkList->종료일시?> </li> <li>참가자수 :<?=$walkList->참가자수?> </li> <li>완보자수 :<?=$walkList->완보자수?> </li> </ul> </div> <div class="event_items_pre_details" value="<?=$walkList->걷기대회_id?>" style="display: none"> <ul class="event_items_details" style="list-style: none;"> <li>경품수 : <?=$walkList->경품수?> </li> <li>기념품수 : <?=$walkList->기념품수?> </li> </ul> </div> <div id="participate_button" class="partici_button"> <?php if($walkList->버튼상태 == '참가신청'){ ?> <p class="move_buttons" onclick="apply(<?= $walkList->걷기대회_id ?>)">참가신청<p> <?php }else{ ?> <p class="move_buttons"><?= $walkList->버튼상태?> </p> <?php } ?> </div> </div> <?php } ?> <script> function apply(id){ location.href = "/walk/getSelectedWalkEvent/"+id; //해당 url로 이동; } $("div.event_items").on("click",function(){ var id_num = $(this).attr("value"); $(".event_items[value="+id_num+"]").css("display","none"); $(".event_items_pre_details[value="+id_num+"]").css("display","block"); }); $("div.event_items_pre_details").on("click",function(){ var id_num = $(this).attr("value"); $(".event_items[value="+id_num+"]").css("display","block"); $(".event_items_pre_details[value="+id_num+"]").css("display","none"); }); </script> <file_sep><style> .findPw_view{ width:100%; height:100%; } .findPw_title{ font-size:20px; text-align:center; padding:30px; padding-bottom:5%; color:#979797; } .findPw_view .msg{ padding:5%; padding-bottom:10%; text-align:center; color:#979797; } .findPw_view .vcCode{ background:#60b9f0; margin-left:10px; width:120px; position:relative; padding:10px 10px; text-align:center; color:white; display:inline; } .findPw_view .codeValue{ padding:5%; color:red; } .findPw_view #myCode{ width:80%; border:none; border-bottom:1px solid #979797; padding-bottom:10px; margin-bottom:20px; display:inline; } .findPw_view .check{ background:#60b9f0; text-align:center; color:white; width:50%; margin:0 auto; padding:10px 0; } .findPw_view .nextBtn{ background:#60b9f0; margin:10px; width:100%; position:relative; padding:10px 0px; text-align:center; color:white; display:none; } </style> <div class="findPw_view"> <div class="findPw_title"> 비밀번호 찾기 </div> <div class="msg"> 비밀번호를 찾고자 하는 아이디를 입력하세요. </div> <form method="post" action="/user/findPw" class="findPw_contents" style="padding:5%; padding-bottom:15px;"> <div> <input type="text" id="user_id" name="user_id" placeholder="아이디 입력" style="border:none; border-bottom: 1px solid #979797; margin-bottom:5%; padding-bottom:10px; width:100%"> </div> <div> <input type="text" id="name" name="name" placeholder="이름 입력" style="border:none; border-bottom: 1px solid #979797; margin-bottom:5%; padding-bottom:10px; width:100%"> </div> <div> <input type="text" id="phone" name="phone" placeholder="휴대폰번호 입력" style="width:100%; border:none; border-bottom:1px solid #979797; padding-bottom:10px; margin-bottom:20px;"> </div> <div class="vcCode"> 인증번호 요청 </div> <div class="codeValue"> </div> <div> <input type="text" id="myCode" placeholder="인증번호 입력"> <div class="check"> 인증번호 확인 </div> </div> </form> </div> <script> $(document).ready(function() { $('.vcCode').click(function() { if($('#user_id').val()=="" || $('#name').val()=="" || $('#phone').val()==""){ alert("내용을 다 입력하지 않았습니다."); return; } $.ajax({ type:"POST", url: "/user/insertCode2", dataType:"json", data:{ "user_id" : $("#user_id").val(), "phone" : $("#phone").val(), }, success: function(result){ if (result["cnt"]==0){ alert("일치하는 정보가 없습니다."); $('#user_id').val(""); $('#name').val(""); $('#phone').val(""); return; }else{ <?php //DB에 인증번호 저장 후 인증번호 보여주기 ?> $(".codeValue").text("해당번호로 인증번호를 발송했습니다. " + result["rand_num"]); } },error: function(result){ } }); }); $('.check').click(function() { $.ajax({ type:"POST", url: "/user/checkCode2", dataType:"json", data:{ "user_id" : $("#user_id").val(), "code" : $("#myCode").val() }, success: function(result){ <?php //DB에 인증번호 저장 후 인증번호 보여주기 ?> if(result==1){ $('.findPw_contents').submit(); }else{ alert("인증번호가 틀렸습니다"); $(".codeValue").text(""); $("#myCode").val(""); } },error: function(result){ } }); }); }); </script><file_sep><ul class="open"> <?php foreach ($checkInList as $checkIn){ ?> <li class="list" value="<?=$checkIn->프로모션_id?>" onclick=""> <p class="title">[<?=$checkIn->주최?>] <?=$checkIn->제목?></p> <img class="banner" src="/mnt/walk/checkin/<?=$checkIn->배너?>" alt=""> </li> <?php } ?> </ul> <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Event_model extends CI_Model{ function __construct(){ parent::__construct(); } /* * getLiveEventCount * 홍익표 * 20170310 * 이벤트 Count 조회 */ function getLiveEventCount(){ $this->db->select("count(*) cnt"); $this->db->from("이벤트"); $this->db->where("시작일시 <= now()",NULL,FALSE); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용여부","Y"); return $this->db->get()->row()->cnt; } /* * getLiveEvent * 홍익표 * 20170310 * 이벤트 List 조회 * $count : record 개수 * $start : record 시작 */ function getLiveEvent($count='',$start=''){ $this->db->select("*"); $this->db->from("이벤트"); $this->db->where("시작일시 <= now()",NULL,FALSE); $this->db->where("now() <= 종료일시",NULL,FALSE); $this->db->where("사용여부","Y"); $this->db->order_by("이벤트_id desc"); if($count !='' || $start !='') $this->db->limit($start,$count); return $this->db->get()->result(); } } ?> <file_sep><style> div.apply_walk_event .top_content { position: relative; margin-right: auto; background: #f1f1f1; text-align: -webkit-center; width: 100%; height: 25px; } div.apply_walk_event div.top_sub_content { background: lavender; height: 120px; margin-top: 10px; } div.apply_walk_event div.event_apply_button { cursor: pointer; margin-right: auto; margin-left: auto; text-align: -webkit-center; border: groove; height: auto; background: steelblue; margin: auto; border-radius: 8px; } div.apply_walk_event div.event_modify_button { cursor: pointer; margin-right: auto; margin-left: auto; text-align: -webkit-center; border: groove; background: steelblue; margin: 20px; position: relative; top: auto; height: auto; border-radius: 8px; } div.apply_walk_event img#cotent_image { position: relative; max-width: 85px; max-height: 100%; float: left; } div.apply_walk_event div#top_info_content { float: left; position: relative; font-size: 13px; color: #666666; font-weight: bolder; } div.apply_walk_event p#apply_date { font-size: xx-small; } div.apply_walk_event div.middle_sub_content { background: #e3e3e3; height: 180px; } div.apply_walk_event div.bottom_sub_content { width: 100%; background: whitesmoke; } div.apply_walk_event div.event_join_content { background: whitesmoke; height: 120px; } div.apply_walk_event li.event_join_content_agree { position: relative; float: left; width: 100%; line-height: 30px; background-color: #e3e3e3; color: #666666; font-size: 12px; list-style-type: none; } div.apply_walk_event ul { padding-left: 0px; margin-left: 0; } div.apply_walk_event input { float: right; } div.apply_walk_event textarea.agree_area { border-color: #DFDFDF; background-color: silver; color: #333333; border-radius: 3px 3px 3px 3px; border-style: solid; border-width: 1px; font-size: 12px; position: relative; float: left; width: 96%; padding: 5px; height: 100px; } div.apply_walk_event ul.middle_sub_content_items { font-size: smaller; padding: 10px; margin: 5px; list-style-type: none; } div.apply_walk_event select { margin: 10px; padding: 2px; position: relative; width: 30%; } div.apply_walk_event p#top_company { font-size: 10px; padding-bottom: 0px; } </style> <div class="apply_walk_event"> <div class="top_content"> <b>대회신청하기</b> </div> <div class="sub_content"> <div class="top_sub_content"> <img id="cotent_image" src="<?=경로_걷기대회.$selectEvent[0]->대회포스터 ?>"></img> <div id="top_info_content"> <p id="top_company"><?=$selectEvent[0]->주최?></p> <p id="top_title"><?=$selectEvent[0]->제목?></p> <p>목표결음수 : <?=number_format($selectEvent[0]->목표걸음수)?></p> <p id="apply_date">신청기간 : <?= substr($selectEvent[0]->시작일시,0,10)?> ~ <?=substr($selectEvent[0]->종료일시,0,10)?></p> </div> </div> <div class="middle_sub_content"> <ul class="middle_sub_content_items"> <li>이름 : <?=$selectUser->이름?></li> <li>성별 : <?=$selectUser->성별?></li> <li>이메일 :<?=$selectUser->이메일?></li> <li>전화번호:<?=$selectUser->핸드폰?></li> <li>지역 <select name='Region'> <option value=''>-- 선택 --</option> <option value='soeul'>서울시</option> <option value='gangju'>광주시</option> </select> <select name='District'> <option value=''>-- 선택 --</option> <option value='seocho'>서초구</option> <option value='gangdong'>강동구</option> </select> </li> <div class="event_modify_button" value="개인정보 변경하기"> <b>개인정보 변경하기</b> </div> </ul> </div> <div class="bottom_sub_content"> <div class="event_join_content"> <ul class="event_join_content_lists"> <li class="event_join_content_agree"> <input type="checkbox" name="all_agree" id="all_agree_button"> <b class="agree_event" id="all_granted_button" style="font-size: small; text-decoration: underline"> 아래의 내용에 모두동의합니다.<br> </b> </input> </li> <ul class='agree_subject'> <li class="event_join_content_agree" id="li1"> <input type="checkbox" name="agree_box" id="agree02"> <b class="agree_event" id="granted_button1" style="font-size: small; text-decoration: underline; cursor: pointer;"> 개인정보 취금방침동의(필수)<br> </b> </input> <textarea class=agree_area id="textarea1" style="display: none">동의 내용 ~~ </textarea> </li> <li class="event_join_content_agree" id="li2"> <input type="checkbox" name="agree_box" id="agree03"> <b class="agree_event" id="granted_button2" style="font-size: small; text-decoration: underline; cursor: pointer;"> 개인정보 3자 제공에 대한 동의(필수)<br> </b> </input> <textarea class=agree_area id="textarea2" style="display: none">동의 내용 ~~ </textarea> </li> <li class="event_join_content_agree" id="li3"> <input type="checkbox" name="agree_box" id="agree04"> <b class="agree_event" id="granted_button3" style="font-size: small; text-decoration: underline; cursor: pointer;"> 개인정보 마케팅 활용에 대한 동의(선택)<br> </b> </input> <textarea class=agree_area id="textarea3" style="display: none">동의 내용 ~~ </textarea> </li> </ul> </ul> </div> </div> <a href="/activity/MainActivity_2/" > <div class="event_apply_button" value="abcdefg"> <b>신청완료</b> </div> </a> </div> </div> <script type="text/javascript"> $(document).ready(function(){ $("#all_agree_button").click(function(){ var chk = $(this).is(":checked"); //check여부 if(chk){$(".agree_subject input").prop('checked',true);} else{$(".agree_subject input").prop('checked',false);} }); }); var cur_open = ""; //현재 열려있는 토글 function toggleclose(submenu_class){ $('#'+cur_open).animate({ opacity : "show", //투명도 height : "toggle", queue : true }); cur_open=""; } function toggle_animate(move_menu){ if(cur_open!="" && cur_open!=move_menu){ //열려있는 토글이 현재 토글이 아니면, toggleclose(cur_open); //열려있는 토글닫고, $('#'+move_menu).animate({ //다시 토글 opacity : "show", //투명도 height : "toggle", }); cur_open = move_menu; } else if(cur_open==""){ //열려있는 토글이 없다면, $('#'+move_menu).animate({ //다시 토글 opacity : "show", //투명도 height : "toggle", }); cur_open = move_menu; }else if(cur_open == move_menu){ //현재 열려있는 토글이 지금 토글이면, toggleclose(cur_open); //열려있는 토글 닫기 } } $(document).ready(function() { $('.agree_event').click(function() { var submenu_check = $(this).attr('id'); //클래스 확인을 위함 $(".event_join_content_agree").css("background-color",'#e3e3e3'); if(submenu_check == "granted_button1") { var move_menu = "textarea1"; //움직일 토글 toggle_animate(move_menu); if(cur_open==move_menu){ $(".event_join_content_agree[id=li1]").css("background-color",'lightsteelblue'); } } else if (submenu_check == "granted_button2") { var move_menu = "textarea2"; //움직일 토글 toggle_animate(move_menu); if(cur_open==move_menu){ $(".event_join_content_agree[id=li2]").css("background-color",'lightsteelblue'); } } else if (submenu_check == "granted_button3") { var move_menu = "textarea3"; //움직일 토글 toggle_animate(move_menu); if(cur_open==move_menu){ $(".event_join_content_agree[id=li3]").css("background-color",'lightsteelblue'); } } }); }); </script> <?php ?> <file_sep><?php class MY_model { public function __construct(){ $this->CI =& get_instance(); } //분류 조회 function get_codeinfo($option){ //1:대분류 2:중분류 3:대분류 $this->CI->db->select('code, code_name, pnt'); $this->CI->db->order_by('pnt'); if($option['num'] == '1'){ $result = $this->CI->db->get_where(TBL_CODE, array('create_yn'=>'Y','length(code)'=>'3','code like '=>'N%'))->result(); }elseif($option['num'] == '2'){ $this->CI->db->where(array('create_yn'=>'Y','length(code)>='=>'4', 'code not like'=>'%\_%\_%'))->like('code',$option['svc_code']); $result = $this->CI->db->get(TBL_CODE)->result(); }elseif($option['num'] == '3'){ $this->CI->db->where(array('create_yn'=>'Y','length(code)>='=>'7', 'code like'=>'%\_%\_%', 'code not like'=>'%\_%\_%\_%'))->like('code',$option['svc_code']); $result = $this->CI->db->get(TBL_CODE)->result(); }elseif($option['num'] == '4'){ $this->CI->db->where(array('create_yn'=>'Y','length(code)>='=>'10', 'code like'=>'%\_%\_%\_%'))->like('code',$option['svc_code']); $result = $this->CI->db->get(TBL_CODE)->result(); } return $result; } //게시판분류 조회 function get_boardinfo($option){ //1:게시판그룹 2:게시판종류 3:게시판말머리 if($option['num'] == '1'){ $this->CI->db->select('code, code_name'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_CODEDETAIL, array('create_yn'=>'Y','code_group'=>'BOARD_GR'))->result(); }elseif($option['num'] == '2'){ $this->CI->db->select('board_id, board_name, board_code1'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_BOARDINFO, array('level <> '=>'9', 'board_code'=>$option['board_code']))->result(); } return $result; } //권한 적용된 부서 조회 function get_departShowInfo($loginId){ $query = $this->CI->db->query(" select code, code_name, pnt from t_code_detail A , ( select DEPART_TP from t_dept_group_auth DD where DD.DEPART_GROUP in (select dept_group_id from t_p_dept_auth CC where CC.gnum = (select EE.gdnum from gija_id_tbl EE where EE.gijaid = '$loginId')) and (READ_ALL = 'Y' or `READ` = 'Y') group by DEPART_TP ) B where B.DEPART_TP = A.code and A.code_group = 'DEPART_TP' and A.create_yn = 'Y' order by A.pnt"); return $query->result(); } //부서 조회 function get_departinfo(){ $this->CI->db->select('code, code_name, pnt'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_CODEDETAIL, array('create_yn'=>'Y', 'code_group'=>'DEPART_TP'))->result(); return $result; } //시리즈리스트 function get_series($lang=''){ $this->CI->db->select('code, code_name, create_yn'); $this->CI->db->order_by('pnt'); $this->CI->db->order_by('code'); $result = $this->CI->db->get(TBL_SERIES)->result(); return $result; } //대분류 시리즈 function get_first_series(){ $this->CI->db->select('code, code_name, create_yn'); $this->CI->db->order_by('create_yn', 'desc'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_SERIES, array('LENGTH(code)'=>'3'))->result(); return $result; } //중분류 시리즈 function get_second_series($code){ $this->CI->db->select('code, code_name, create_yn'); $this->CI->db->order_by('create_yn', 'desc'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_SERIES, array('LENGTH(code)'=>'6','create_yn'=>'Y', 'code like'=>$code.'%'))->result(); return $result; } //소분류 시리즈 function get_third_series($code){ $this->CI->db->select('code, code_name, create_yn'); $this->CI->db->order_by('create_yn', 'desc'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_SERIES, array('LENGTH(code)'=>'9','create_yn'=>'Y', 'code like'=>$code.'%'))->result(); return $result; } //4depth 시리즈 function get_fourth_series($code){ $this->CI->db->select('code, code_name, create_yn'); $this->CI->db->order_by('create_yn', 'desc'); $this->CI->db->order_by('pnt'); $result = $this->CI->db->get_where(TBL_SERIES, array('LENGTH(code) > '=>'9','create_yn'=>'Y', 'code like'=>$code.'%'))->result(); return $result; } //종목리스트 function get_stockitem($word=''){ $this->CI->db->select('gdnum, code, code_name, pnt, create_yn'); $this->CI->db->order_by('pnt'); if(!empty($word)){ $this->CI->db->like('code_name', $word); } $result = $this->CI->db->get_where(TBL_CODEDETAIL, array('code_group'=>'STOCK'))->result(); return $result; } //기타코드 조회 function get_t_code_detail($group){ $this->CI->db->select('code, code_name, pnt, code_name_etc'); $this->CI->db->order_by('pnt, code_name'); $result = $this->CI->db->get_where(TBL_CODEDETAIL, array('create_yn'=>'Y', 'code_group'=>$group))->result(); return $result; } //관련기사쿼리 - 기사키 및 관련기사쿼리개수 0이면 전부다 function get_relnews($idx,$limit){ $master_key = ''; $result = null; //관련기사의 마스터 키를 구함 - 자기자신이 마스터키인지 먼저 조사함 $relresult = $this->CI->db->query("select newskey from ".TBL_RELNEWS." where newskey='$idx' and rel_newskey='$idx'"); if ($relresult->num_rows() > 0) { $relrow = $relresult->row(); $master_key = $relrow->newskey; } else { $relresult->free_result(); $relresult = $this->CI->db->query("select newskey from ".TBL_RELNEWS." where rel_newskey='$idx'"); if ($relresult->num_rows() > 0) { $relrow = $relresult->row(); $master_key = $relrow->newskey; } } if ($master_key <> '') { $this->CI->db->select("rel_newskey,rel_newstitle,rel_seq,newskey"); $this->CI->db->order_by("rel_seq"); if($limit > 0) {$this->CI->db->limit($limit);} $result = $this->CI->db->get_where(TBL_RELNEWS, array('newskey'=>$master_key,'rel_newskey !='=>$idx))->result(); //자기자신 제외 } return $result; // 사용시 $relresult = $this->my_model->get_relnews($idx,0); // 결과가 없을지도 모르니 아래 if문을 씌워 수행함 // if (!is_null($relresult)) { // ... // } } //조건절로 쿼리한 한 레코드의 한 필드 값을 쿼리 function func_dbval($tbl,$fld,$wh){ $this->CI->db->select($fld); $result = $this->CI->db->get_where($tbl, $wh)->row(); if (!empty($result)) { return $result->$fld; } else { return ''; } } //조건절로 한 레코드 쿼리 function func_dbval1($tbl,$fld,$wh){ $this->CI->db->select($fld); $result = $this->CI->db->get_where($tbl, $wh)->row(); return $result; } //조건절로 레코드셋 쿼리 function func_dbvals1($tbl,$fld,$wh){ $result = null; $this->CI->db->select($fld); if($wh) {$result = $this->CI->db->get_where($tbl, $wh)->result();} else {$result = $this->CI->db->get($tbl)->result();} return $result; } //조건절로 레코드셋 배열 리턴 function func_dbvals2($tbl,$fld,$wh){ $result = null; $this->CI->db->select($fld); $result = $this->CI->db->get_where($tbl, $wh)->result_array(); return $result; } //쿼리로 한 레코드 리턴 function func_dbval_qry($qry){ $result = null; $result = $this->CI->db->query($qry)->row(); return $result; } //쿼리로 레코드셋 리턴 function func_dbvals_qry($qry){ $result = null; $result = $this->CI->db->query($qry)->result(); return $result; } //데이터 공통 입력 function func_dbinput($tbl,$in){ $result = null; $result = $this->CI->db->insert($tbl, $in); return $result; } //데이터 공통 수정 function func_dbupdate($tbl,$up,$wh){ $result = null; $result = $this->CI->db->update($tbl, $up, $wh); return $result; } //데이터 공통 삭제 function func_dbdel($tbl,$wh){ $result = null; $result = $this->CI->db->delete($tbl, $wh); return $result; } //발췌문알아내기 function func_text($key, $newstype='') { $this->CI->db->select("news_text,news_body"); $this->CI->db->from(TBL_TEXT); $this->CI->db->where("newskey",$key); $row = $this->CI->db->get()->row(); $ntext = ''; if($row){ $ntext = $row->news_text; $ntext = strip_tags($ntext); if (!$ntext) { $ntext = $row->news_body; $ntext = str_ireplace("\r\n","",$ntext); $ntext = preg_replace("/<table(.*?)<\/table>/", "", $ntext); $ntext = preg_replace("/<TABLE(.*?)<\/TABLE>/", "", $ntext); $ntext = strip_tags($ntext); } } return trim($ntext); } function func_wcmslog($id,$flag) { $query = "insert into ".TBL_WCMS_LOG." (gijaid,conn_flag,conn_date,remote_ip) values ('$id','$flag',now(),'".$_SERVER['REMOTE_ADDR']."')"; $result = mysql_query($query); //console.log($query); } //조회 조건 부서 및 본인 권한 쿼리 function func_getDepartAuthrity($loginId){ $sql = " select DEPART_TP,IFNULL(MAX(`READ_ALL`),'N') READ_ALL, IFNULL(MAX(`READ`),'N') `READ` from t_dept_group_auth DD where DD.DEPART_GROUP in (select dept_group_id from t_p_dept_auth CC where CC.gnum = (select EE.gdnum from gija_id_tbl EE where EE.gijaid = '$loginId')) group by DD.DEPART_TP having READ_ALL = 'Y' or `READ` = 'Y' "; $query = $this->CI->db->query($sql); return $query->result(); } function func_getAuthority($loginid,$mediaTbl,$orgKey,$key,$deptListStr){ $news_gija = ($mediaTbl == TBL_NEWS)? TBL_NEWSGIJA: TBL_AMEDIAGIJA; $query = $this->CI->db->query( "select IFNULL(MAX(`READ`),'N') `READ` ,IFNULL(MAX(`READ_ALL`),'N') READ_ALL ,IFNULL(MAX(`WRITE`),'N') `WRITE` ,IFNULL(MAX(`WRITE_ALL`),'N') WRITE_ALL ,IFNULL(MAX(`RELEASE`),'N') `RELEASE` ,IFNULL(MAX(`RELEASE_SECOND`),'N') `RELEASE_SECOND` ,IFNULL(MAX(`RELEASE_REQUEST`),'N') `RELEASE_REQUEST` ,IFNULL(MAX(DELETE_WRITE),'N') DELETE_WRITE ,IFNULL(MAX(DELETE_BEFORE_RELEASE),'N') DELETE_BEFORE_RELEASE ,IFNULL(MAX(DELETE_AFTER_RELEASE),'N') DELETE_AFTER_RELEASE from t_dept_group_auth DD where DD.DEPART_GROUP in (select dept_group_id from t_p_dept_auth CC where CC.gnum = (select EE.gdnum from gija_id_tbl EE where EE.gijaid = '$loginid')) and DEPART_TP in ($deptListStr) "); return $query->row(); } function func_getNewAuthority($loginid){ $query = $this->CI->db->query( "select IFNULL(MAX(`READ`),'N') `READ` ,IFNULL(MAX(`READ_ALL`),'N') READ_ALL ,IFNULL(MAX(`WRITE`),'N') `WRITE` ,IFNULL(MAX(`WRITE_ALL`),'N') WRITE_ALL ,IFNULL(MAX(`RELEASE`),'N') `RELEASE` ,IFNULL(MAX(`RELEASE_SECOND`),'N') `RELEASE_SECOND` ,IFNULL(MAX(`RELEASE_REQUEST`),'N') `RELEASE_REQUEST` ,IFNULL(MAX(DELETE_WRITE),'N') DELETE_WRITE ,IFNULL(MAX(DELETE_BEFORE_RELEASE),'N') DELETE_BEFORE_RELEASE ,IFNULL(MAX(DELETE_AFTER_RELEASE),'N') DELETE_AFTER_RELEASE from t_dept_group_auth DD where DD.DEPART_GROUP in (select dept_group_id from t_p_dept_auth CC where CC.gnum = (select EE.gdnum from gija_id_tbl EE where EE.gijaid = '$loginid')) and DEPART_TP in (select buseid from gija_id_tbl AA where AA.gijaid = '$loginid') "); return $query->row(); } } ?><file_sep><style media="screen"> .list{ text-align: center; display: inline-block; float: left; width: 45%; margin: 2.5%; overflow: hidden; text-overflow: ellipsis; white-space: normal; } .title{ position: relative; text-align: left; margin : 1px; width: 100%; line-height: 1.3; max-height: 2.6em; white-space: normal; word-wrap: break-word; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } #thumbnail{ position: relative; width: 100%; } </style> <div style="color:RGB(255,205,51);background:RGB(12,12,12);padding:10px 0px; ">매거진</div> <div class="article"style="text-align:center;"> <?php foreach ($magazines as $magazine){ ?> <div class="list" value="<?=$magazine->매거진_id?>" > <img id="thumbnail" src="<?=경로_매거진.$magazine->섬네일?>"> </div> <?php } ?> </div> <script type="text/javascript"> $(document).ready(function(){ $(".list").on("click",function(){ window.location.assign("<?=WEB_ROOT?>magazine/magazineView/"+$(this).attr("value")); })} ); </script> <file_sep><style> .pop-layer .pop-container , .pop-layer2 .pop-container, .pop-layer3 .pop-container, .pop-layer4 .pop-container { padding: 20px 25px; } .pop-layer, .pop-layer2, .pop-layer3, .pop-layer4 { display: none; background:#f2f2f2; color:#000000; position: fixed; top: 35%; left: 9%; width: 80%; height: auto; border-radius: 10px; border: 5px solid #cdcdcd; } .btn-r { height:20px; } .btn-r #ok{ position:absolute; right:60%; background-color:#ffe882; padding:8px; font-size:12px; border-radius:4px; } .btn-r #cancel{ position:absolute; left:60%; background-color:#7ec6f7; padding:8px; font-size:12px; border-radius:4px; } .pop-conts { text-align:center; } #myfriendlist { margin-top:86px; } #invitefriend{ margin-top:42px; } .list_box ul{ list-style:none; border-left:1px solid #cdcdcd; border-right:1px solid #cdcdcd; border-bottom:1px solid #cdcdcd; margin-bottom:20%; } .list_box .friend_box{ border-top:1px solid #cdcdcd; padding:10px; position:relative; } .list_box .friend_box:hover{ background-color:#f2f2f2; } .list_box .ms_bt, .accept_bt, .invite_bt { position:absolute; right:60px; top:20px; background-color:#ffe882; padding:8px; font-size:12px; border-radius:4px; } .list_box .del_bt, .reject_bt, .cancel_bt { position:absolute; right:10px; top:20px; background-color:#7ec6f7; padding:8px; font-size:12px; border-radius:4px; } .list_box .ms_bt:hover, .accept_bt:hover, .invite_bt:hover,.btn-r #ok:hover { background-color:#fff5bc; } .list_box .del_bt:hover, .reject_bt:hover, .cancel_bt:hover,.btn-r #cancel:hover { background-color:#bcefff; } .mythumb{ margin: 10px auto; width: 50px; height: 50px; overflow: hidden; display: block; border-radius: 50px; text-align: center; position:absolute; left:10px; top:0px; } .mythumb img{ width: 50px;height: 50px; } .add_btn{ z-index:100; position:fixed; background-color:#ffffff; bottom:0; width:100%; height=25%; left:0; } .add_btn .container { border:1px solid #cdcdcd; border-radius:10px; text-align:center; background-color:#cdcdcd; font-size: 15px; padding:5px; margin:10px; } .menu_tab { z-index:100; position:fixed; width:100%; top:0; text-align:center; background-color:white; } .menu_tab ul { background-color:#63483c; padding:10px 0 10px 0; margin:0; } .menu_tab ul #myfriends { display:inline; font: 18px Dotum; font-family: arial; color: #ffffff; padding:0 10px; } .menu_tab ul #invite,.menu_tab ul #messege { display:inline; border-left:1px solid #999; font: 18px Dotum; font-family: arial; color: #ffffff; padding:0 10px; } .menu_tab ul #myfriends:hover,.menu_tab ul #invite:hover,.menu_tab ul #messege:hover { font-weight:bold; } .sub_menu_tab { z-index:100; position:fixed; width:100%; top:45px; text-align:center; /*padding-left:25px;*/ background-color:white; } .sub_menu_tab ul { background-color:#63483c; padding:10px 0 10px 0; margin:0 0 20px 0; } .sub_menu_tab ul #sub_left { display:inline; font: 15px Dotum; font-family: arial; color: #ffffff; padding:0 10px; } .sub_menu_tab ul #sub_right { display:inline; border-left:1px solid #999; font: 15px Dotum; font-family: arial; color: #ffffff; padding:0 10px; } .menu_tab ul li:first-child{ border-left:none; } .list_box li{ /*border:1px solid #cdcdcd;*/ } .list_box .room_box{ border-top:1px solid #cdcdcd; padding:10px; position:relative; } .list_box .room_box:hover{ background-color:#f2f2f2; } .list_box .det2{ position:absolute; right:10px; bottom:18px; background-color:#7ec6f7; padding:8px; font-size:12px; border-radius:4px; } .list_box .det2:hover { background-color:#bcefff; } .list_box .time{ position:absolute; right:60px; top:10px; font-size:12px; color:#888; } .time .badge{ position:absolute; left:-20px; top:0px; width: 15px; height: 15px; } .mythumb2{ width: 50px; height: 50px; overflow: hidden; display: block; border-radius: 50px; text-align: center; position:absolute; left:10px; } .mythumb2 img{ width: 50px; height: 50px; } .text_over{ overflow:hidden; white-space:nowrap; text-overflow:ellipsis; font-size:15px; padding-top:10px; } .profile_box { position: absolute; width:100%; height:90%; overflow:auto; } .profile_box .profile_top { position: relative; width: 100%; height: 35%; background-color: #f2f2f2; border-top: 3px solid black; } .profile_box .profile_middle { position: relative; width: 100%; height: 15%; padding-top:10%; background-color: white; border-top: 3px solid black; text-align: -webkit-center; } .profile_middle .middle_info { float:left; width:33.33333%; height:100%; font-size:12px; } .profile_middle .sub_middle_info { position:relative; width:33%; font-size:15px; } .profile_box .profile_bottom { position: relative; width: 100%; height: 27%; background-color: white; border-top: 3px solid black; text-align: -webkit-center; } .profile_bottom .bottom_info { float:left; width:33%; height:80%; font-size:12px; } .profile_bottom .sub_bottom_info { position:relative; width:90%; height:60%; font-size:18px; } .sub_bottom_info img { width:100%; height:100%; } .profile_box .profilethumb{ width: 100px; height: 100px; overflow: hidden; border-radius: 50px; text-align: center; position:absolute; left:36%; top:20%; } .profile_box .profilethumb img{ width: 100px; height: 100px; align : center; } .profile_box .sendbtn { text-align:center; margin-left:5%; padding:10px 30px 10px 30px; border-radius: 10px; background-color:#f9c454; display:inline-block; float:left; } .profile_box .circlebtn { width: 70%; height: 90%; overflow: hidden; float:left; border-radius: 50px; text-align: center; font-size:12px; background-color:#a7f2f9; position:relative; left:35%; margin-top:3%; padding:1px; } body{margin:0px;} ul{padding:0px;} </style> <div class="total"> </div> <script> $(document).ready(function() { friendsReload(5); }); function friendsReload(idx){ <?php //페이지 이동 함수 ?> switch(idx){ case 1: $(".result").load("/friends/myFriends"); break; case 2: $(".result").load("/friends/invite"); break; case 3: $(".result").load("/friends/msCheck"); break; case 4: $(".result").load("/friends/inviteEvents"); break; case 5: $(".total").load("/friends/friendList"); break; case 6: $(".total").load("/friends/msRoom"); break; } } function changeFont(idx){ <?php //탭 클릭 시 bold 변경 함수 ?> switch(idx){ case 1: $("#myfriends").css("font-weight","bold"); $("#invite").css("font-weight",""); $("#messege").css("font-weight",""); break; case 2: $("#myfriends").css("font-weight",""); $("#invite").css("font-weight","bold"); $("#messege").css("font-weight",""); break; case 3: $("#myfriends").css("font-weight",""); $("#invite").css("font-weight",""); $("#messege").css("font-weight","bold"); break; case 4: $("#myfriends").css("font-weight",""); $("#invite").css("font-weight","bold"); $("#messege").css("font-weight",""); $(".sub_menu_tab #sub_left").css("font-weight","bold"); $("#sub_right").css("font-weight",""); break; case 5: $("#myfriends").css("font-weight",""); $("#invite").css("font-weight","bold"); $("#messege").css("font-weight",""); $(".sub_menu_tab #sub_left").css("font-weight",""); $("#sub_right").css("font-weight","bold"); break; } } </script><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User_model extends CI_Model{ function __construct(){ parent::__construct(); $this->load->helper('date'); } /* * pwCheck * 이소희 * 20170314 * 비밀번호 일치 여부 */ function pwCheck($user_id,$password){ $this->db->select("count(*) cnt"); $this->db->from("사용자"); $this->db->where("사용자_id",$user_id); $this->db->where("암호",$password); return $this->db->get()->row()->cnt; } /* * deleteInfo * 이소희 * 20170314 * 회원 탈퇴 */ function deleteInfo($user_id,$reason,$etc){ $this->db->set("이름",null); $this->db->set("암호",null) ; $this->db->set("e-mail",null); $this->db->set("성별",null); $this->db->set("핸드폰",null); $this->db->set("사진",null); $this->db->set("탈퇴코드",$reason); //기타가 아닐 경우 if($etc==null){ $this->db->set("탈퇴사유",null); }else{ $this->db->set("탈퇴사유",$etc); } $this->db->where("사용자_id",$user_id); echo $this->db->update('focus_walk.사용자'); } /* * userInfo * 이소희 * 20170315 * 회원정보 확인 */ function userInfo($user_id){ $this->db->select("사용자_id, 이름, e-mail as email, 성별, 주소, 사진 "); $this->db->from("사용자"); $this->db->where("사용자_id",$user_id); return $this->db->get()->row(); } /* * newPwSet * 이소희 * 20170315 * 비밀번호 재설정 */ function newPwSet($user_id, $pw){ $this->db->set("암호",$pw); $this->db->where("사용자_id",$user_id); echo $this->db->update('focus_walk.사용자'); } /* * loginCheck * 이소희 * 20170330 * 로그인체크 (대회이름, 종료일시, 사용자_id, 이름, 참여중대회_id, cnt, logged_in 정보를 가지고옴) */ function loginCheck($user_id,$password){ $this->db->select("제목 as 대회이름,종료일시,사용자.사용자_id as user_id, 사용자.이름 as name, 사용자.참여중대회_id as contest_id, count(*) cnt"); $this->db->from("걷기대회_참가자"); $this->db->join("걷기대회","걷기대회_참가자.걷기대회_id=걷기대회.걷기대회_id and 걷기대회_참가자.완보여부='N'","",FALSE); $this->db->join("사용자","걷기대회_참가자.사용자_id = 사용자.사용자_id","right outer",FALSE); $this->db->where("사용자.사용자_id",$user_id); $this->db->where("사용자.암호",$password); return $this->db->get()->row(); } /* * checkPhone * 이소희 * 20170322 * 아이디 찾기 - 휴대폰 유무 확인 */ function checkPhone($name,$phone){ $this->db->select("count(*) cnt"); $this->db->from("사용자"); $this->db->where("이름",$name); $this->db->where("핸드폰",$phone); return $this->db->get()->row()->cnt; } /* * insertCode * 이소희 * 20170317 * 인증번호 생성 + 인증번호 요청 시간 update 추가 */ function insertCode($name,$phone,$rand_num){ $this->db->set("인증번호",$rand_num); $this->db->set("인증번호요청시간", date("Y-m-d-h:m:s",time())); $this->db->where("이름",$name); $this->db->where("핸드폰",$phone); return $this->db->update('focus_walk.사용자'); } /* * checkCode * 이소희 * 20170316 * 인증번호 일치 여부 확인 (아이디 찾기 일 때는 이름으로) */ function checkCode($name,$phone,$code){ $this->db->select("count(*) cnt"); $this->db->from("사용자"); $this->db->where("이름",$name); $this->db->where("핸드폰",$phone); $this->db->where("인증번호",$code); return $this->db->get()->row()->cnt; } /* * findId * 이소희 * 20170316 * 아이디 찾기 */ function findId($name,$phone){ //$this->db->select("사용자_id, DATE_FORMAT('가입일', '%Y-%m-%d') AS 가입일"); $this->db->select("사용자_id, 가입일"); $this->db->from("사용자"); $this->db->where("이름",$name); $this->db->where("핸드폰",$phone); return $this->db->get()->row(); } /* * checkCode2 * 이소희 * 20170317 * 인증번호 일치 여부 확인 */ function checkCode2($user_id,$code){ $this->db->select("count(*) cnt"); $this->db->from("사용자"); $this->db->where("사용자_id",$user_id); $this->db->where("인증번호",$code); return $this->db->get()->row()->cnt; } /* * checkIdPhone * 이소희 * 20170322 * 비밀번호 찾기 - 아이디, 휴대폰 유무 확인 */ function checkIdPhone($id, $phone){ $this->db->select("count(*) cnt"); $this->db->from("사용자"); $this->db->where("사용자_id",$id); $this->db->where("핸드폰",$phone); return $this->db->get()->row()->cnt; } /* * insertCode2 * 이소희 * 20170320 * 인증번호 생성 (아이디로 인증번호 생성) */ function insertCode2($id, $phone, $rand_num){ $this->db->set("인증번호",$rand_num); $this->db->set("인증번호요청시간", date("Y-m-d-h:m:s",time())); $this->db->where("사용자_id",$id); $this->db->where("핸드폰",$phone); return $this->db->update('focus_walk.사용자'); } /* * newPwSet2 * 이소희 * 20170320 * 비밀번호 재설정 (아이디로) */ function newPwSet2($user_id, $pw){ $this->db->set("암호",$pw); $this->db->where("사용자_id",$user_id); echo $this->db->update('focus_walk.사용자'); } /* * adsChange * 이소희 * 20170322 * 휴대폰 재설정 (아이디로) */ function adsChange($user_id, $newAdd){ $this->db->set("주소",$newAdd); $this->db->where("사용자_id",$user_id); return $this->db->update('focus_walk.사용자'); } } <file_sep><div align="center" style="z-index:100;top:45px;position:fixed;width:100%;padding:10px 0 10px 0;background-color:white;"> 현재 등록된 친구는 <b><?=$friendcnt?></b>명 입니다. </div> <div class="list_box" id="myfriendlist"> <form action="/friends/msRoomOther/" method="POST" id="form"> <input type="hidden" id="friend_id" name="friend_id" value=""/> </form> <ul> <?php foreach($friendIds as $friendId ) { ?> <li> <div class="friend_box" name="<?=$friendId->친구_id?>"> <div class="friendsInfo" style="width:65%; height:100%;"> <div class="mythumb"><img src="<?=경로_사용자?><?=$friendId->사진?>" alt=""></div> <div class="userName" style="padding:15px 0px;padding-left:70px;"><?=$friendId->이름?></div> </div> <div class="ms_bt" onclick="ms_bt_click('<?=$friendId->친구_id?>')">쪽지</div> <div class="del_bt">삭제</div> </div> </li> <?php } ?> </ul> <div id="pop_delete" class="pop-layer"> <div class="pop-container"> <div class="pop-conts"> <p>친구 삭제 </p> <p class="ctxt mb20"></p> <div class="btn-r"> <div id="ok">확인</div> <div id="cancel">취소</div> </div> </div> </div> </div> </div> <div class="add_btn"> <div class="container">친구 추가 및 초대</div> </div> <script> $(document).ready(function() { var name_id_tmp = ""; var name_name_tmp = ""; $('.del_bt').click(function(){ <?php //삭제버튼 클릭 ?> name_id_tmp = $(this).parent().attr("name"); name_name_tmp = $(this).parent().find(".userName").html(); $('#pop_delete').show(); $('.ctxt').text(name_name_tmp+" 친구를 삭제하시겠습니까?"); }); $('.pop-layer #cancel').click(function() { <?php //삭제 시 팝업레이어의 취소 클릭 ?> $('#pop_delete').hide(); }); $('.pop-layer #ok').click(function() { <?php //삭제 시 팝업레이어의 확인 클릭 ?> $('#pop_delete').hide(); $.ajax({ type:"POST", url: "/friends/deleteFriends", dataType:"text", data:{ "friend_id" : name_id_tmp }, success: function(result){ friendsReload(1); },error: function(result){ alert("오류가 발생했습니다."); } }); }); $('.friendsInfo').click(function(){ <?php // 프로필 영역 클릭(친구정보 화면으로 이동)?> name_id_tmp=$(this).parent().attr("name"); $.ajax({ type:"POST", url: "/friends/friendsInfo", dataType:"text", data:{ "friend_id" : name_id_tmp }, success: function(result){ $(".result").html(result); },error: function(result){ alert("오류가 발생했습니다."); } }); }); }); function ms_bt_click(id){ <?php //post방식으로 파라미터 넘겨주기 위한 함수 ?> $("#friend_id").val(id); $("#form").submit(); } </script><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Content_model extends CI_Model{ function __construct(){ parent::__construct(); } /* * 홍익표 * 20170330 * wish 정보 조회 * $id wish id */ function getWishInfo($user_id,$id){ $this->db->set("참여위시",$id); $this->db->where("사용자_id",$user_id); $this->db->update("사용자"); $this->db->select('*'); $this->db->from('위시'); $this->db->where("위시_id",$id); return $this->db->get()->row(); } /* * 홍익표 * 20170331 * wish 스템프 발행 * $id wish id */ function issueWish($user_id){ $this->db->select('참여위시'); $this->db->from('사용자'); $this->db->where("사용자_id",$user_id); $row = $this->db->get()->row(); if(count($row) < 1 || $row->참여위시 < 1){ $result["result"] = false; $result["message"] = "참여 Wish가 없습니다."; return $result; } $this->db->select('count(*) cnt'); $this->db->from('위시_스템프'); $this->db->where("사용자_id",$user_id); $this->db->where("위시_id",$row->참여위시); $cnt = $this->db->get()->row()->cnt; if($cnt > 0){ $result["result"] = false; $result["message"] = "이미 스템프룰 획득한 Wish입니다."; return $result; } $this->db->set("위시_id",$row->참여위시); $this->db->set("사용자_id",$user_id); $this->db->set("스탬프획득일시","now()",FALSE); $ret = $this->db->insert("위시_스템프"); if($ret == FALSE){ $result["result"] = false; $result["message"] = "스템프 발행 중 에러가 발생 했습니다."; return $result; } $result["result"] = true; $result["message"] = "스템프가 발행 되었습니다."; return $result; } /* * 홍익표 * 20170331 * Mission 정보 조회 * $id wish id */ function getMissionInfo($user_id,$id){ $this->db->set("참여미션",$id); $this->db->where("사용자_id",$user_id); $this->db->update("사용자"); $this->db->select('*'); $this->db->from('미션'); $this->db->where("미션_id",$id); return $this->db->get()->row(); } /* * 홍익표 * 20170331 * 경품 추첨권 * $id wish id */ function issueMission($user_id){ $this->db->select('참여미션'); $this->db->from('사용자'); $this->db->where("사용자_id",$user_id); $row = $this->db->get()->row(); if(count($row) < 1 || $row->참여미션 < 1){ $result["result"] = false; $result["message"] = "참여 미션이 없습니다."; return $result; } $this->db->select('count(*) cnt'); $this->db->from('경품추첨권'); $this->db->where("사용자_id",$user_id); $this->db->where("분류","MISSION"); $this->db->where("분류_id",$row->참여미션); $cnt = $this->db->get()->row()->cnt; if($cnt > 0){ $result["result"] = false; $result["message"] = "이미 경품추첨권을 받은 미션 입니다."; return $result; } $this->db->set("분류","MISSION"); $this->db->set("사용자_id",$user_id); $this->db->set("분류_id",$row->참여미션); $this->db->set("획득일","now()",FALSE); $ret = $this->db->insert("경품추첨권"); if($ret == FALSE){ $result["result"] = false; $result["message"] = "경품추첨권 발행 중 에러가 발생 했습니다."; return $result; } $result["result"] = true; $result["message"] = "경품추첨권이 발행 되었습니다."; return $result; } /* * 정수영 * deleteWishStamp * 사용자_id와 사용자가 참여중인 대회_id를 받아오면, 위시_스템프 테이블에서 해당 위시_id에 해당하는 기록들을 삭제한다. */ function deleteWishStamp($user_id, $event_id){ $sql = " delete A from 위시 B, 위시_스템프 A where B.걷기대회_id='".$event_id."' and A.사용자_id='".$user_id."' and A.위시_id=B.위시_id"; return $this->db->query( $sql )->result(); } /* * 정수영 * deleteWishStamp * 사용자_id와 사용자가 참여중인 대회_id를 받아오면, 미션_수행 테이블에서 해당 미션_id에 대당하는 기록들을 삭제한다. */ function deleteMissionState($user_id, $event_id){ $sql = "delete A from 미션 B, 미션_수행 A where B.걷기대회_id='".$event_id."' and A.사용자_id='".$user_id."' and A.미션_id=B.미션_id"; return $this->db->query( $sql )->result(); } } ?> <file_sep><style> .faQ{ border-bottom:1px solid black; padding :10px; } </style> <div> <?php foreach($faqs as $faq){?> <div class="faQ"> <?= $faq->글제목 ?> <div class="cbutton" style="float:right;"> &#8681; </div> </div> <div class="faA" style="display:none" value="<?= $faq->글내용 ?>"> </div> <?php } ?> </div> <script> $(document).ready(function(){ $(".cbutton").each(function(idx){ $(this).click(function(){ }); }); }); </script><file_sep> <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_function { public function __construct(){ $this->CI =& get_instance(); } //URL 세그먼트 전체 값 설정 public function get_segment(){ if ($this->CI->uri->segment(6)){ $arrSegment = $this->CI->uri->uri_to_assoc(6); $segment_str = $this->CI->uri->assoc_to_uri($arrSegment); }else{ $segment_str = ''; } return $segment_str; } //URL 세그먼트 전체 값 설정 //문자열자르기 //예 : encode_substr($org_str,0,$length,'utf-8'); function encode_substr($str,$start,$end,$encoding){ mb_internal_encoding($encoding); $str_len = mb_strlen($str); if($end<$str_len){$str = trim(mb_substr($str,$start,$end))."..";} else{$str = mb_substr($str,$start,$end);} return $str; } //문자열자르기 .. 없음 function encode_substr_nd($str,$start,$end,$encoding){ mb_internal_encoding($encoding); $str_len = mb_strlen($str); if($end<$str_len){$str = trim(mb_substr($str,$start,$end));} else{$str = mb_substr($str,$start,$end);} return $str; } //자바스크립트용 타이틀 function title_js($tit) { $tit = str_replace("'","`",$tit); $tit = str_replace("\"","``",$tit); $tit = str_replace("\n","",$tit); return $tit; } function make_dir($dir){ if(!is_dir($dir)){ @umask(0000); @mkdir($dir, 0777, true); @chmod($dir, 0777); } } //조회 조건 부서 및 본인 권한 쿼리 function func_getDepartAuthrity($loginId){ return $this->CI->my_model->func_getDepartAuthrity($loginId); } //권한 조회 function getAuthority($loginid, $loginbuse, $key){ $levelGroup = '1'; $authoritys = array(); $mediaTbl = ''; $orgKey = ''; $isConfirm = FALSE; //버튼 권한 $isSave = FALSE; $isModifyOrder = FALSE; //수정요청 $isConfirmRequest = FALSE; //승인요청 $isModifyComplete = FALSE; //수정완료 $isReleaseRequest = FALSE; //출고요청 $isRelease = FALSE; //출고버튼 $isDelete = FALSE; //삭제 //복원 및 삭제 $isRestore = FALSE; $isPerfectDelete = FALSE; $isSelf = FALSE; $isHold = FALSE; //20160523 본인이거나 데스크 이상이면 수정가능하게 변경 $isMediaModify = FALSE; //기사정보 $confirm = '0'; $create_id = $loginid; $byline_gijaid = $loginid; $service_tf = '1'; $webnews_type = $loginbuse; if(substr($key, 8, 2) == "00"){ $mediaTbl = TBL_NEWS; $orgKey = "newskey"; }else{ $mediaTbl = TBL_AMEDIA; $orgKey = "mediakey"; } $newsInfo = $this->CI->my_model->func_dbval1($mediaTbl, '*', array($orgKey=>$key)); //기사정보 확인 if(!empty($newsInfo)){ if($newsInfo->first_releasedate != '' && strlen($newsInfo->first_releasedate) == 19){ $isConfirm = TRUE; //재출고 확인 } $deptListStr = ""; $deptLists = explode(';', $newsInfo->byline_buseid); for($i=0;$i<count($deptLists);$i++){ if( strlen(trim($deptLists[$i])) > 0 ){ if($deptListStr == "") $deptListStr = "'".trim($deptLists[$i])."'"; else $deptListStr .= ",'".trim($deptLists[$i])."'"; } } $userAuthority = $this->CI->my_model->func_getAuthority($loginid,$mediaTbl,$orgKey,$key,$deptListStr); $confirm = $newsInfo->confirm; $create_id = $newsInfo->create_id; $byline_gijaid = $newsInfo->byline_gijaid; $service_tf = $newsInfo->service_tf; $webnews_type = $newsInfo->webnews_type; //본인 여부 확인 if($create_id == $loginid || stripos($byline_gijaid, $loginid.';') !== FALSE){ $isSelf = TRUE; } if($service_tf == '1'){//정상 기사 //출고 버튼 if((substr($key, 8, 2) == "01" || substr($key, 8, 2) == "04") && stripos($loginbuse, 'L') === FALSE){ //사진 사진첩 모두 출고 가능 단 지역기자는 없음 $isRelease = TRUE; } if($userAuthority->RELEASE == "Y") $isRelease = TRUE; else if($userAuthority->RELEASE_SECOND == "Y" && ($isConfirm && ($confirm == '1' || $confirm == '4' || $confirm == '5'))) $isRelease = TRUE; //승인 요청 //수정 완료 //저장 버튼 if($userAuthority->WRITE_ALL == "Y" || ($userAuthority->WRITE == "Y" && $isSelf)){ $isMediaModify = TRUE; if($confirm == '0' || $confirm == '2'){ //작성중, 승인요청 상태 $isConfirmRequest = TRUE; }else if($confirm == '4'){ //수정지시 상태 $isModifyComplete = TRUE; } if($confirm != '1' && $confirm != '6') $isSave = TRUE; } //수정 요청 if($userAuthority->RELEASE == "Y" || $userAuthority->RELEASE_SECOND == "Y"){ //출고권이 있는 사람 $levelGroup = '3'; //HIP 20151030 출고된 기사 수정이 안 보여서 출고 가능한 사람은 보이게 수정 $isSave = TRUE; if($confirm != '0') $isModifyOrder = TRUE; } //수정 요청 //출고 요청 if($userAuthority->RELEASE_REQUEST == "Y"){ //해당 부서에 출고 요청 권한이 있는경우 $levelGroup = '2'; if($confirm != '1') //출고요청 $isReleaseRequest = TRUE; if($confirm != '0'){ //수정 요청 $isModifyOrder = TRUE; } } //삭제 버튼: if($userAuthority->DELETE_AFTER_RELEASE == "Y") $isDelete = TRUE; else if($userAuthority->DELETE_BEFORE_RELEASE == "Y" && $confirm != '1' && !$isConfirm) $isDelete = TRUE; else if($userAuthority->DELETE_WRITE == "Y" && $confirm == '0' && $isSelf ) //작성 중인 기사는 삭제는 본인것만 가능 $isDelete = TRUE; else if($userAuthority->RELEASE_REQUEST == "Y" && $confirm == '2') //출고 요청자는 승인요청 기사에 대해 삭제 버튼 나옴 $isDelete = TRUE; }else{//삭제기사 복원, 완전삭제 if($userAuthority->DELETE_AFTER_RELEASE == "Y" || $userAuthority->DELETE_BEFORE_RELEASE == "Y"){ //삭제 권한이 있는 사람은 복원 가능 : 필요시 분기 $isRestore = TRUE; $isPerfectDelete = TRUE; } } }else{//신규기사 버튼 //저장 버튼 $userAuthority = $this->CI->my_model->func_getNewAuthority($loginid); $isSave = true; if($userAuthority->RELEASE == "Y"){ $isRelease = TRUE; } //승인 요청 if($userAuthority->WRITE_ALL == "Y" || ($userAuthority->WRITE == "Y")){ $isConfirmRequest = TRUE; } //출고 요청 if($userAuthority->RELEASE_REQUEST == "Y"){ //해당 부서에 출고 요청 권한이 있는경우 $isReleaseRequest = TRUE; } } $authoritys["levelGroup"] = $levelGroup; $authoritys["isSave"] = $isSave; $authoritys["isConfirmRequest"] = $isConfirmRequest; $authoritys["isModifyOrder"] = $isModifyOrder; $authoritys["isModifyComplete"] = $isModifyComplete; $authoritys["isReleaseRequest"] = $isReleaseRequest; $authoritys["isRelease"] = $isRelease; $authoritys["isDelete"] = $isDelete; $authoritys["isRestore"] = $isRestore; $authoritys["isPerfectDelete"] = $isPerfectDelete; $authoritys["isHold"] = $isHold; $authoritys["isMediaModify"] = $isMediaModify; return $authoritys; } //로그인 여부 확인 function login_check($loginId){ $result = array("isLogin"=>TRUE, "msg"=>'', "url"=>''); if($loginId == '' || $loginId == FALSE || $loginId == '0'){ //if(TRUE){ $result["isLogin"] = FALSE; $result["msg"] = "로그인 시간이 만료되었습니다.<br>다시로그인해주시기 바랍니다."; $result["url"] = HTTPS_WCMSPATH."auth/login"; } return $result; } } ?> <file_sep><?php class Session_common { public function __construct(){ $this->CI =& get_instance(); } /* * setSession * 이소희 * 20170330 * DB 결과를 세션에 저장 */ function setSession($sesName, $user){ $user_array = get_object_vars($user); $user_array['logged_in'] = True; $this->CI-> session -> set_userdata($sesName,$user_array); } /* * changeSession * 이소희 * 20170330 * 세션 일부분 수정 */ function changeSession($sesName, $key, $value){ $session_data = $this->CI->session->userdata($sesName); $session_data[$key] = $value; $this->CI->session->set_userdata($sesName,$session_data); } /* * getSession * 이소희 * 20170320 * 세션에 있는 정보 가져오기 */ function getSession($key){ $session_data = $this->CI->session->userdata($key); return $session_data; } /* * checkSession * 이소희 * 20170322 * 세션에 있는 정보 가져오기 */ function checkSession($key){ if(!$this-> getSession($key)){ header("Location: /user/loginIndex"); }else{ return true; } } /* * logout * 이소희 * 20170320 * 세션 종료 */ function logout(){ if (!isset($_SESSION)){ session_start(); } $this->CI->session->unset_userdata('user'); session_destroy(); } } ?>
3ee2ead7be7c69d00dfff0ad69a643a3f7a94be2
[ "JavaScript", "PHP" ]
113
PHP
CHOIJAESEONG/WalkApp
5b987fc2e198d176eacc85c5959a945d75de9953
89333718e2e5d399813b913515f175de6a04876c
refs/heads/master
<repo_name>brelian/sapui5-walkthrough<file_sep>/src/com/0x400/demo/controller/InvoiceList.controller.js sap.ui.define([ "sap/ui/core/mvc/Controller", "sap/ui/model/json/JSONModel", "../formatter/InvoiceFormatter", "sap/ui/model/Filter", "sap/ui/model/FilterOperator" ], function (Controller, JSONModel, InvoiceFormatter, Filter, FilterOperator) { return Controller.extend("com.0x400.demo.controller.InvoiceList", { formatter: InvoiceFormatter, onInit: function () { var oModel = new JSONModel({ currency: "ERU" }); this.getView().setModel(oModel, "root"); }, onFilterInvoices: function (oEvent) { var aFilter = []; var sQuery = oEvent.getParameter("query"); if (sQuery) { aFilter.push(new Filter("ProductName", FilterOperator.Contains, sQuery)); } var oList = this.byId("invoiceList"); var oBinding = oList.getBinding("items"); oBinding.filter(aFilter); }, onPress: function (oEvent) { var oItem = oEvent.getSource(); var oContext = oItem.getBindingContext("invoice"); var invoicePath = oContext.getPath().substr(1); var oRouter = sap.ui.core.UIComponent.getRouterFor(this); oRouter.navTo("detail", { invoicePath: window.encodeURIComponent(invoicePath) }); } }); }); <file_sep>/src/com/0x400/demo/controller/HelloPanel.controller.js sap.ui.define([ "sap/ui/core/mvc/Controller", "sap/m/MessageToast", ], function (Controller, MessageToast) { return Controller.extend("com.0x400.demo.controller.App", { onSayHello: function () { var oBundle = this.getView().getModel("i18n").getResourceBundle(); var oModel = this.getView().getModel(); var lastName = oModel.getProperty("/recipient/lastName"); var firstName = oModel.getProperty("/recipient/firstName"); var sMsg = oBundle.getText("helloMsg", [firstName, lastName]); MessageToast.show(sMsg); }, onOpenDialog: function () { this.getOwnerComponent().openHelloDialog(); }, }) }); <file_sep>/README.md ## 项目启动 ```shell git clone https://github.com/brelian/sapui5-walkthrough.git cd sapui5-walkthrough npm run proxy & # 启动代理,处理 CORS 问题 npm start ``` 查阅 Git 提交记录 https://github.com/brelian/sapui5-walkthrough/commits/master 没次提交对应 Walkthrough 的一个步骤。 ## 学习笔记 SAPUI5 开发环境: 三种环境: SAP Web IDE / OpenUI5 / Node.js OpenUI5 https://github.com/SAP/openui5-sample-app 1. 引入 UI5 2. 配置启动 3. Hello world ### manifest.json 配置 创建项目, ```shell $ mkdir -p sapui5/walkthrough $ cd sapui5/walkthrough $ yarn init -y yarn init v1.22.4 warning The yes flag has been set. This will automatically answer yes to all questions, which may have security implications. success Saved package.json Done in 0.05s. $ mkdir -p src/com/0x400/demo ``` 在项目入口路径 `src/com/0x400/demo` 下创建 `manifest.json` 配置文件, *manifest.json* ```json { "_version": "1.0.0", "sap.app": { "id": "com.0x400.demo", "type": "application" } } ``` 其中 id 表示【??待补充】 ### 创建启动文件 - index.html 在项目入口路径 `src/com/0x400/hello` 下创建 `index.html` 文件, *index.html* ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Quickstart Tutorial</title> <script id="sap-ui-bootstrap" src="resources/sap-ui-core.js" data-sap-ui-theme="sap_belize" data-sap-ui-libs="sap.m" data-sap-ui-resourceroots='{"com.0x400.demo": "./"}' data-sap-ui-onInit="module:com/0x400/demo/hello" data-sap-ui-compatVersion="edge" data-sap-ui-async="true"> </script> </head> <body class="sapUiBody" id="content"></body> </html> ``` `src="resources/sap-ui-core.js"` 使用相对路径引入 `sap-ui-core.js`,也就说项目启动后会在 http://\<host>:\<port>/resources/ 下找到 `sap-ui-core.js`,这是由 `ui5` 完成的。 `data-sap-ui-resourceroots='{"com.0x400.demo": "./"}'` 是将命名空间 `com.0x400.demo` 和当前的相对路径 `./` 进行映射。 【??? 待补充】 `data-sap-ui-onInit="module:com/0x400/demo/hello"` 指定启动文件是当前目录下的 `hello.js`。`com/0x400/demo` 是命名空间 `com.0x400.demo` 的路径表示,最终指向的是 `./` 路径。 创建 `hello.js` 文件, *hello.js* ```js sap.ui.define([ "sap/m/Button", "sap/m/MessageToast" ], function(Button, MessageToast) { new Button({ text: "Ready...", press: function () { MessageToast.show("Hello World"); } }).placeAt("content"); }); ``` ### 使用 ui5 加载依赖 ```shell $ npm install --global @ui5/cli ``` 创建 `ui5.yaml` 文件用于配置项目启动选项, ```shell $ ui5 init ``` 编辑 `ui5.yaml` ,确认项目类型为 `application`, 使用 `resources` 配置项目的启动路径, *ui5.yaml* ```yaml ... type: application resources: configuration: paths: webapp: src/com/0x400/demo ... ``` 使用 `ui5` 加载 SAPUI5 的核心文件和 `index.html` 中用到主题和 libs ```shell $ ui5 use sapui5@latest $ ui5 add sap.ui.core sap.m themelib_sap_belize ``` 在官网 https://sapui5.hana.ondemand.com/ 可以查阅 SAPUI5 的版本列表,选择其中一个版本安装。 ### 启动 在 `scripts` 中添加启动脚本 `start: ui5 server`。 *package.json* ```json { "name": "sapui5-walkthrough", "version": "1.0.0", "main": "index.js", "license": "MIT", "scripts": { "start": "ui5 serve" } } ``` 运行 `npm start` 启动项目。 ### Git 提交 ```shell $ git init ``` 创建 `.gitignore` 文件并添加如下内容, *.gitignore* ```shell # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Dependency directories node_modules/ dist/ .idea/ ``` 创建提交记录: ```shell $ git add . $ git commit -m "feat: ramp up sapui5" ``` ## 笔记 使用 ui5 安装 libs ```shell $ ui5 add sap.ui.layout sap.tnt ``` `sap.core.mvc.View` `sap.m.App` `sap.m.Page` `sap.m.layout` XML Views - View 的名字大写开头 - 所有 View 都放在 view 目录下 - XML View 以 `.view.xml` 结尾 - View 的默认命名空间为 `sap.m` - 其他命名空间一般以最后一部分作为别名,如 mvc => sap.ui.core.mvc 【sap.ui.define ??】 sap.ui.define 用于定义 JS 模块,所定义的模块遵循 AMD 模块化标准。 Step 7: 使用 `"{/recipient/name}"` 绑定根 Model 的数据。`{...}` 表示渲染的数据来自 Model 中,这也叫做数据绑定。 ```shell <Input value="{/recipient/lastName}" description="Hello {/recipient/lastName}" valueLiveUpdate="true" width="30%" /> ``` 普通的数据绑定属性的值只能包含绑定模式 (binding pattern) ,如果想要除了绑定模式之外还支持其他内容填充,则需要开启兼容模式。即在 `index.html` 中添加 `data-sap-ui-compatVersion="edge"` Step 8: 所有的 Model 都由 getProperty 方法,用于取对应路径的值。通过调用 ResourceModel 的 `getResourceBundle` 方法取得 resouce bundle。 resouce bundle 提供 getText 方法,其中第二个参数是一个字符串类型的数组,用于替换资源文件中的 `{0} {1} {2} ...` 。 如 ```js onSayHello: function () { var oBundle = this.getView().getModel("i18n").getResourceBundle(); var oModel = this.getView().getModel(); var lastName = oModel.getProperty("/recipient/lastName"); var firstName = oModel.getProperty("/recipient/firstName"); var sMsg = oBundle.getText("helloMsg", [firstName, lastName]); MessageToast.show(sMsg); } ``` Step 9: Component Configuration - ComponentContainer - UIComponent UIComponent 通过 metedata.rootView 指定 rootView,也可以在 `manifest.json` 配置 rootView ,然后创建 Component 时开启 `manifest: true` 选项。 *manifest.json* ```json ... "sap.ui5": { "_version": "1.0.1", "rootView": { "viewName": "com.0x400.demo.view.App", "type": "XML", "async": true, "id": "app" } } ... ``` *index.js* ```js sap.ui.define([ "sap/ui/core/ComponentContainer" ], function (ComponentContainer) { "use strict"; new ComponentContainer({ name: "com.0x400.demo", manifest: true, async: true }).placeAt("content"); }); ``` Step 10: Descriptor for Applications 将应用的配置统一放入 `manifest.json` 文件中,配置和业务代码分离,使得应用更加灵活。`manifest.json` 分为如下几个部分: **sap.app** - `id` (mandatory): 应用的**命名空间**, 和 `index.html` 中的 resourceroots` 一致。 - `type`: 应用的类型,可以是 libary, application 等。 - `i18n`: resource bundle 的路径, 我理解是 default??? 【待确认??】 - `title`: 应用名字,使用 `{{your-title-key}}` 从 resource bundle 中引入 - `description`: 应用描述 - `applicationVersion`: 应用版本 **sap.ui** - `technology`: ??【待确认】 - `deviceTypes`: 适配的设备类型,一般而言 desktop, tablet, phone 都默认适配。 **sap.ui5** - `rootView`: 配置 rootView, Component 会默认加载该配置所指向的 view。 - `dependencies`: 项目依赖,【待确认 libs】 - `models`: 该属性可以定义全局的默认加载的 model,一般用于自动加载 i18n model。 key 为 model 的名字,使用命名空间定义 model 的加载路径。如 `"bundleName": "com.0x400.demo.i18n.i18n"` 表示在 `com/0x400/demo/i18n/` 下查找 `i18n.properties` 文件作为 resource model 加载的文件资源。 使用 `sap.ui.core.ComponentSupport` Step 11: Pages and Panels ```xml <App> <pages> <Page title="{i18n>pageTitle}"> <content> <Panel headerText="{i18n>helloPanelTitle}"> <content> <Button text="{i18n>showHelloButtonText}" /> </content> </Panel> </content> </Page> </pages> </App> ``` 小写为 aggregations,大写为组件。如 pages 是 sap.m.App 的一个 0...n 的 aggregation。 sap.m.Page 和 sap.m.Panel 都由一个 0...n 的 aggregation, 0...n 表示可以聚合多个控件。`displayBlock` 用于矫正全屏时候的高度。 Step 12: Shell 使用 Shell 作为最外层容器,宽屏显示时 Shell 会自动缩放成一个“信封”样式。 Step 12: Margins and Paddings 使用 SAPUI5 提供的默认 CSS 标准类,`sapUiResponsiveMargin`,`sapUiSmallMarginEnd`, `sapUiSmallMargin` 自动调节 Margins 和 Paddings。 `sapUiResponsiveMargin` 会随着窗口大小的改变而自适应调整 Margin。 Step 13: 自定义 CSS *manifest.json* ```shell "sap.ui5": { ... "models": { ... }, "resources": { "css": [ { "uri": "css/style.css" } ] } }, ... ``` 使用 resources 指定自定义 css 的路径,自定义的 css 可以有很多个,所以 css 是一个数组。 Step 15: 嵌套的 Views 将 Panel 拆分成一个 View,并在 App.view.xml 中引入 ```js <mvc:XMLView viewName="sap.ui.demo.walkthrough.view.HelloPanel"/> ``` Step 16: Dialogs and Fragments Fragments 是一些可复用的组件,这些组件没有 Controller。 使用`sap.ui.core.FragmentDefinition` 定义 Fragment,如 ```xml <core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" > <Dialog id="helloDialog" title="Hello {/recipient/name}"> </Dialog> </core:FragmentDefinition> ``` 在 HelloPanel.view.xml 中有个 Button,点击时会弹出对话框, ```xml <Button id="helloDialogButton" text="{i18n>openDialogButtonText}" press=".onOpenDialog" class="sapUiSmallMarginEnd"/> ``` 在 HelloPanel.controller.js 中定义 onOpenDialog 方法用于打开对话框, ```js ... onOpenDialog: function () { var oView = this.getView(); if(!this.byId("helloDialog")) { Fragment.load({ id: oView.getId(), name: "com.0x400.demo.view.HelloDialog" }).then(function (oDialog) { oView.addDependent(oDialog); oDialog.open(); }); } else { this.byId("helloDialog").open(); } } ... ``` 该方法中使用 sap.ui.core.Fragment 加载相应的 fragments。通过 `oView.addDependent(oDialog)` 将 Dialog 和 View 进行连接,从而使得定义 Dialog 的 Fragments 中可以读到 oView 上的 Model 完成数据绑定。 Step 17: Fragments callbacks ```js Fragment.load({ id: oView.getId(), name: "com.0x400.demo.view.HelloDialog", controller: this }); ``` 加载 fragments 时,使用 controller 参数传递 fragments 的 controller。(因为 fragments 没有特定的 controller)。 Steps 18: Icons 使用 sap.ui.core.Icon 引入 SAPUI5 内置的 icon, 通过设置 src 属性为 `sap-icon://<iconname>` 选择要引入的 Icon。请查阅 [Icon Explore](https://sapui5.hana.ondemand.com/test-resources/sap/m/demokit/iconExplorer/webapp/index.html) 找到你想要的 Icon。 Step 19: Reuse Dialogs 目前我们将 Dialog 抽离出来了,Dialog 的用户交互事件仍然在 App.controller 中处理。如果想要在别的地方复用这个 Dialog 那么就必须再次将用户交互逻辑拷贝到相应的 Controller 中,这导致了大量的代码冗余。为了更好的复用 Dialog,我们可以将这部分公共的用户交互逻辑提升到 Component 一级。 Step 20: Aggregation bindings 在 manifest.json 中添加一个 JSONModel invoice, *manifest.json* ```json "invoice": { "type": "sap.ui.model.json.JSONModel", "uri": "model/Invoices.json" } ``` 其中 uri 指向的是相对于 Component 的资源路径。 创建一个 InvoiceList.view.xml, *view/InvoiceList.view.xml* ```xml <mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc"> <List headerText="{i18n>invoiceListTitle}" class="sapUiResponsiveMargin" width="auto" items="{invoice>/Invoices}" > <items> <ObjectListItem title="{invoice>Quantity} x {invoice>ProductName}"/> </items> </List> </mvc:View> ``` items aggregation 和 invoice model 通过 `items="{invoice>/Invoices}"`的 Invoices 资源进行了绑定,这种绑定叫做 Aggregation Binding。`ObjectListItem` 定义了每个 item 的渲染模板,使用绑定的 model 名字 + `>` 取数据,如 `invoice>Quantity` 表示 invoice model 中的 Invoices 数组下每个元素中的 Quantity 属性。 Step 21: Data Types sap.ui.model.type 下有支持的数据类型,使用 format 属性可以自定义 format 函数用于格式化显示输入数据。 Step 22: Express Binding `${model>pattern}` 使用 `$` + model pattern 可以以此作为表达式运算的单元,因此可以对属性绑定的数据进行表达式运算,这种绑定叫做 Expression Binding。 ``` propertyName="{= ${model>pattern} }" ``` Step 23: Custom Formatters 属性绑定的数据可以使用 format 进行格式化,自定义的格式化函数一般放在 model/formatter.js 下。 Step 24: Filtering List 有一个0..1 的 headerToolbar aggregation,里面允许装填一个 Toolbar,Toolbar 里面使用 SearchField 可以构造搜索输入框。 使用 `oEvent.getParameter("query")` 获取搜索框的用户输入,使用 sap.ui.model.Filter 构造过滤器,并使用 `Binding.filter()` 方法应用它。 ```js onFilterInvoices: function (oEvent) { var aFilter = []; var sQuery = oEvent.getParameter("query"); if (sQuery) { aFilter.push(new Filter("ProductName", FilterOperator.Contains, sQuery)); } var oList = this.byId("invoiceList"); var oBinding = oList.getBinding("items"); oBinding.filter(aFilter); } ``` Step 25: Sorting and Grouping 使用 Aggregation Binding 时,可以通过 `sorter` 属性指定排序规则,如 ```js items="{ path: 'invoice>/Invoices', sorter: { path: 'ShipperName', group: true } }" ``` sorter 是一个对象,可以用 `descending` 降序排列,使用 `group` 将相同数据分组。 Step 26: Remote OData Service 在 *manifest.json* 文件的 `sap.app` 中,可以通过 `dataSources` 属性配置远程数据源,并在 `sap.ui5` 的 models 中通过指定的 key 使用配置好的数据源。如下配置一个 invoiceRemote 的 OData 类型的数据源, *manifest.json* ```json ... "sap.app": { ... "dataSources": { "invoiceRemote": { "uri": "https://services.odata.org/V2/Northwind/Northwind.svc/", "type": "OData", "settings": { "odataVersion": "2.0" } } } ... } ... ``` *Component.js* 初始化项目时会根据以上配置自动创建一个 sap.ui.model.odata.v2.ODataModel,并以 `invoice` 作为 model 名字注册到全局。 遇到跨域问题请参考 https://sapui5.hana.ondemand.com/#/topic/5bb388fc289d44dca886c8fa25da466e.html#loio5bb388fc289d44dca886c8fa25da466e/CORSAnywhere Step 27: Mock Server Configuration 创建 *test/mockServer.html* 文件,内容与 *index.html* 近乎相同,用于启动 MockServer,不同的是 `data-sap-ui-oninit` 指向的是 MockerServer 创建 localService 目录,包含如下文件, ```shell localService ├── metadata.xml // http://services.odata.org/V2/Northwind/Northwind.svc/$metadata ├── mockServer.js └── mockdata └── Invoices.json ``` 使用 sap.ui.core.util.MockServer 创建 MockServer Step 28: Unit Test with QUnit *InvoiceFormatter.js* 中引用了 this 对象,this 对象实际上是一个 Controller,因此我们需要构造一个 controller ```js // Arrange var oControllerStub = { getView: this.stub().returns({ getModel: this.stub().withArgs("i18n").returns(this._oResourceModel) }) }; var fnIsolatedFormatter = InvoiceFormatter.statusText.bind(oControllerStub); ``` 在 *test/unit/unitTests.qunit.html* 中配置 QUnit 等测试框架的版本,在 *test/unit/unitTests.qunit.js* 中加载单元测试的类。 Step 29: Integration Test with OPA 在 test 目录下新建目录 integration, ``` ├── navigationJourney.js ├── opaTests.qunit.html ├── opaTests.qunit.js └── pages └── App.js ``` 使用 Given - When - Then 的模式创建 OPA 测试。*pages/App.js* 中使用 `Opa5.createPageObjects()` 创建一个 Page 对象, actions 中定义的方法使用 When 调用,assertions 中定义的方法使用 Then 调用。 Step 30: Debugging Tools CTRL + ALT + SHIFT + S: 打开 Debug 窗口 Step 31: Routing and Navigation 使用 sap.m.routing.Router 自动管理路由,在 *manifest.json* 中添加三个属性 `config` 、`routes` 和 `targets`。 - `config` 全局路由信息配置,包括 View 的类型,View 的路径,是否同步加载 View 等配置。 - `routes` 每个路由都都名字,模式和一个或多个 targets 组成,当 URL 匹配到模式时,自动加载 target 指向的 view. - `targets` 定义 view 的 ID 和 Name。 在 Component.js 中使用 `this.getRouter()` 获取全局注册的路由,在 Controller 中使用 `sap.ui.core.UIComponent.getRouterFor(this)` 获取路由,使用 `Router.navTo()` 导航到新的页面。 Step 32: Routing with Parameters oEvent.getSource(): 返回被点击的 ObjectListItem 控件。 sap.ui.model.Context: 绑定上下文 Step 33: Routing back and History 使用 sap.ui.core.routing.History 接管页面的浏览历史记录。 Step 34: Custom control extend sap.ui.core.Control 可以自定义 Control,自定义的 Control 如下解构: ```js return Control.extend("your.namespace.control.controlName", { metadata: {}, init: function() {}, renderer: function(oRm, oControl) {} }) ``` - metadata metadata 定义了控件的 properties, events, and aggregations。SAPUI5 会自动为这些 properties, events, and aggregations 创建 setter 和 getter。 - renderer 该方法定义了空间在 HTML 中的 DOM 结构, 一般而言它会自动被调用一旦控件的属性有变化。`oRm` 参数是 SAPUI5 的 render manager,用来将字符串和控件属性写入 HTML 页面中。 - init `init` 方法会在控件初始化时被自动执行。<file_sep>/src/com/0x400/demo/formatter/InvoiceFormatter.js sap.ui.define([], function () { return { statusText: function (sStutus) { var oBundle = this.getView().getModel("i18n").getResourceBundle(); switch (sStutus) { case "A": return oBundle.getText("invoiceStatusA"); case "B": return oBundle.getText("invoiceStatusB"); default: return oBundle.getText("invoiceStatusC"); } } } }); <file_sep>/src/com/0x400/demo/controller/App.controller.js sap.ui.define([ "sap/ui/core/mvc/Controller" ], function (Controller) { return Controller.extend("com.0x400.demo.controller.App", { onOpenDialog: function () { this.getOwnerComponent().openHelloDialog(); } }) });
70e33793a828f534ed4e25597cfbb4c7016f4d4b
[ "JavaScript", "Markdown" ]
5
JavaScript
brelian/sapui5-walkthrough
b0e92e9e5781e23d6ff79345568abf71a6f6fd50
d0693be0dea30ab6c477e5e7327cd3f4e8cdd2bc
refs/heads/master
<file_sep>OPTIMIZE = -O2 CC = g++ CFLAGS = $(OPTIMIZE) -std=c++11 default: StableMatching Heap -include StableMatching.mk -include Heap.mk clean: $(RM) *.o *.gch StableMatching Heap<file_sep>// // StableMatching.hpp // Algorithm-Design // // Created by <NAME> on 5/3/16. // Copyright © 2016 kenneth. All rights reserved. // #ifndef StableMatching_hpp #define StableMatching_hpp #include <vector> class Woman; class Man { public: Man(size_t number); void addPreferenceList(std::vector<Woman *> preferenceList); size_t getNumber(); Woman *getCurrentInterest(); void moveOnToAnotherWoman(); void print(); private: size_t m_number; size_t m_currentInterestIndex; std::vector<Woman *> m_preferenceList; }; class Woman { public: Woman(size_t number, std::vector<Man *> preferenceList); size_t getNumber(); size_t getRank(Man *man); Man *getCurrentPartner(); void setCurrentPartner(Man *man); private: size_t m_number; Man *m_currentPartner; std::vector<Man *> m_preferenceList; std::vector<size_t> m_ranking; }; class StableMatching { public: StableMatching(bool debug = false); void operator()(std::vector<Man *> men, std::vector<Woman *> women); void setDebug(bool debug); private: bool m_debugging; void proposal(Man *man, Woman *woman); void directEngagement(Man *man, Woman *woman); void rejection(Man *man, Woman *woman, Man *anotherMan); void leavingForAnotherMan(Man *man, Woman *woman, Man *anotherMan); }; #endif /* StableMatching_hpp */ <file_sep>// // main.cpp // Algorithm-Design // // Created by <NAME> on 5/3/16. // Copyright © 2016 kenneth. All rights reserved. // #include <iostream> #include "StableMatching.hpp" using std::cout; using std::endl; int main(int argc, const char * argv[]) { Man *m0 = new Man(0); Man *m1 = new Man(1); Man *m2 = new Man(2); Woman *w0 = new Woman(0, {m1, m2, m0}); Woman *w1 = new Woman(1, {m1, m0, m2}); Woman *w2 = new Woman(2, {m0, m2, m1}); m0->addPreferenceList({w0, w1, w2}); m1->addPreferenceList({w0, w1, w2}); m2->addPreferenceList({w0, w1, w2}); StableMatching stableMatchingFunctor(true); cout << "====================" << endl; stableMatchingFunctor({m0, m1, m2}, {w0, w1, w2}); cout << "====================" << endl; cout << "Man 0 ends up with Woman " << m0->getCurrentInterest()->getNumber() << endl; cout << "Man 1 ends up with Woman " << m1->getCurrentInterest()->getNumber() << endl; cout << "Man 2 ends up with Woman " << m2->getCurrentInterest()->getNumber() << endl; cout << "Woman 0 ends up with Man " << w0->getCurrentPartner()->getNumber() << endl; cout << "Woman 1 ends up with Man " << w1->getCurrentPartner()->getNumber() << endl; cout << "Woman 2 ends up with Man " << w2->getCurrentPartner()->getNumber() << endl; cout << "====================" << endl; return 0; } <file_sep>// // Heap.hpp // PlayGround // // Created by <NAME> on 7/1/16. // Copyright © 2016 kenneth. All rights reserved. // #ifndef Heap_hpp #define Heap_hpp #include <vector> template <typename SizeType> class Heap { public: typename std::vector<SizeType>::const_iterator begin() const { return m_keys.begin(); } typename std::vector<SizeType>::const_iterator end() const { return m_keys.end(); } bool isEmpty() const { return m_keys.empty(); } void findMin() const { return m_keys[0]; } void insert(SizeType v); void remove(size_t i); void extractMin() { remove(0); } private: size_t leftChild(size_t i) { return 2 * i + 1; } size_t rightChild(size_t i) { return 2 * i + 2; } size_t parent(size_t i) { return (i - 1) / 2; } void heapifyUp(size_t i); void heapifyDown(size_t i); std::vector<SizeType> m_keys; }; template <typename SizeType> void Heap<SizeType>::insert(SizeType v) { m_keys.push_back(v); heapifyUp(m_keys.size()-1); } template <typename SizeType> void Heap<SizeType>::heapifyUp(size_t i) { if (i > 0) { size_t j = parent(i); if (m_keys[i] < m_keys[j]) { std::swap(m_keys[i], m_keys[j]); heapifyUp(j); } } } template <typename SizeType> void Heap<SizeType>::heapifyDown(size_t i) { size_t length = m_keys.size(); size_t j; if (leftChild(i) + 1 > length) { return; } else if (leftChild(i) + 1 == length) { j = leftChild(i); } else { j = (m_keys[leftChild(i)] < m_keys[rightChild(i)]) ? leftChild(i) : rightChild(i); } if (m_keys[j] < m_keys[i]) { std::swap(m_keys[i], m_keys[j]); heapifyDown(j); } } template <typename SizeType> void Heap<SizeType>::remove(size_t i) { std::swap(m_keys[i], m_keys[m_keys.size()-1]); m_keys.pop_back(); heapifyUp(i); heapifyDown(i); } #endif /* Heap_hpp */ <file_sep>// // StableMatching.cpp // Algorithm-Design // // Created by <NAME> on 5/3/16. // Copyright © 2016 kenneth. All rights reserved. // #include "StableMatching.hpp" #include <iostream> #include <list> ////// // Man Implemantation // // // Man::Man(size_t number) : m_number(number), m_currentInterestIndex(0) {} void Man::addPreferenceList(std::vector<Woman *> preferenceList) { m_preferenceList = preferenceList; } size_t Man::getNumber() { return m_number; } void Man::print() { std::cout << "Man number " << m_number << ":" << std::endl; for (Woman *woman : m_preferenceList) { std::cout << woman->getNumber() << std::endl; } } Woman *Man::getCurrentInterest() { return m_preferenceList[m_currentInterestIndex]; } void Man::moveOnToAnotherWoman() { ++m_currentInterestIndex; } ////// // Woman Implementation // // // Woman::Woman(size_t number, std::vector<Man *> preferenceList) : m_number(number), m_currentPartner(nullptr), m_preferenceList(preferenceList) { m_ranking.resize(preferenceList.size()); for (size_t t = 0; t < preferenceList.size(); ++t) { size_t man = preferenceList[t]->getNumber(); m_ranking[man] = t; } } size_t Woman::getNumber() { return m_number; } size_t Woman::getRank(Man *man) { return m_ranking[man->getNumber()]; } Man *Woman::getCurrentPartner() { return m_currentPartner; } void Woman::setCurrentPartner(Man *man) { m_currentPartner = man; } ////// // Stable Matching Implementation // // // StableMatching::StableMatching(bool debug) : m_debugging(debug) {} void StableMatching::operator()(std::vector<Man *> men, std::vector<Woman *> women) { std::list<Man *> freeMen; for (Man *man : men) { freeMen.push_back(man); } while (!freeMen.empty()) { Man *man = freeMen.front(); freeMen.pop_front(); Woman *woman = man->getCurrentInterest(); Man *possiblyAnotherMan = woman->getCurrentPartner(); // Debugging purposes proposal(man, woman); if (possiblyAnotherMan == nullptr) { woman->setCurrentPartner(man); // Debugging purposes directEngagement(man, woman); } else if (woman->getRank(man) > woman->getRank(possiblyAnotherMan)) { freeMen.push_back(man); man->moveOnToAnotherWoman(); // Debugging purposes rejection(man, woman, possiblyAnotherMan); } else { woman->setCurrentPartner(man); freeMen.push_back(possiblyAnotherMan); possiblyAnotherMan->moveOnToAnotherWoman(); // Debugging purposes leavingForAnotherMan(man, woman, possiblyAnotherMan); } } } void StableMatching::setDebug(bool debug) { m_debugging = debug; } void StableMatching::proposal(Man *man, Woman *woman) { if (m_debugging) { std::cout << "Man " << man->getNumber() << " is asking Woman " << woman->getNumber() << std::endl; } } void StableMatching::directEngagement(Man *man, Woman *woman) { if (m_debugging) { std::cout << "Woman " << woman->getNumber() << " is single, so she accepts" << std::endl; } } void StableMatching::rejection(Man *man, Woman *woman, Man *anotherMan) { if (m_debugging) { std::cout << "Woman " << woman->getNumber() << " is with Man " << anotherMan->getNumber(); std::cout << " and Man " << anotherMan->getNumber(); std::cout << " is higher on her preference list, so she declines" << std::endl; } } void StableMatching::leavingForAnotherMan(Man *man, Woman *woman, Man *anotherMan) { if (m_debugging) { std::cout << "Woman " << woman->getNumber() << " is with Man " << anotherMan->getNumber(); std::cout << " and Man " << man->getNumber(); std::cout << " is higher on her preference list, so she leaves Man " << anotherMan->getNumber(); std::cout << " and engages with Man " << man->getNumber() << std::endl; } } <file_sep>StableMatching: StableMatching.o StableMatchingTest.o $(CC) $(CFLAGS) -o StableMatching StableMatching.o StableMatchingTest.o StableMatchingTest.o: StableMatchingTest.cpp $(CC) $(CFLAGS) -c StableMatchingTest.cpp StableMatching.o: StableMatching.hpp StableMatching.cpp $(CC) $(CFLAGS) -c StableMatching.hpp StableMatching.cpp<file_sep>Heap: HeapTest.o $(CC) $(CFLAGS) -o Heap HeapTest.o HeapTest.o: HeapTest.cpp Heap.hpp $(CC) $(CFLAGS) -c HeapTest.cpp Heap.hpp<file_sep>// // HeapTest.cpp // PlayGround // // Created by <NAME> on 7/1/16. // Copyright © 2016 kenneth. All rights reserved. // #include "Heap.hpp" #include <iostream> void HeapTest(); int main() { HeapTest(); } void HeapTest() { auto printHeapLambda = [](Heap<int> H) { for (auto x : H) { std::cout << x << " "; } std::cout << std::endl; }; Heap<int> H; // 0 y -2 y 1 y 7 y -1 y 3 y 4 y 8 y 9 y 1 y 2 y -5 while (true) { std::cout << "Enter a value" << std::endl; int val; std::cin >> val; H.insert(val); printHeapLambda(H); std::cout << "Do you want to continute? (If so, type y)" << std::endl; char ch; std::cin >> ch; if (ch != 'y') break; } while (true) { std::cout << "Enter an index to remove" << std::endl; int idx; std::cin >> idx; H.remove(idx); printHeapLambda(H); std::cout << "Do you want to continute? (If so, type y)" << std::endl; char ch; std::cin >> ch; if (ch != 'y') break; } while (!H.isEmpty()) { printHeapLambda(H); H.extractMin(); } }
493dac6e90506ac4fa91e9a75f3c804c781a48b2
[ "Makefile", "C++" ]
8
Makefile
kanatufuk/Algorithm-Design
4531a33242b645697626bc57db433f7621129785
90ae174d76e6393d27f0cacc917a77241554ecd0
refs/heads/master
<repo_name>happy-lele/learn-aqs<file_sep>/src/main/java/com/le/aqs/LockInterruptiblyDemo.java package com.le.aqs; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * 测试中断锁&非中断锁 * * @Author happy_le * @date 2020/12/14 下午11:05 */ public class LockInterruptiblyDemo { private static Object object1 = new Object(); private static Object object2 = new Object(); private static ReentrantLock lock1 = new ReentrantLock(); private static ReentrantLock lock2 = new ReentrantLock(); public static void main(String[] args) throws Throwable { /** 可中断锁 */ // Thread t1 = new Thread(new ReentrantLockThread(lock1, lock2)); // Thread t2 = new Thread(new ReentrantLockThread(lock2, lock1)); /** 不可中断锁 */ Thread t1 = new Thread(new SynchronizedThread(object1, object2)); Thread t2 = new Thread(new SynchronizedThread(object2, object1)); t1.start(); t2.start(); //主线程睡眠1秒,避免线程t1直接响应run方法中的睡眠中断 System.out.println("主线程开始沉睡第1秒!"); TimeUnit.MILLISECONDS.sleep(1000); System.out.println("主线程开始沉睡第2秒!"); TimeUnit.MILLISECONDS.sleep(1000); System.out.println("主线程开始沉睡第3秒!"); TimeUnit.MILLISECONDS.sleep(1000); System.out.println("主线程线程" + t1.getName() + ",在t1上开始执行interrupt()"); t1.interrupt(); } /** * ReentrantLock的lockInterruptibly实现死锁 */ static class ReentrantLockThread implements Runnable { private ReentrantLock lock1; private ReentrantLock lock2; public ReentrantLockThread(ReentrantLock lock1, ReentrantLock lock2) { this.lock1 = lock1; this.lock2 = lock2; } @Override public void run() { try { lock1.lockInterruptibly(); // 获得lock1的可中断锁 TimeUnit.MILLISECONDS.sleep(100); // 等待lock1和lock2分别被两个线程获取。产生死锁现象 lock2.lockInterruptibly(); // 获得lock2的可中断锁 } catch (InterruptedException e) { e.printStackTrace(); } finally { lock1.unlock(); lock2.unlock(); System.out.println("线程" + Thread.currentThread().getName() + ",正常结束"); } } } /** * Synchronized实现死锁 */ static class SynchronizedThread implements Runnable { private Object lock1; private Object lock2; public SynchronizedThread(Object lock1, Object lock2) { this.lock1 = lock1; this.lock2 = lock2; } @Override public void run() { try { synchronized(lock1) { // 获得lock1的不可中断锁 TimeUnit.MILLISECONDS.sleep(100); // 等待lock1和lock2分别被两个线程获取。产生死锁现象 synchronized(lock2) { // 获得lock2的不可中断锁 } } } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println("线程" + Thread.currentThread().getName() + "正常结束"); } } } } <file_sep>/src/main/java/com/le/aqs/ConditionDemo.java package com.le.aqs; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @Author happy_le * @date 2020/12/14 下午11:05 */ public class ConditionDemo { public static ReentrantLock lock = new ReentrantLock(); public static Condition condition = lock.newCondition(); public static void main(String[] args) throws Throwable { new Thread(() -> { try { lock.lock(); System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + ", " + "子线程开始等待!"); condition.await(); // 释放当前锁,进入等待中;其中,调用await,一定要先获得锁。 System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + ", " + "子线程继续执行!"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }).start(); Thread.sleep(1000); System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + ", 主线程睡了第1秒钟!"); Thread.sleep(1000); System.out.println(System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + ", 主线程睡了第2秒钟!"); lock.lock(); // 调用signal之前,一定要先获得锁,否则会报IllegalMonitorStateException异常 condition.signal(); System.out.println( System.currentTimeMillis() / 1000 + " " + Thread.currentThread().getName() + ", 主线程调用了signal!"); lock.unlock(); } } <file_sep>/src/main/java/com/le/aqs/SemaphoreBoundedList.java package com.le.aqs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Semaphore; /** * @Author happy_le * @date 2020/12/14 下午1:25 */ public class SemaphoreBoundedList { public static void main(String[] args) { //4、容器边界限制 final BoundedList ba = new BoundedList(5); Runnable runnable1 = new Runnable() { @Override public void run() { try { ba.add("John"); ba.add("Martin"); ba.add("Adam"); ba.add("Prince"); ba.add("Tod"); System.out.println("Available Permits : " + ba.getSemaphore().availablePermits()); ba.add("Tony"); System.out.println("Final list: " + ba.getArrayList()); } catch (InterruptedException e) { Thread.interrupted(); } } }; Runnable runnable2 = new Runnable() { @Override public void run() { try { System.out.println("Before removing elements: "+ ba.getArrayList()); Thread.sleep(5000); ba.remove("Martin"); ba.remove("Adam"); } catch (InterruptedException e) { Thread.interrupted(); } } }; Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2); thread1.start(); thread2.start(); } } class BoundedList<T> { private final Semaphore semaphore; private List arrayList; public BoundedList(int limit) { this.semaphore = new Semaphore(limit); this.arrayList = Collections.synchronizedList(new ArrayList<>()); } public boolean add(T t) throws InterruptedException { boolean added = false; semaphore.acquire(); try { added = arrayList.add(t); return added; } finally { if (!added) { semaphore.release(); } } } public boolean remove(T t) { boolean wasRemoved = arrayList.remove(t); if (wasRemoved) { semaphore.release(); } return wasRemoved; } public void remove(int index) { arrayList.remove(index); semaphore.release(); } public List getArrayList() { return arrayList; } public Semaphore getSemaphore() { return semaphore; } }<file_sep>/src/main/java/com/le/aqs/SemaphoreCommunication.java package com.le.aqs; import java.util.concurrent.Semaphore; /** * @Author happy_le * @date 2020/12/14 上午11:46 */ public class SemaphoreCommunication { public static void main(String[] args) { //2、线程间进行通信 Semaphore semaphore = new Semaphore(1); new SendingThread(semaphore,"SendingThread"); new ReceivingThread(semaphore,"ReceivingThread"); } } class SendingThread extends Thread { Semaphore semaphore; String name; public SendingThread(Semaphore semaphore, String name) { this.semaphore = semaphore; this.name = name; new Thread(this).start(); } @Override public void run() { try { semaphore.acquire(); for (int i = 0; i < 5; i++) { System.out.println(name + ":" + i); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } } class ReceivingThread extends Thread { Semaphore semaphore; String name; public ReceivingThread(Semaphore semaphore, String name) { this.semaphore = semaphore; this.name = name; new Thread(this).start(); } @Override public void run() { try { semaphore.acquire(); for (int i = 0; i < 5; i++) { System.out.println(name + ":" + i); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } }<file_sep>/README.md # learn-aqs ## 这是一个学习一个AQS的小demo
2ff79f2f1058ad17ec7e93e4d888dc98d919258c
[ "Markdown", "Java" ]
5
Java
happy-lele/learn-aqs
6e57d3746e3a9365a89d2b13d2feb192afe0e694
09d71f8b5eddea5b1ce0d01c866d505bc56587b3
refs/heads/master
<repo_name>dendennekoneko/ZaikoKanriMenu<file_sep>/src/在庫管理システム/Search_SQL.java package 在庫管理システム; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; //SQL処理用メインクラス public class Search_SQL{ @SuppressWarnings("unused") private static final long serialVersionUID = 1L; Connection conn; //SQL接続インスタンス Statement st; //SQL実行用インスタンス ResultSet rset; //SQL結果格納用インスタンス ResultSetMetaData rsmd; //SQLカラム名取得用インスタンス static String selectSql; //SQL文を格納する public static int get_shocd = 0; //入力された商品CD public static String get_shoname = ""; //入力された商品名 boolean string_check_ok; //DB内に存在しない文字列が入力されていないかチェック用 boolean int_check_ok; //DB内に存在しない商品CDが入力されていないかチェック用 public static List<ArrayList<String>> result_Column = new ArrayList<>(); //二次元配列(DB結果を格納する表) //コンストラクタ、在庫検索が入力されたタイミングでDB接続 Search_SQL() throws SQLException{ // (1) 接続用のURIを用意する(必要に応じて認証指示user/passwordを付ける) String uri = "jdbc:postgresql://localhost:5432/sample"; String user = "postgres"; String password = "<PASSWORD>"; // (2) DriverManagerクラスのメソッドで接続する conn = DriverManager.getConnection(uri,user,password); //SQL実行用インスタンス st = conn.createStatement(); } //SQL結果一覧表示用メソッド public void getSql() throws SQLException { selectSql = "SELECT * FROM hatzaiko ORDER BY shocd ASC"; //商品CDが正しく入力されているかチェック intCheck(); //商品CDが問題なければ if(int_check_ok) { //商品名が正しく入力されているかチェック stringCheck(); } //存在しない文字列エラーが出ていなければ if(string_check_ok && int_check_ok) { //入力された検索条件に従い、SQL実行メソッドlistGo()で必要なSQL文を確定する。 search(); } //諸々のエラーが出ていなければ if(Zaiko_Search.l_error_syu.getText().equals("") && int_check_ok && string_check_ok) { //SQL実行&一覧表作成 listGo(); } } //一覧表作成メソッド public void listGo() throws SQLException { //選択SQL実行 rset = st.executeQuery(selectSql); //レコードを取得 while(rset.next()) { //なぎせさん(ArrayList生成) ArrayList<String> tempArray = new ArrayList<>(); tempArray.add(String.valueOf(rset.getInt("shocd"))); tempArray.add(rset.getString("shoname")); tempArray.add(String.valueOf(rset.getInt("zaisu"))); //二次元ListにtempArrayを追加 result_Column.add(tempArray); } //在庫一覧表が開いていない if(!Zaiko_List.paint_now) { //在庫一覧表インスタンス生成 new Zaiko_List(); //在庫一覧表のJTable配列に代入できたため、二次元配列をクリアする Search_SQL.result_Column.clear(); conn.close(); } } //存在しない商品CDが入力されていないかチェック public void intCheck() throws SQLException { //商品CDが入力されている if(get_shocd!=0) { rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品CDと、SQL結果の商品CDが一致する if(rset.getString("shocd").equals(String.valueOf(get_shocd))) { int_check_ok = true; break; } } //入力された商品CDが不正 if(!int_check_ok) { Zaiko_Search.l_error_syu.setText("存在しない商品CDが入力されています。"); } //そもそも商品CDが入力されていなかった、もしくは0なら }else { int_check_ok = true; } } //存在しない商品名が入力されていないかチェック public void stringCheck() throws SQLException { //商品名が入力されている if(!get_shoname.equals("")) { rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品名と、SQL結果の商品名が一致する if(rset.getString("shoname").trim().equals(get_shoname.trim())) { string_check_ok = true; break; } } //入力された商品名が不正 if(!string_check_ok) { Zaiko_Search.l_error_syu.setText("存在しない商品名が入力されています。"); } //そもそも商品名が入力されていなかったら }else { string_check_ok = true; } } //入力された商品名が一致しているかチェック public void search() throws SQLException { //商品CDが入力されている if(get_shocd != 0) { selectSql = "SELECT * FROM hatzaiko WHERE shocd="+get_shocd+""; //商品名が入力されている if(!get_shoname.trim().equals("")) { rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品名がと、入力された商品CDに対応する商品名が正しく一致している if(rset.getString("shoname").trim().equals(get_shoname)) { break; }else { Zaiko_Search.l_error_syu.setText("商品CDと商品名が一致しません。"); break; } } } //商品名のみ入力されている。 }else { if(!get_shoname.trim().equals("")){ rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品名がDB上の商品名と一致している if(rset.getString("shoname").trim().equals(get_shoname)) { selectSql = "SELECT * FROM hatzaiko WHERE shoname like '%"+get_shoname+"%'"; break; } } } } } //ウィンドウが閉じられた時の処理、オーバーライド←そもそも親クラスにこのメソッド必要ない・・・ class WinAda extends WindowAdapter{ public void windowClosing(WindowEvent e) { try { //データベース接続を切断 conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } } } }<file_sep>/src/在庫管理システム/Out_SQL.java package 在庫管理システム; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; //出荷SQL処理用メインクラス public class Out_SQL{ @SuppressWarnings("unused") private static final long serialVersionUID = 1L; Connection conn; //SQL接続インスタンス Statement st; //SQL実行用インスタンス ResultSet rset; //SQL結果格納用インスタンス ResultSetMetaData rsmd; //SQLカラム名取得用インスタンス String selectSql; //SQL文を格納する public static int get_shocd = 0; //入力された商品CD public static String get_shoname = ""; //入力された商品名 public static int get_syusu = 0; //入力された出荷数 boolean string_check_ok; //DB内に存在しない文字列が入力されていないかチェック用 boolean int_check_ok; //DB内に存在しない商品CDが入力されていないかチェック用 Out_SQL() throws SQLException{ // (1) 接続用のURIを用意する(必要に応じて認証指示user/passwordを付ける) String uri = "jdbc:postgresql://localhost:5432/sample"; String user = "postgres"; String password = "<PASSWORD>"; // (2) DriverManagerクラスのメソッドで接続する conn = DriverManager.getConnection(uri,user,password); //SQL実行用インスタンス st = conn.createStatement(); } //SQL結果一覧表示用メソッド ******************************************************************** public void getSql() throws SQLException { selectSql = "SELECT * FROM hatzaiko ORDER BY shocd ASC"; intCheck(); if(int_check_ok) { stringCheck(); } //存在しない文字列エラーが出ていなければ if(string_check_ok && int_check_ok) { search(); } //諸々のエラーが出ていなければ if(Zaiko_Syukka.l_error_s.getText().equals("") && int_check_ok && string_check_ok) { //一覧表作成 syukka(); conn.close(); } } //***************************************************************************************** //一覧表作成メソッド public void syukka() throws SQLException { st.executeUpdate(selectSql); Zaiko_Syukka.l_result.setText(get_syusu+"個、出荷されました"); } //存在しない商品CDが入力されていないかチェック public void intCheck() throws SQLException { //存在しない商品CDが入力されていないかチェック if(get_shocd!=0) { rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品CDと、SQL結果の商品CDが一致する if(rset.getString("shocd").equals(String.valueOf(get_shocd))) { int_check_ok = true; break; } } if(!int_check_ok) { Zaiko_Syukka.l_error_s.setText("存在しない商品CDが入力されています。"); } }else { int_check_ok = true; } } //存在しない商品名が入力されていないかチェック public void stringCheck() throws SQLException { //無効な商品名が入っていないか確認する!! if(!get_shoname.equals("")) { rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品名と、SQL結果の商品名が一致する if(rset.getString("shoname").trim().equals(get_shoname.trim())) { string_check_ok = true; break; } } if(!string_check_ok) { Zaiko_Syukka.l_error_s.setText("存在しない商品名が入力されています。"); } }else { string_check_ok = true; } } //入力された商品名が一致しているかチェック public void search() throws SQLException { //商品CDが入力されている if(get_shocd != 0) { selectSql = "SELECT * FROM hatzaiko WHERE shocd="+get_shocd+""; //商品名が入力されている if(!get_shoname.trim().equals("")) { rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品名がと、入力された商品CDに対応する商品名が正しく一致している if(rset.getString("shoname").trim().equals(get_shoname)) { selectSql = "UPDATE hatzaiko SET zaisu = zaisu - "+get_syusu+" WHERE shocd="+get_shocd+""; break; }else { Zaiko_Syukka.l_error_s.setText("商品CDと商品名が一致しません。"); break; } } }else { selectSql = "UPDATE hatzaiko SET zaisu = zaisu - "+get_syusu+" WHERE shocd="+get_shocd+""; } //商品名のみ入力されている。 }else { if(!get_shoname.trim().equals("")){ rset = st.executeQuery(selectSql); while(rset.next()) { //入力された商品名がDB上の商品名と一致している if(rset.getString("shoname").trim().equals(get_shoname)) { selectSql = "UPDATE hatzaiko SET zaisu = zaisu - "+get_syusu+" WHERE shoname LIKE '%"+get_shoname+"%'"; break; } } }else { selectSql = "UPDATE hatzaiko SET zaisu = zaisu - "+get_syusu+""; } } } }
13d3a9d173f7cdb0f0af2300f3fafc98893d1e05
[ "Java" ]
2
Java
dendennekoneko/ZaikoKanriMenu
9226c8d089a6dabfa4530da07500335c4459dee4
430debfddf66e0c613f7795252b642ddfec1ae34
refs/heads/master
<file_sep>/** * Created by mattsu on 11/19/14. */ var RectUtil = function() {}; RectUtil.fit = function (r, into) { var intoAspect = into.width / into.height; var rAspect = r.width / r.height; var scaleMultiplier; if (rAspect >= intoAspect) { scaleMultiplier = into.width / r.width; } else { scaleMultiplier = into.height / r.height; } var width = r.width * scaleMultiplier; var height = r.height * scaleMultiplier; var resultRect = new goog.math.Rect( into.left + (into.width - width) / 2, into.top + (into.height - height) / 2, width, height ); return resultRect; } // TODO: Implement fill() /* RectUtil.fill = function (r, into) { var newRect; return newRect; }*/ <file_sep>/** * Created by mattsu on 11/19/14. */ var BezierTest = function () { var bounds; var defaultBounds = new goog.math.Rect(0, 0, 1400, 840); var $window = $(window); var $wrapper = $("#wrapper"); var renderer; var scene; var camera; var FOV = 60; var CAMERA_NEAR = 0.1; var CAMERA_FAR = 100; var sphereGeometry = new THREE.SphereGeometry(1); var sphereMeshes = []; function init() { initRenderer(); init3D(); redraw(); initRender(); } /** * TEST */ function initRenderer() { renderer = new THREE.WebGLRenderer( { alpha: false, antialias: true } ); $wrapper.append(renderer.domElement); } function init3D() { scene = new THREE.Scene(); var aspect = defaultBounds.width / defaultBounds.height; camera = new THREE.PerspectiveCamera(FOV, aspect, CAMERA_NEAR, CAMERA_FAR); camera.position.set(5, 5, 5); camera.lookAt(scene.position); var mesh; for (var i = 0; i < 8; i++) { mesh = new THREE.Mesh(sphereGeometry); sphereMeshes.push(mesh); scene.add(mesh); } } function redraw() { var into = new goog.math.Rect(0, 0, $window.width(), $window.height()); bounds = RectUtil.fit(defaultBounds, into); $wrapper.css( { width: bounds.width, height: bounds.height } ); renderer.setSize(bounds.width, bounds.height); camera.aspect = bounds.width / bounds.height; camera.updateProjectionMatrix(); } function initRender() { // Use TweenMax to manage the requestAnimationFrame calls TweenMax.ticker.addEventListener("tick", render); } function render() { renderer.render(scene, camera); } return { init: init, redraw: redraw } };
f05f24700c2b53aae4888c7d8729584e8268891b
[ "JavaScript" ]
2
JavaScript
julespong/1411_BezierTest
d16fd348d4c3db64dc3768328279dd692c46d0a2
83e4c489295f6a0055ec1a0bf5f2013704da0c33
refs/heads/master
<file_sep>package bpm import ( "fmt" ) type _KMPSearchEngine struct { *_BaseEngine pattern []byte prefix []int64 } func (kmp *_KMPSearchEngine) PreprocessPattern(pattern []byte) { kmp.pattern = pattern kmp.computePrefix() } func (kmp *_KMPSearchEngine) computePrefix() { pl := len(kmp.pattern) if pl == 1 { kmp.prefix = []int64{-1} return } var ( count int64 = 0 pos int = 2 ) kmp.prefix = make([]int64, pl) kmp.prefix[0], kmp.prefix[1] = -1, 0 for pos < pl { if kmp.pattern[pos-1] == kmp.pattern[count] { count++ kmp.prefix[pos] = count pos++ } else { if count > 0 { count = kmp.prefix[count] } else { kmp.prefix[pos] = 0 pos++ } } } return } func (kmp *_KMPSearchEngine) FindAllOccurrences() (srs SearchResults, err error) { dl, pl := kmp.bfr.FileSize(), int64(len(kmp.pattern)) if pl > dl { err = fmt.Errorf("pattern must not be longer than data") return } var ( i, m int64 indices []int64 plm1 int64 = pl - 1 ) for m+i < dl { if kmp.pattern[i] == kmp.bfr.ReadByteAt(m+i) { if i == plm1 { indices = append(indices, m) m += i - kmp.prefix[i] if kmp.prefix[i] > -1 { i = kmp.prefix[i] } else { i = 0 } } else { i++ } } else { m += i - kmp.prefix[i] if kmp.prefix[i] > -1 { i = kmp.prefix[i] } else { i = 0 } } } srs = newSearchResults().putMany(kmp.pattern, indices) return } <file_sep>package bpm import ( "testing" . "github.com/pkorotkov/randombulk" ) var ( randomFilePath = "./test-data/data.bin" spatterns = []string{ "3Hs9Wnlo1Q5", "o0plMs-EgdC3#", "D0zWholeBr7q4W9", "Kw87_uiX2Y", "RWo-45vZl", } ) func createRandomFile() (err error) { bulk := NewRandomBulk() incls := []Inclusion{ NewInclusionFromString(spatterns[0], Frequencies.Sometimes), NewInclusionFromString(spatterns[1], Frequencies.Rarely), NewInclusionFromString(spatterns[2], Frequencies.Sometimes), NewInclusionFromString(spatterns[3], Frequencies.Frequently), NewInclusionFromString(spatterns[4], Frequencies.Rarely), } _, err = bulk.DumpToFile(randomFilePath, 50*1024, false, incls) return } func TestAlgorithms(t *testing.T) { var ( err error srs SearchResults patterns [][]byte ) for _, sp := range spatterns { patterns = append(patterns, []byte(sp)) } // Test Aho-Corasick. ac := NewSearchEngine(Algorithms.AC).(MultiplePatternSearchEngine) if err = ac.SetFile(randomFilePath); err != nil { t.Fatal(err) } ac.PreprocessPatterns(patterns) if srs, err = ac.FindAllOccurrences(); err != nil { t.Fatal(err) } for i := 0; i < 5; i++ { fps, sps := srs.Get(patterns[i]), samplePositions[spatterns[i]] for k, fp := range fps { if sp := sps[k]; fp != sp { t.Errorf("[AC] position comparison is broken: expected %d but encountered %d", sp, fp) } } } // Test Boyer–Moore–Horspool. bmh := NewSearchEngine(Algorithms.BMH).(SinglePatternSearchEngine) if err = bmh.SetFile(randomFilePath); err != nil { t.Fatal(err) } bmh.PreprocessPattern(patterns[2]) if srs, err = bmh.FindAllOccurrences(); err != nil { t.Fatal(err) } fps, sps := srs.Get(patterns[2]), samplePositions[spatterns[2]] for k, fp := range fps { if sp := sps[k]; fp != sp { t.Errorf("[BMH] position comparison is broken: expected %d but encountered %d", sp, fp) } } // Test Knuth–Morris–Pratt. kmp := NewSearchEngine(Algorithms.KMP).(SinglePatternSearchEngine) if err = kmp.SetFile(randomFilePath); err != nil { t.Fatal(err) } kmp.PreprocessPattern(patterns[3]) if srs, err = kmp.FindAllOccurrences(); err != nil { t.Fatal(err) } fps, sps = srs.Get(patterns[3]), samplePositions[spatterns[3]] for k, fp := range fps { if sp := sps[k]; fp != sp { t.Errorf("[KMP] position comparison is broken: expected %d but encountered %d", sp, fp) } } } <file_sep>package bpm type treeNode struct { parent *treeNode char byte failure *treeNode // See https://github.com/golang/go/issues/3512 results map[string][]byte transitions map[byte]*treeNode } func newTreeNode(p *treeNode, c byte) *treeNode { return &treeNode{ parent: p, char: c, results: make(map[string][]byte), transitions: make(map[byte]*treeNode), } } // Adds pattern ending in this node. func (tn *treeNode) AddResult(r []byte) { if _, ok := tn.results[string(r)]; ok { return } tn.results[string(r)] = r } // adds trabsition node. func (tn *treeNode) AddTransition(n *treeNode) { tn.transitions[n.char] = n } type _ACSearchEngine struct { *_BaseEngine root *treeNode } func (ac *_ACSearchEngine) PreprocessPatterns(patterns [][]byte) { ac.buildTree(patterns) } // builds tree from specified patterns. func (ac *_ACSearchEngine) buildTree(patterns [][]byte) { // Build pattern tree and transition function. ac.root = newTreeNode(nil, 0) for _, p := range patterns { n := ac.root for _, pc := range p { var nn *treeNode for c, tn := range n.transitions { if c == pc { nn = tn break } } if nn == nil { nn = newTreeNode(n, pc) n.AddTransition(nn) } n = nn } n.AddResult(p) } // Find failure functions. var nodes []*treeNode for _, tn := range ac.root.transitions { tn.failure = ac.root for _, tt := range tn.transitions { nodes = append(nodes, tt) } } // Deal with other nodes using BFS. for len(nodes) != 0 { var nnodes []*treeNode for _, n := range nodes { r, c := n.parent.failure, n.char for r != nil && r.transitions[c] == nil { r = r.failure } if r == nil { n.failure = ac.root } else { n.failure = r.transitions[c] for _, res := range n.failure.results { n.AddResult(res) } } for _, tn := range n.transitions { nnodes = append(nnodes, tn) } } nodes = nnodes } ac.root.failure = ac.root } func (ac *_ACSearchEngine) FindAllOccurrences() (srs SearchResults, err error) { var ( index int64 dl int64 = ac.bfr.FileSize() ) srs = newSearchResults() rt := ac.root for index < dl { var tn *treeNode for tn == nil { tn = rt.transitions[ac.bfr.ReadByteAt(index)] if rt == ac.root { break } if tn == nil { rt = rt.failure } } if tn != nil { rt = tn } for _, pattern := range rt.results { srs.putOne(pattern, index-int64(len(pattern))+1) } index++ } return } <file_sep>package bpm import ( "os" ) type bufferedFileReader struct { baseFile *os.File fileSize int64 buffer []byte bufferSize int64 bufferPivotPosition int64 } func newBufferedFileReader(fp string) (bfr *bufferedFileReader, err error) { return newBufferedFileReaderWithSize(fp, 64*1024*1024) } func newBufferedFileReaderWithSize(fp string, bs int64) (bfr *bufferedFileReader, err error) { var ( bf *os.File fi os.FileInfo buf []byte ) if bf, err = os.Open(fp); err != nil { return } if fi, err = bf.Stat(); err != nil { return } buf = make([]byte, bs) if _, err = bf.Read(buf); err != nil { return } bfr = &bufferedFileReader{bf, fi.Size(), buf, bs, 0} return } func (bfr *bufferedFileReader) FileSize() int64 { return bfr.fileSize } func (bfr *bufferedFileReader) ReadByteAt(offset int64) byte { if offset >= bfr.bufferPivotPosition && offset < (bfr.bufferPivotPosition+bfr.bufferSize) { return bfr.buffer[offset-bfr.bufferPivotPosition] } if n, _ := bfr.baseFile.ReadAt(bfr.buffer, offset); n == 0 { panic("(*bufferedFileReader).ReadByteAt: unexpected zero bytes read") } bfr.bufferPivotPosition = offset return bfr.buffer[0] } func (bfr *bufferedFileReader) Close() error { return bfr.baseFile.Close() } <file_sep>package bpm type algorithm string var Algorithms = struct{ AC algorithm BMH algorithm KMP algorithm }{"Aho-Corasick", "Boyer–Moore–Horspool", "Knuth–Morris–Pratt"} type SearchResults map[string][]int64 func newSearchResults() SearchResults { srs := make(map[string][]int64) return srs } func (sr SearchResults) putOne(pattern []byte, position int64) SearchResults { sr[string(pattern)] = append(sr[string(pattern)], position) return sr } func (sr SearchResults) putMany(pattern []byte, positions []int64) SearchResults { sr[string(pattern)] = append(sr[string(pattern)], positions...) return sr } // Get returns positions of the given byte pattern. func (sr SearchResults) Get(pattern []byte) []int64 { return sr[string(pattern)] } type SearchEngine interface { Name() string SetFile(filePath string) error FindAllOccurrences() (SearchResults, error) } type _BaseEngine struct { name algorithm bfr *bufferedFileReader } func (be *_BaseEngine) Name() string { return string(be.name) } func (be *_BaseEngine) SetFile(fp string) (err error) { var bfr *bufferedFileReader if bfr, err = newBufferedFileReader(fp); err != nil { return } be.bfr = bfr return } type SinglePatternSearchEngine interface { SearchEngine PreprocessPattern(pattern []byte) } type MultiplePatternSearchEngine interface { SearchEngine PreprocessPatterns(patterns [][]byte) } func NewSearchEngine(alg algorithm) SearchEngine { switch alg { case Algorithms.BMH: return &_BMHSearchEngine{_BaseEngine: &_BaseEngine{name: alg}} case Algorithms.KMP: return &_KMPSearchEngine{_BaseEngine: &_BaseEngine{name: alg}} case Algorithms.AC: return &_ACSearchEngine{_BaseEngine: &_BaseEngine{name: alg}} default: return nil } } <file_sep># bpm A byte pattern matching library adapted for search in binary files [![GoDoc](https://godoc.org/github.com/pkorotkov/bpm?status.svg)](https://godoc.org/github.com/pkorotkov/bpm) ## Installation and testing go get -u -v -t github.com/pkorotkov/bpm go test github.com/pkorotkov/bpm <file_sep>package bpm import ( "fmt" ) type _BMHSearchEngine struct { *_BaseEngine pattern []byte } func (bmh *_BMHSearchEngine) PreprocessPattern(pattern []byte) { bmh.pattern = pattern } func (bmh *_BMHSearchEngine) FindAllOccurrences() (srs SearchResults, err error) { dl, pl := bmh.bfr.FileSize(), int64(len(bmh.pattern)) if pl > dl { err = fmt.Errorf("pattern must not be longer than data") return } var ( indices []int64 badChars []int64 = make([]int64, 256) index int64 = 0 i int64 = 0 // Difference in data and pattern length. ld int64 = dl - pl // Last pattern's byte position. lpbp int64 = pl - 1 ) for i = 0; i < 256; i++ { badChars[i] = pl } for i = 0; i < lpbp; i++ { badChars[bmh.pattern[i]] = lpbp - i } // Start search. for index <= ld { innerLoop: for i = lpbp; bmh.bfr.ReadByteAt(index+i) == bmh.pattern[i]; i-- { if i == 0 { indices = append(indices, index) break innerLoop } } index += badChars[bmh.bfr.ReadByteAt(index+lpbp)] } srs = newSearchResults().putMany(bmh.pattern, indices) return }
f516edfe797006773cb98d32863f08e1f8356606
[ "Markdown", "Go" ]
7
Go
pkorotkov/bpm
ac0c187fb3be43ef4571a3b212620f0af479dce5
a65a5a5ee559a38b95d914af8341c55e533f1ac5
refs/heads/master
<repo_name>BSP-Embed/Home-Automation-By-VR-2016<file_sep>/Source Code/App/main.c #include "main.h" extern int8u lcdptr; const char *VoiceComm[] = {"Door Open", "Door Close", "Light ON", "Light OFF", "Fan ON", "Fan OFF", "Charger ON","Charger OFF"}; int main(void) { init(); while (TRUE) { if (Flag.ChkVoi) { VoiceRecog(); Flag.ChkVoi = FALSE; } if(Flag.Sw) { Flag.Sw = FALSE; VoiceTrain(); } sleep(); } return 0; } static void VoiceRecog(void) { int8u x; x = SDRecognize('B')-'A'; if (x <= 7) { lcdclr(); lcdws("Voice Recognized"); lcdr2(); lcdws(VoiceComm[x]); beep(1,100); switch(x) { case 0: Flag.Door = TRUE; Forward(); dlyms(5000); Stop(); break; case 1: Flag.Door = FALSE; Backward(); dlyms(5000); Stop(); break; case 2: if (Flag.Door) LightOn(); break; case 3: LightOff(); break; case 4: if (Flag.Door) FanOn(); break; case 5: FanOff(); break; case 6: if (Flag.Door) ChargerOn(); break; case 7: ChargerOff(); break; } dlyms(DISP_DLY); disptitl(); } } static void VoiceTrain(void) { int8u i; VoiceErase(); lcdclr(); lcdws("Voice Training"); beep(1,100); for (i = 0; i <= 7; i++) { lcdclrr(1); lcdws(VoiceComm[i]); dlyms(1000); while (!VrTrain('B', 'A' + i)); lcdclrr(1); lcdws("Success"); } beep(2,200); disptitl(); } static void VoiceErase(void) { int8u i; lcdclr(); lcdws("Erasing"); for (i = 0; i <= 7; i++) { lcdclrr(1); lcdws(VoiceComm[i]); beep(2,75); while (!EraseTraining('B', 'A' + i)); lcdclrr(1); lcdws("Success"); } } static void init(void) { buzinit(); beep(2,100); gpioinit(); ledinit(); lcdinit(); uartinit(); tmr1init(); motorinit(); EXT0init(); // if (VoiceRecognitionInitialize()) { // lcdptr = 0xc5; // setTimeOut(); // AddSDComm(); // SetLevel(); // lcdws("Success"); // } disptitl(); sei(); } static void gpioinit(void) { RELAY_DDR |= 0x07; RELAY_PORT &= ~(0x07); } static void disptitl(void) { lcdclr(); lcdws("Home Auto by VR"); } static void tmr1init(void) { TCNT1H = 0xD3; TCNT1L = 0x00; TIMSK |= _BV(TOIE1); //ENABLE OVERFLOW INTERRUPT TCCR1A = 0x00; TCCR1B |= _BV(CS10) | _BV(CS11); /* PRESCALAR BY 16 */ } /* overflows at every 100msec */ ISR(TIMER1_OVF_vect) { static int8u i,j,k; TCNT1H = 0xD3; TCNT1L = 0x00; if (++i >= 50) i = 0; switch(i) { case 0: case 2: ledon(); break; case 1: case 3: ledoff(); break; } if (++j >= 2) { j = 0; Flag.ChkVoi = TRUE; } } static void EXT0init(void) { INTDDR &= ~_BV(INT0_PIN); INTPORT |= _BV(INT0_PIN); GICR |= _BV(INT0); //ENABLE EXTERNAL INTERRUPT MCUCR |= _BV(ISC01); //FALLING EDGE INTERRUPT } ISR(INT0_vect) { Flag.Sw = TRUE; GICR |= _BV(INT0); } <file_sep>/Source Code/Source/vr.c //include .h file #include"vr.h" //Global Variables unsigned char Position = 0x40; //functions unsigned char VoiceRecognitionInitialize(void) { do { putchar ('b'); }while (getchar() != 'o'); return 1; } void SetLevel(void) { putchar('v'); putchar('B'); while (getchar() != 'o'); } static void SelectIndex(void) { unsigned char Index; lcdr2(); lcdws("SW2 TO INDEX NO."); dlyms(1000); for(;;) { if(Switch2Pressed()) { if(Position++ == 0x4A) Position = 0x41; Index = Position - 0x41; lcdr2(); lcdws(" INDEX No.="); lcdwint(0xCB, Index); lcdws(" "); dlyms(200); } if(Switch1Pressed()) break; } } int8u VrTrain(char GroupID, int8u index) { lcdr2(); lcdws(" Speak Now... "); lcdr2(); switch(TrainCommand(GroupID, index)) { case 0x74: lcdws(" Time Out "); dlyms(1000); return (0); break; case 0x65: lcdws(" ERROR "); dlyms(1000); return (0); break; case 0x6F: case 0x73: lcdws(" "); dlyms(500); return (1); break; case 0x72: default: lcdws(" "); dlyms(500); return (0); break; } } static unsigned char SpeakNow(void) { lcdr2(); lcdws(" Speak Now... "); lcdr2(); switch(TrainCommand('B', Position)) { case 0x74: lcdws(" Time Out "); dlyms(1000); return (0); break; case 0x65: lcdws(" ERROR "); dlyms(1000); return (0); break; case 0x6F: case 0x73: lcdws(" "); dlyms(500); return (1); break; case 0x72: default: lcdws(" "); dlyms(500); break; } } void setTimeOut(void) { do { putchar ('o'); dlyms(10); putchar ('D'); /* 5 seconds */ }while (getchar() != 'o'); } void AddSDComm(void) { puts("gBA"); while (getchar() != 'o'); // puts("gDBDBSP"); // while (getchar() != 'o'); } static unsigned char TrainCommand(unsigned char GroupIndex, unsigned char Position) { putchar(CMD_TRAIN_SD); //ascii value 't' to train command putchar(GroupIndex); //Group Number range ascii A to Q putchar(Position); return (getchar()); } unsigned char SDRecognize(unsigned char GroupIndex) { unsigned char SerialData; putchar(CMD_RECOG_SD); //ascii value 'd' to recognize command putchar(GroupIndex); //Group Number ascii characters A to Q if((SerialData = getchar()) == STS_RESULT) { dlyms(200); putchar(' '); return (getchar()); } else return (SerialData); } /****************************** ERASE TRAINING **************************/ unsigned char VoiceEraseTraining(void) { lcdclr(); lcdws(" ERASE TRAINING "); dlyms(1000); SelectIndex(); if(EraseTraining('B', Position)) { lcdr2(); lcdws(" SUCCESS "); dlyms(1000); return (1); } else { lcdr2(); lcdws(" FAIL "); dlyms(1000); return (0); } } unsigned char EraseTraining(unsigned char GroupIndex, unsigned char Position) { putchar(CMD_ERASE_SD); //ascii value to erase training of command putchar(GroupIndex); //Group Number range ascii A to Q putchar(Position); if(getchar() == STS_SUCCESS) return (1); else return (0); }<file_sep>/Source Code/App/main.h #ifndef MAIN_H #define MAIN_H #include "includes.h" #define INTDDR DDRD #define INTPORT PORTD #define INT0_PIN PD2 #define INT1_PIN PD3 #define RELAY_DDR DDRA #define RELAY_PORT PORTA #define LIGHT_PIN PA0 #define FAN_PIN PA1 #define CHARGER_PIN PA2 //DEFINE CONSTANT #define INFO_EE_ADDR 0x01 #define DELTA 4 enum {VOICE = 1, CTRL}; //DEFINE MACROS #define StartTmr() TCCR0 |= _BV(CS01) #define StopTmr() TCCR0 &= ~_BV(CS01) #define LightOn() RELAY_PORT |= _BV(LIGHT_PIN) #define LightOff() RELAY_PORT &= ~_BV(LIGHT_PIN) #define FanOn() RELAY_PORT |= _BV(FAN_PIN) #define FanOff() RELAY_PORT &= ~_BV(FAN_PIN) #define ChargerOn() RELAY_PORT |= _BV(CHARGER_PIN) #define ChargerOff() RELAY_PORT &= ~_BV(CHARGER_PIN) struct { volatile int8u ChkVoi:1; volatile int8u Door:1; volatile int8u Sw:1; } Flag; //FUNCTION PROTOTYPES static void init (void); static void disptitl (void); static void tmr1init (void); static void EXT0init (void); static void gpioinit (void); static void VoiceTrain (void); static void VoiceErase (void); static void VoiceRecog (void); #endif
dfc423f563b18fba16992d7f0d1feebc5a1d6565
[ "C" ]
3
C
BSP-Embed/Home-Automation-By-VR-2016
bd3c54935b7596f95108dd0215de2180476410b5
8b68bfa27371b02caa4ba5109946febdbab695e2
refs/heads/master
<file_sep>reverse_each_word(sentence1) = "olleH ,ereht dna woh era ?ouy"
303c517e2d96f44b6e31321485f26e7b38961759
[ "Ruby" ]
1
Ruby
ScarlettUtopia/ruby-enumerables-reverse-each-word-lab-seattle-web-071519
904dc3783c4cfa918d1df3f19d4a48aba44be930
1be9fdc715178bcf733a22bcfb47a9deab7f4720
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {AdminComponent} from './admin/admin.component'; import {DriverComponent} from './driver/driver.component'; import {PassengerComponent} from './passenger/passenger.component'; const routes: Routes = [ { path:'admin', component:AdminComponent }, { path:'driver', component:DriverComponent }, { path:'passenger', component:PassengerComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // Components import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AppheadComponent } from './apphead/apphead.component'; import { SidebarComponent } from './sidebar/sidebar.component'; import { DriverComponent } from './driver/driver.component'; import { PassengerComponent } from './passenger/passenger.component'; import { AdminComponent } from './admin/admin.component'; // Services import {HttpClient, HttpClientModule} from '@angular/common/http'; import { UserprofileComponent } from './userprofile/userprofile.component'; @NgModule({ declarations: [ AppComponent, SidebarComponent, DriverComponent, PassengerComponent, AdminComponent, AppheadComponent, UserprofileComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import {DriverdataService} from '../driverdata.service'; import {observable} from 'rxjs'; @Component({ selector: 'app-driver', templateUrl: './driver.component.html', styleUrls: ['./driver.component.scss'] }) export class DriverComponent implements OnInit { users$: Object; constructor(private data: DriverdataService) { } ngOnInit() { this.data.getDrivers().subscribe( data => this.users$ = data ); } }
911088b7f02343dd6c72765c731de1266a20c89a
[ "TypeScript" ]
3
TypeScript
millesinghe/adminPortal
d1ccc3790f1a74058d6c563660e6f87f74bcc4e9
b2afac6251d4da793ac1ee03f15644618a51deaf
refs/heads/master
<file_sep>1 - Generate from the following object a constructor function ```javascript var person = { _name: "Juan", getName: function() { return this._name; }, getSteps: function() { return this.walk.steps; }, walk: (function () { function walk() { walk.steps++; } walk.steps = 0; return walk; })(); }; function Person (_name) { // Opcion privada 1 // Privado por convensión pero se puede modificar desde afuera // this._name = _name; // Opcion privada 2 // getName es privilegiado, accese a la var privada _name // esto deberia estar en el prototype para que no haya una function por cada instancia // Esto nos sirve para ocultar información sensible this.getName = function () { return _name; }; // Opción 1 metodo privilegiado var _steps = 0; this.getSteps = function () { return _steps; }; this.walk = function () { _steps++; } } // Todo esto mismo pero con prototype, es más performante pero son publicas las vars _name y _steps. `` 2 - Implement a function `construct` with the following signature: `construct(Constructor: Function, args: Array): Object` It must reproduce exactly the behaviour of the operator `new`. **Example** ```javascript function Person(name) { this._name = name; } Person.prototype.sayHello = function() { console.log("Hi, I'm " + this._name); } var person1 = new Person("juan"); var person2 = construct(Person, [ "pepe" ]); console.log(person1 instanceof Person); // true console.log(person1._name); // "juan" console.log(person2 instanceof Person); // true console.log(person2._name); // "pepe" ``` // operador new function construct(Constructor, args) { var instance = Object.create(Constructor.prototype); var result = Constructor.apply(instance, args); return result !== null && typeof result === "object" ? result : instance; } <file_sep>// add the corresponding listeneres in order to // 1 - if a personality is selected it must be displayed on the right // of the personality list // 2 - the browser must only redirect to the twitter handle if it is clicked // on the personality selected (not on the list) // document.querySelector('#personalities').addEventListener('click', function (event) { // // if (event.target.tagName === 'A') { // // console.log('enviar a tw'); // // } else { // // event.preventDefault(); // // } // if (event.target.tagName === 'UL' || event.target.tagName === 'LI' || event.target.tagName === 'A') { // loadPersonaloty(event.target); // selectPersonality(event.target); // } // }); // function loadPersonaloty (clicked) { // var personalityContainer = document.querySelector('#personalitySelected'); // personalityContainer.innerHTML = clicked.textContent; // } // function selectPersonality (clicked) { // console.log(clicked); // var allPersonalitys = document.querySelectorAll('.Personalities-personality'); // for (var i = 0; i < allPersonalitys.length; i++) { // allPersonalitys[i].className = 'Personalities-personality'; // } // clicked += ' selected'; // if (clicked === 'UL') { // } // } document.addEventListener('DOMcontentLoad', function (event) { var personalities = document.getElementById('personalities'); personalities.addEventListener('click', function (event) { var target = event.target; if (target.nodeName === 'A') { event.preventDefault(); } event.stopImmediatePropagation(); // insert en dom function insertPersonality(); }); }); function insertPersonality () { } <file_sep>// * exports // - default: class // * constructor parameters // - legs: the amount of legs the walker has // * methods // - getLegs : It returns the amount of legs (the ones received in the constructor) // - getSteps: It returns the amount of steps done // - walk : It increments the amount of steps done import LivingCreature from "./living-creature"; class Walker extends LivingCreature { constructor(legs) { super(); this._legs = legs; this._steps = null; } getLegs() { if (typeof this._legs !== 'number') { throw new Error('The amount of legs provided is not a number'); } return this._legs; } getSteps() { return this._steps; } walk() { this._steps += 1; } } export default Walker; <file_sep>1 - Transform the following singleton (calculator) to a proper (stateless or stateful) module representation (it has to receive the export destination) ```javascript var calculator = { _result: 0, add: function(value) { this._result += value; }, substract: function(value) { this._result -= value; }, multiply: function(value) { this._result *= value; }, divide: function(value) { this._result /= value; } getResult: function() { return this._result; } }; ``` 2 - Apply all the changes required to convert the module that you created in the previous exercise to its opposite (if it was stateless, then create its stateful version, and if it was stateful, then create its stateless version) (function (module, exports, Module2, Module5) { var _result = 0, value = exports.value; function add (value) { _result += value; } function substract (value) { _result -= value; } function multiply (value) { _result *= value; } function divide (value) { _result /= value; } function getResult () { return _result; } module.exports = { apiAdd: add, apiSubstract: substract, apiMultiply: multiply, apiDivide: divide, apiGetResult: getResult }; }).apply( undefined, ( ( (typeof module === "object" && module !== null) && (typeof module.exports === "object" && module.exports !== null) ) ? [ module, module.exports ] : [ { exports: (App.Module1 = {}) }, App.Module1 ] ) // dependencies .concat(App.Module2, App.Module5) );<file_sep>var Walker = require("./walker"); // * constructor parameters // - oxygen: initial amount of oxygen // * methods // - getRemainingOxygen: It returns the amount of remaining oxygen // - breath : It increments the amount of remaining oxygen // - consumeOxygen : It decrements the amount of remaining oxygen // - hasDied : It returns true if the amount of oxygen is zero and false otherwise <<<<<<< HEAD:object-creation-patterns/exercises/inheritance/src/living-criature.js function LivingCriature (initialOxygen, legs) { if (typeof initialOxygen !== 'number') { throw new Error('the oxygen provided is not a number'); } if (initialOxygen < 0) { throw new Error('the oxygen provided is not a number'); } this.oxigen = initialOxygen; if(legs === undefined) { return; } Walker.call(this, legs); } LivingCriature.prototype = Object.create(Walker.prototype); LivingCriature.prototype.constructor = LivingCriature; LivingCriature.prototype.getRemainingOxygen = function () { return this.oxigen; }; LivingCriature.prototype.breath = function () { if(this.hasDied()) { throw new Error('it has died'); } this.oxigen += 1; }; LivingCriature.prototype.consumeOxygen = function () { if(this.hasDied()) { throw new Error('it has died'); } this.oxigen -= 1; }; LivingCriature.prototype.hasDied = function () { if (this.oxigen === 0) { return true; } else { return false; } }; module.exports = LivingCriature; ======= function LivingCreature() { } module.exports = LivingCreature; >>>>>>> upstream/master:object-creation-patterns/exercises/inheritance/src/living-creature.js <file_sep>var assert = require("assert"); var Walker = require("../src/walker"); var LivingCriature = require("../src/living-criature"); // * inherits from // - LivingCreature // - Walker // * constructor parameters: // - the ones required to be passed to their ancestor // * methods // - walk // - must throw an exception if it has died // - must consume oxygen and walk <<<<<<< HEAD:object-creation-patterns/exercises/inheritance/src/walking-criature.js function WalkingCriature(oxigen, legs) { LivingCriature.call(this, oxigen, legs); } WalkingCriature.prototype = Object.create(LivingCriature.prototype); WalkingCriature.prototype.constructor = WalkingCriature; WalkingCriature.prototype.walk = function () { if (WalkingCriature.prototype.hasDied.call(this)) { throw new Error('it has died'); } Walker.prototype.walk.call(this); LivingCriature.prototype.consumeOxygen.call(this); }; module.exports = WalkingCriature; ======= function WalkingCreature() { } module.exports = WalkingCreature; >>>>>>> upstream/master:object-creation-patterns/exercises/inheritance/src/walking-creature.js
f578632a370f354a825ffa6ed4b61cf8a1544e6f
[ "Markdown", "JavaScript" ]
6
Markdown
ibarbieri/frontend-training
7dd18b7ccdaa40020f4eaa53f23b71513d7660f4
dba49b2431c52c8935b5226ab6b8e2c840186572
refs/heads/master
<file_sep>#include <stdio.h> #include "Student.h" Student::Student(std::string fn, std::string ln, int y, Major m) : _first_name(fn), _last_name(ln), _grad_year(y), _major(m) {} Student::~Student() {} float Student::getGpa() { float gpa = 0; for(int i = 0; i < _grades.size(); i++){ gpa = gpa + _grades[i]; } if (gpa != 0) { gpa = gpa/_grades.size(); } return gpa; } void Student::addGrade(float grade) { _grades.push_back(grade); } const std::string& Student::getLastName() { return _last_name; } void Student::printInfo() { std::string major; switch(_major) { case Major::EE: major = "EE"; break; case Major::ME: major = "ME"; break; case Major::CE: major = "CE"; break; case Major::CHE: major = "CHE"; break; case Major::BSE: major = "BSE"; break; case Major::ART: major = "ART"; break; case Major::ARCH: major = "ARCH"; break; } printf("%s, %s\n", _last_name.c_str(), _first_name.c_str()); printf("%s %d\n", major.c_str(), _grad_year); printf("GPA: %.2f\n", getGpa()); } <file_sep>#include "MastersStudent.h" // Constructor Implementations MastersStudent::MastersStudent(Student ug, int msy): Student(ug), _ms_grad_year(msy) {} MastersStudent::MastersStudent(std::string fn, std::string ln, int ugy, int msy, Major m): Student(fn, ln, ugy, m), _ms_grad_year(msy) {} // New methods specific to MastersStudent float MastersStudent::getMsGpa() { float msgpa = 0; for(int i = 0; i < _ms_grades.size(); i++){ msgpa = msgpa + _ms_grades[i]; } if (msgpa != 0) { msgpa = msgpa/_ms_grades.size(); } return msgpa; } void MastersStudent::addMsGrade(float grade) { _ms_grades.push_back(grade); } // Override Student's printInfo to include new fields void MastersStudent::printInfo() { Student::printInfo(); std::string major; switch(_major) { case Major::EE: major = "EE"; break; case Major::ME: major = "ME"; break; case Major::CE: major = "CE"; break; case Major::CHE: major = "CHE"; break; case Major::BSE: major = "BSE"; break; case Major::ART: major = "ART"; break; case Major::ARCH: major = "ARCH"; break; } printf("MS %s: %d\n", major.c_str(), _ms_grad_year); printf("MS GPA: %.2f\n", getMsGpa()); }
672d4d0b1d30375677d9941d062e89eae5dcbe8a
[ "C++" ]
2
C++
purplenicole730/ece160-hw06
1a062ceb1e545bc04a0cd152ab662afe59421628
0a240a818d0b1ab63b6cd628fe83cf00a4e25a25
refs/heads/master
<repo_name>XuseenNoah/MvcCharp<file_sep>/MvcCsharp/ViewModels/Persons.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MvcCsharp.ViewModels { public class Persons { public int Id { get; set; } [Required,StringLength(10,ErrorMessage ="Waxad galisay way ka badan tahay 10")] public string Name { get; set; } public string Addres { get; set; } public string Phone { get; set; } [DataType(DataType.Date)] public DateTime Date { get; set; } public HttpPostedFileBase Image { get; set; } public IEnumerable<ValidationResult> validations(ValidationContext validationContext) { if (Image != null) { if (Image.ContentType.Equals("Image/jpeg")) { yield return new ValidationResult("Only jpg files allowed", new string[] { "Image" }); } if (Image.ContentLength >= (4096 * 4096)) { yield return new ValidationResult("Signature must be less than 1mb ", new List<string> { "Image" }); } } } } }<file_sep>/MvcCsharp/Controllers/PersonsController.cs using MvcCsharp.Models; using MvcCsharp.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcCsharp.Controllers { [Authorize] public class PersonsController : Controller { Repository _repo = new Repository(); // GET: Persons [AllowAnonymous] public ViewResult CreatePerson() { return View(); } [HttpPost] //[ActionName("CreatePerson")] public ActionResult CreatePerson(Persons persons) { if (ModelState.IsValid) { _repo.CreatePerson(persons); TempData["Succes"] = "Succesfly Saved Record"; ModelState.Clear(); return RedirectToAction("ListPersons"); } return View(); } public ActionResult GetImage(string id) { var getImage = _repo.GetImage(id); return File(getImage, "Image/jpeg"); } public ActionResult DownloadImage(string id) { var getImage = _repo.GetImage(id); return File(getImage,"Image/jpeg","download.jpg"); } public ViewResult ListPersons(string CustomerName) { var getListPerson = _repo.ListPerson(CustomerName); return View(getListPerson); } public ActionResult Details(string id) { var getPerson = _repo.GetPerson(id); if (getPerson == null)ViewBag.NotFound="Ma jiro Qof Idga leh oo ku diwan gashan"; return View(getPerson); } //public ActionResult Delete(string id) //{ // var getPerson = _repo.GetPerson(id); // return View(getPerson); //} public ActionResult Delete(string id) { _repo.DeletePerson(id); TempData["SuccesfullyDeleted"] = "Succesfully Deleted"; return RedirectToAction(nameof(ListPersons)); } public ActionResult UpdatePerson(string id) { var getPerson = _repo.GetPerson(id); return View(getPerson); } [HttpPost] [ActionName("UpdatePerson")] public ActionResult Updated(Persons persons) { if (ModelState.IsValid) { _repo.UpdatePerson(persons); TempData["SuccesfullyUpdated"] = "Succesfully Updated"; ModelState.Clear(); return RedirectToAction(nameof(ListPersons)); } return View(persons); } } }<file_sep>/MvcCsharp/Controllers/MainController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcCsharp.Controllers { public class MainController :Controller { // GET: Main public ActionResult Index() { return View(); } public ActionResult Search(string name) { var input = Server.HtmlDecode(name); return Content(input); } //public ActionResult EmptyResutl() //{ // //return EmptyResutl(); // return PartialView(); // return Json(); // return JavaScript(); //} } }<file_sep>/MvcCsharp/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcCsharp.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult GetHOme() { //nreturn View(); //return Content("sdfdsfsdf"); //return RedirectToAction("Index"); //return Json(); //return new EmptyResult(); //return JavaScript(); return View(); //throw new ArithmeticException("fsdfsdf"); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }<file_sep>/MvcCsharp/Controllers/AccountController.cs using MvcCsharp.Models; using MvcCsharp.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace MvcCsharp.Controllers { public class AccountController : Controller { Auth_Repository _repo = new Auth_Repository(); // GET: Account public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Login login) { if (ModelState.IsValid) { var User = _repo.Authenticate(login); if (User != null) { Session["User"] = User; Session["Username"] = User.Username; FormsAuthentication.SetAuthCookie(User.Username, false); return RedirectToAction("Index", "Home"); } else { TempData["ErrorLogin"] = "Error Login"; } } return View(login); } public ActionResult Logout() { Session["User"] = null; FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); } } }<file_sep>/MvcCsharp/Models/Repository.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using MvcCsharp.ViewModels; namespace MvcCsharp.Models { public class Repository { public string dbconn = System.Configuration.ConfigurationManager.ConnectionStrings["Db"].ConnectionString; public void CreatePerson(Persons person) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = "INSERT INTO Persons VALUES (@Name,@Addres,@Phone,getdate(),@Image)"; cmd.Parameters.AddWithValue("@Name", person.Name); cmd.Parameters.AddWithValue("@Addres", person.Addres); cmd.Parameters.AddWithValue("@Phone", person.Phone); var bytes = new byte[person.Image.ContentLength]; person.Image.InputStream.Read(bytes, 0, person.Image.ContentLength); cmd.Parameters.AddWithValue("@Image", bytes); conn.Open(); cmd.ExecuteNonQuery(); } } internal object ListPerson(string CustomerName) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT *FROM Persons WHERE NAME LIKE @Search Or Phone LIKE @Phone"; cmd.Parameters.AddWithValue("@Phone", CustomerName + "%%"); cmd.Parameters.AddWithValue("@Search", CustomerName+"%%"); conn.Open(); var reader = cmd.ExecuteReader(); var listPersons = new List<Persons>(); while (reader.Read()) { var person = new Persons(); person.Id = (int)reader["Id"]; person.Name = reader["Name"] as string; person.Addres = reader["Addres"]as string; person.Phone = reader["Phone"]as string; person.Date = (DateTime)reader["Date"]; listPersons.Add(person); } return listPersons; } } internal byte[] GetImage(string id) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT Image FROM Persons WHERE Id=@Id"; cmd.Parameters.AddWithValue("@Id",id); conn.Open(); var reader = cmd.ExecuteScalar() as byte[]; return reader; } } internal void DeletePerson(string id) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"DELETE FROM Persons WHERE Id=@id"; cmd.Parameters.AddWithValue("@id", id); conn.Open(); cmd.ExecuteNonQuery(); } } public void UpdatePerson(Persons persons) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"UPDATE Persons SET Name=@Name,Addres=@Addres,Phone=@Phone WHERE Id=@Id "; cmd.Parameters.AddWithValue("@Name", persons.Name); cmd.Parameters.AddWithValue("@Addres", persons.Addres); cmd.Parameters.AddWithValue("@Phone", persons.Phone); cmd.Parameters.AddWithValue("@Id", persons.Id); conn.Open(); cmd.ExecuteNonQuery(); } } internal object GetPerson(string id) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT *FROM Persons WHERE Id=@Id"; cmd.Parameters.AddWithValue("@Id", id); conn.Open(); var reader=cmd.ExecuteReader(); Persons person = null; if (reader.Read()) { person = new Persons(); person.Id = (int)reader["Id"]; person.Name = reader["Name"] as string; person.Addres = reader["Addres"] as string; person.Phone = reader["Phone"] as string; person.Date = (DateTime)reader["Date"]; } return person; } } } }<file_sep>/MvcCsharp/Models/Auth_Repository.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using MvcCsharp.ViewModels; namespace MvcCsharp.Models { public class Auth_Repository { public string dbconn = System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString; internal Login Authenticate(Login login) { using (var conn = new SqlConnection(dbconn)) using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT *FROM Users where Username=@User AND Password=@<PASSWORD>"; cmd.Parameters.AddWithValue("@User", login.Username); cmd.Parameters.AddWithValue("@Pass", login.Password); conn.Open(); var reader = cmd.ExecuteReader(); Login loginEnter = null; if (reader.Read()) { loginEnter = new Login(); loginEnter.Username = reader["Username"] as string; loginEnter.Password = reader["<PASSWORD>"] as string; } return loginEnter; } } } }
f44da01c5872e747fcd281823a52c5aab91a4e49
[ "C#" ]
7
C#
XuseenNoah/MvcCharp
1a25cea143ce09863e82b0237dd05110f2d97c79
62ae9384066f10f999fd6e60c46512782c639cab
refs/heads/master
<file_sep>DIR="/home/$NB_USER/work/campusagh" if [ ! -d "$DIR" ]; then git clone https://github.com/kaskadz/jupyter-workshop-campusagh.git --depth 1 "$DIR"; fi<file_sep># Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. # Pin to version of notebook image that includes start-singleuser.sh script FROM jupyter/scipy-notebook:137a295ff71b # Use custom startup script USER jovyan COPY clone-notebooks.sh /home/$NB_USER/clone-notebook.sh USER root COPY docker-entrypoint.sh /srv/docker-entrypoint.sh CMD ["start-singleuser.sh"] USER jovyan
f7e3f83d67c2fcf468be4e17dc9e2068a593b733
[ "Dockerfile", "Shell" ]
2
Shell
kaskadz/jupyterhub-deploy-docker
f1cc79244a926ac6d695548324526b12e7727871
e541798fa5d943b71ad6b1c4f7ee25294ae4ad2c
refs/heads/master
<file_sep>package main import "fmt" func main() { numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println(numbers) test := numbers[0:3:5] fmt.Println(test) test = append(test, 44) fmt.Println(test) test = append(test, 55) fmt.Println(test) fmt.Println(numbers) } <file_sep>package main import ( "fmt" "runtime" ) func main() { runtime.GOMAXPROCS(1) c := make(chan int) go func() { for i := 0; i < 5; i++ { c <- i fmt.Println("c<-i", i) } close(c) }() useChanRange(c) // useVariable(c) } func useChanRange(c chan int) { for i := range c { fmt.Println(i) } } func useVariable(c chan int) { a, ok := <-c fmt.Println(a, ok) close(c) b, ok := <-c fmt.Println(b, ok) } <file_sep>package main import "fmt" func main() { for bottles := 99; bottles >= 0; bottles-- { switch { case bottles > 1: fmt.Printf("%d bottles of beer on the wall, %d bottles of beer.\n", bottles, bottles) s := "bottles" if bottles-1 == 1 { s = "bottle" } fmt.Printf("Take one down, pass it around, %d %s of beer on the wall.\n", bottles-1, s) case bottles == 1: fmt.Println("1 bottles of beer on the wall, 1 bottle of beer.\n") fmt.Printf("Take one down, pass it around, No more bottles of beer on the wall\n") default: fmt.Printf("No more bottles of beer on the wall, no more bottles of beer.\n") fmt.Printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n") } } } <file_sep>package main import ( "fmt" "runtime" ) func main() { runtime.GOMAXPROCS(1) c := num(1, 2) out := sumByChan(c) fmt.Println("sumByhan func : ", <-out) fmt.Println("sum func : ", <-sum(1, 2)) } func num(a, b int) <-chan int { out := make(chan int) go func() { out <- a out <- b close(out) }() return out } func sumByChan(c <-chan int) <-chan int { out := make(chan int) // 채널 생성 go func() { r := 0 for i := range c { // range를 사용하여 채널이 닫힐 때까지 값을 꺼내고 꺼낸 값을 모두 더함. r = r + i } out <- r }() return out // 채널 반환 } func sum(a, b int) <-chan int { out := make(chan int) // 채널 생성 go func() { out <- a + b // 채널에 a와 b의 합을 보냄 }() return out // 채널 반환 } <file_sep>package main import ( "fmt" "runtime" ) func main() { runtime.GOMAXPROCS(1) c := make(chan int) go producer(c) go consumer(c) fmt.Scanln() } func producer(c chan<- int) { for i := 0; i < 5; i++ { fmt.Println("producer :", i) c <- i } c <- 100 // fmt.Println(<-c) } func consumer(c <-chan int) { for i := range c { fmt.Println(i) } fmt.Println(<-c) //c <- 1 } <file_sep>package main import ( "fmt" "runtime" "time" ) func main() { runtime.GOMAXPROCS(1) done := make(chan bool, 2) count := 4 go func() { for i := 0; i < count; i++ { done <- true fmt.Println("고루틴 : ", i) } }() for i := 0; i < count; i++ { if i%2 == 0 { time.Sleep(1 * time.Second) } <-done fmt.Println("메인 : ", i) } fmt.Scanln() } <file_sep>package main import ( "fmt" "time" ) func main() { c1 := make(chan int) c2 := make(chan string) c3 := make(chan int) go func() { for { c1 <- 10 time.Sleep(100 * time.Millisecond) } }() go func() { for { c2 <- "Hello, world!" time.Sleep(500 * time.Millisecond) } }() //defaultCount := 0 go func() { for { select { case i := <-c1: fmt.Println("c1 : ", i) case s := <-c2: fmt.Println("c2 : ", s) //case now :=<-time.After(50 * time.Millisecond): // fmt.Println("timeout", now) case c3<- 10000: //default: // if defaultCount < 3 { // fmt.Println("default") // } // defaultCount++ } } }() go func() { for { select { case i := <-c3: time.Sleep(1 * time.Second) fmt.Println("c3 : ", i) } } }() time.Sleep(5 * time.Second) } <file_sep>package main import ( "fmt" "time" ) func main() { c1 := make(chan int) go func() { for { i := <-c1 fmt.Println("첫번째 고루틴 c1 :", i) time.Sleep(100 * time.Millisecond) } }() go func() { for { c1 <- 20 time.Sleep(500 * time.Millisecond) } }() go func() { for { select { case c1 <- 10: case i := <-c1: fmt.Println("select c1 : ", i) } } }() time.Sleep(5 * time.Second) }
19c5f60e52e67f0df0876bd1c4260a27f7136789
[ "Go" ]
8
Go
sungsu9022/study-golang
2fa3eed92249ce80386909f7128251c0c36300e0
45b6aebbdfce33cb77cdf724e0fcc3a28e84eb4a
refs/heads/master
<repo_name>Bogdan-Lyashenko/vscode-bookmarks<file_sep>/src/extension.ts /*--------------------------------------------------------------------------------------------- * Copyright (c) <NAME>. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import path = require("path"); import * as vscode from "vscode"; import { codicons } from "vscode-ext-codicons"; import { BookmarkedFile, NO_BOOKMARKS_AFTER, NO_BOOKMARKS_BEFORE, NO_MORE_BOOKMARKS } from "../vscode-bookmarks-core/src/api/bookmark"; import { Directions, isWindows, SEARCH_EDITOR_SCHEME } from "../vscode-bookmarks-core/src/api/constants"; import { Container } from "../vscode-bookmarks-core/src/container"; import { createTextEditorDecoration, updateDecorationsInActiveEditor } from "../vscode-bookmarks-core/src/decoration"; import { BookmarksController } from "../vscode-bookmarks-core/src/model/bookmarks"; import { loadBookmarks, saveBookmarks } from "../vscode-bookmarks-core/src/model/workspaceState"; import { expandSelectionToNextBookmark, selectBookmarkedLines, shrinkSelection } from "../vscode-bookmarks-core/src/selections"; import { BookmarksExplorer } from "../vscode-bookmarks-core/src/sidebar/bookmarkProvider"; import { parsePosition, Point } from "../vscode-bookmarks-core/src/sidebar/parser"; import { Sticky } from "../vscode-bookmarks-core/src/sticky/sticky"; import { suggestLabel, useSelectionWhenAvailable } from "../vscode-bookmarks-core/src/suggestion"; import { registerOpenSettings } from "./commands/openSettings"; import { registerSupportBookmarks } from "./commands/supportBookmarks"; import { registerHelpAndFeedbackView } from "./sidebar/helpAndFeedbackView"; import { registerWhatsNew } from "./whats-new/commands"; // this method is called when vs code is activated export function activate(context: vscode.ExtensionContext) { Container.context = context; const bookmarks: BookmarksController = new BookmarksController(); let activeEditorCountLine: number; let timeout: NodeJS.Timer; registerWhatsNew(); context.subscriptions.push(vscode.commands.registerCommand("_bookmarks.openFolderWelcome", () => { const openFolderCommand = isWindows ? "workbench.action.files.openFolder" : "workbench.action.files.openFileFolder" vscode.commands.executeCommand(openFolderCommand) })); // load pre-saved bookmarks const didLoadBookmarks: boolean = loadWorkspaceState(); // tree-view // const bookmarkProvider = new BookmarkProvider(bookmarks, context); // vscode.window.registerTreeDataProvider("bookmarksExplorer", bookmarkProvider); const bookmarkExplorer = new BookmarksExplorer(bookmarks, context); const bookmarkProvider = bookmarkExplorer.getProvider(); registerOpenSettings(); registerSupportBookmarks(); registerHelpAndFeedbackView(context); // bookmarkProvider.showTreeView(); context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(cfg => { // Allow change the gutterIcon without reload if (cfg.affectsConfiguration("bookmarks.gutterIconPath")) { if (bookmarkDecorationType) { bookmarkDecorationType.dispose(); } bookmarkDecorationType = createTextEditorDecoration(context); context.subscriptions.push(bookmarkDecorationType); updateDecorations(); } if (cfg.affectsConfiguration("bookmarks.saveBookmarksInProject")) { saveWorkspaceState(); } })); let bookmarkDecorationType = createTextEditorDecoration(context); context.subscriptions.push(bookmarkDecorationType); // Connect it to the Editors Events let activeEditor = vscode.window.activeTextEditor; if (activeEditor) { if (!didLoadBookmarks) { bookmarks.add(activeEditor.document.uri.fsPath); } activeEditorCountLine = activeEditor.document.lineCount; bookmarks.activeBookmark = bookmarks.fromUri(activeEditor.document.uri.fsPath); triggerUpdateDecorations(); } // new docs vscode.workspace.onDidOpenTextDocument(doc => { bookmarks.add(doc.uri.fsPath); }); vscode.window.onDidChangeActiveTextEditor(editor => { activeEditor = editor; if (editor) { activeEditorCountLine = editor.document.lineCount; bookmarks.activeBookmark = bookmarks.fromUri(editor.document.uri.fsPath); triggerUpdateDecorations(); } }, null, context.subscriptions); vscode.workspace.onDidChangeTextDocument(event => { if (activeEditor && event.document === activeEditor.document) { // triggerUpdateDecorations(); let updatedBookmark = false; // workaround for formatters like Prettier (#118) if (vscode.workspace.getConfiguration("bookmarks").get("useWorkaroundForFormatters", false)) { updateDecorations(); return; } // call sticky function when the activeEditor is changed if (bookmarks.activeBookmark && bookmarks.activeBookmark.bookmarks.length > 0) { updatedBookmark = Sticky.stickyBookmarks(event, activeEditorCountLine, bookmarks.activeBookmark, activeEditor, bookmarks); } activeEditorCountLine = event.document.lineCount; updateDecorations(); if (updatedBookmark) { saveWorkspaceState(); } } }, null, context.subscriptions); context.subscriptions.push(vscode.workspace.onDidRenameFiles(rename => { if (rename.files.length === 0) { return; } rename.files.forEach(async file => { const files = bookmarks.storage.fileList.map(file => file.path); const stat = await vscode.workspace.fs.stat(file.newUri); if (stat.type === vscode.FileType.File) { if (files.includes(file.oldUri.fsPath)) { bookmarks.storage.updateFilePath(file.oldUri.fsPath, file.newUri.fsPath); } } if (stat.type === vscode.FileType.Directory) { bookmarks.storage.updateDirectoryPath(file.oldUri.fsPath, file.newUri.fsPath); } }); bookmarkProvider.refresh(); saveWorkspaceState(); })); // Timeout function triggerUpdateDecorations() { if (timeout) { clearTimeout(timeout); } timeout = setTimeout(updateDecorations, 100); } // Evaluate (prepare the list) and DRAW function updateDecorations() { updateDecorationsInActiveEditor(activeEditor, bookmarks, bookmarkDecorationType); } vscode.commands.registerCommand("_bookmarks.jumpTo", (documentPath, line, column: string) => { const uriDocBookmark: vscode.Uri = vscode.Uri.file(documentPath); vscode.workspace.openTextDocument(uriDocBookmark).then(doc => { vscode.window.showTextDocument(doc ).then(() => { const lineInt: number = parseInt(line, 10); const colunnInt: number = parseInt(column, 10); // revealLine(lineInt - 1); revealPosition(lineInt - 1, colunnInt - 1); }); }); }); vscode.commands.registerCommand("bookmarks.refresh", () => { bookmarkProvider.refresh(); }); vscode.commands.registerCommand("_bookmarks.clearFromFile", node => { bookmarks.clear(node.bookmark); saveWorkspaceState(); updateDecorations(); }); vscode.commands.registerCommand("_bookmarks.deleteBookmark", node => { const book: BookmarkedFile = bookmarks.fromUri(node.command.arguments[0]); const index = book.indexOfBookmark(node.command.arguments[1] - 1); // bookmarks.indexOf({line: node.command.arguments[1] - 1}); bookmarks.removeBookmark(index, node.command.arguments[1] - 1, book); saveWorkspaceState(); updateDecorations(); }); vscode.commands.registerCommand("_bookmarks.editLabel", node => { const uriDocBookmark: vscode.Uri = vscode.Uri.file(node.command.arguments[0]); const book: BookmarkedFile = bookmarks.fromUri(uriDocBookmark.fsPath); const index = book.indexOfBookmark(node.command.arguments[1] - 1); const position: vscode.Position = new vscode.Position(node.command.arguments[1] - 1, node.command.arguments[2] - 1); // book.bookmarks[index].label = "novo label"; askForBookmarkLabel(index, position, book.bookmarks[index].label, false, book); }); vscode.commands.registerCommand("bookmarks.clear", () => clear()); vscode.commands.registerCommand("bookmarks.clearFromAllFiles", () => clearFromAllFiles()); vscode.commands.registerCommand("bookmarks.selectLines", () => selectBookmarkedLines(bookmarks)); vscode.commands.registerCommand("bookmarks.expandSelectionToNext", () => expandSelectionToNextBookmark(bookmarks, Directions.Forward)); vscode.commands.registerCommand("bookmarks.expandSelectionToPrevious", () => expandSelectionToNextBookmark(bookmarks, Directions.Backward)); vscode.commands.registerCommand("bookmarks.shrinkSelection", () => shrinkSelection(bookmarks)); vscode.commands.registerCommand("bookmarks.toggle", () => toggle()); vscode.commands.registerCommand("bookmarks.toggleLabeled", () => toggleLabeled()); vscode.commands.registerCommand("bookmarks.jumpToNext", () => jumpToNext(Directions.Forward)); vscode.commands.registerCommand("bookmarks.jumpToPrevious", () => jumpToNext(Directions.Backward)); vscode.commands.registerCommand("bookmarks.list", () => list()); vscode.commands.registerCommand("bookmarks.listFromAllFiles", () => listFromAllFiles()); function revealLine(line: number) { let reviewType: vscode.TextEditorRevealType = vscode.TextEditorRevealType.InCenter; if (line === vscode.window.activeTextEditor.selection.active.line) { reviewType = vscode.TextEditorRevealType.InCenterIfOutsideViewport; } const newSe = new vscode.Selection(line, 0, line, 0); vscode.window.activeTextEditor.selection = newSe; vscode.window.activeTextEditor.revealRange(newSe, reviewType); } function revealPosition(line, column: number) { if (isNaN(column)) { revealLine(line); } else { let reviewType: vscode.TextEditorRevealType = vscode.TextEditorRevealType.InCenter; if (line === vscode.window.activeTextEditor.selection.active.line) { reviewType = vscode.TextEditorRevealType.InCenterIfOutsideViewport; } const newSe = new vscode.Selection(line, column, line, column); vscode.window.activeTextEditor.selection = newSe; vscode.window.activeTextEditor.revealRange(newSe, reviewType); } } function loadWorkspaceState(): boolean { return loadBookmarks(bookmarks, context); } function saveWorkspaceState(): void { saveBookmarks(bookmarks, context); } function removeBasePathFrom(aPath: string, currentWorkspaceFolder: vscode.WorkspaceFolder): string { if (!vscode.workspace.workspaceFolders) { return aPath; } let inWorkspace: vscode.WorkspaceFolder; for (const wf of vscode.workspace.workspaceFolders) { if (aPath.indexOf(wf.uri.fsPath) === 0) { inWorkspace = wf; } } if (inWorkspace) { if (inWorkspace === currentWorkspaceFolder) { return aPath.split(inWorkspace.uri.fsPath).pop(); } else { if (!currentWorkspaceFolder && vscode.workspace.workspaceFolders.length === 1) { return aPath.split(inWorkspace.uri.fsPath).pop(); } else { return codicons.file_submodule + " " + inWorkspace.name + aPath.split(inWorkspace.uri.fsPath).pop(); } } // const base: string = inWorkspace.name ? inWorkspace.name : inWorkspace.uri.fsPath; // return path.join(base, aPath.split(inWorkspace.uri.fsPath).pop()); // return aPath.split(inWorkspace.uri.fsPath).pop(); } else { return codicons.file_directory + " " + aPath; } } // function list() { if (!vscode.window.activeTextEditor) { vscode.window.showInformationMessage("Open a file first to list bookmarks"); return; } // no active bookmark if (!bookmarks.activeBookmark) { vscode.window.showInformationMessage("No Bookmark found"); return; } // no bookmark if (bookmarks.activeBookmark.bookmarks.length === 0) { vscode.window.showInformationMessage("No Bookmark found"); return; } // push the items const items: vscode.QuickPickItem[] = []; // tslint:disable-next-line:prefer-for-of for (let index = 0; index < bookmarks.activeBookmark.bookmarks.length; index++) { const bookmarkLine = bookmarks.activeBookmark.bookmarks[index].line + 1; const bookmarkColumn = bookmarks.activeBookmark.bookmarks[index].column + 1; const lineText = vscode.window.activeTextEditor.document.lineAt(bookmarkLine - 1).text.trim(); if (bookmarks.activeBookmark.bookmarks[index].label === "") { items.push({ description: "(Ln " + bookmarkLine.toString() + ", Col " + bookmarkColumn.toString() + ")", label: lineText }); } else { items.push({ description: "(Ln " + bookmarkLine.toString() + ", Col " + bookmarkColumn.toString() + ")", label: codicons.tag + " " + bookmarks.activeBookmark.bookmarks[index].label }); } } // pick one const currentLine: number = vscode.window.activeTextEditor.selection.active.line + 1; const options = <vscode.QuickPickOptions> { placeHolder: "Type a line number or a piece of code to navigate to", matchOnDescription: true, // matchOnDetail: true, onDidSelectItem: item => { const itemT = <vscode.QuickPickItem> item; const point: Point = parsePosition(itemT.description); if (point) { revealPosition(point.line - 1, point.column - 1); } } }; vscode.window.showQuickPick(items, options).then(selection => { if (typeof selection === "undefined") { revealLine(currentLine - 1); return; } const itemT = <vscode.QuickPickItem> selection; const point: Point = parsePosition(itemT.description); if (point) { revealPosition(point.line - 1, point.column - 1); } }); } function clear() { if (!vscode.window.activeTextEditor) { vscode.window.showInformationMessage("Open a file first to clear bookmarks"); return; } bookmarks.clear(); saveWorkspaceState(); updateDecorations(); } function clearFromAllFiles() { bookmarks.clearAll(); saveWorkspaceState(); updateDecorations(); } function listFromAllFiles() { // no bookmark if (!bookmarks.hasAnyBookmark()) { vscode.window.showInformationMessage("No Bookmarks found"); return; } // push the items const items: vscode.QuickPickItem[] = []; const activeTextEditorPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri.fsPath : ""; const promisses = []; const currentLine: number = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.selection.active.line + 1 : -1; let currentWorkspaceFolder: vscode.WorkspaceFolder; if (activeTextEditorPath) { currentWorkspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(activeTextEditorPath)); } // for (let index = 0; index < bookmarks.bookmarks.length; index++) { for (const bookmark of bookmarks.storage.fileList) { const pp = bookmark.listBookmarks(); promisses.push(pp); } Promise.all(promisses).then( (values) => { for (const element of values) { if (element) { for (const elementInside of element) { if (elementInside.detail.toString().toLowerCase() === activeTextEditorPath.toLowerCase()) { items.push( { label: elementInside.label, description: elementInside.description } ); } else { const itemPath = removeBasePathFrom(elementInside.detail, currentWorkspaceFolder); items.push( { label: elementInside.label, description: elementInside.description, detail: itemPath } ); } } } } // sort // - active document // - no octicon - document in same workspaceFolder // - with octicon 'file-submodules' - document in another workspaceFolder // - with octicon - 'file-directory' - document outside any workspaceFolder const itemsSorted: vscode.QuickPickItem[] = items.sort(function(a: vscode.QuickPickItem, b: vscode.QuickPickItem): number { if (!a.detail && !b.detail) { return 0; } if (!a.detail && b.detail) { return -1; } if (a.detail && !b.detail) { return 1; } if ((a.detail.toString().indexOf(codicons.file_submodule + " ") === 0) && (b.detail.toString().indexOf(codicons.file_directory + " ") === 0)) { return -1; } if ((a.detail.toString().indexOf(codicons.file_directory + " ") === 0) && (b.detail.toString().indexOf(codicons.file_submodule + " ") === 0)) { return 1; } if ((a.detail.toString().indexOf(codicons.file_submodule + " ") === 0) && (b.detail.toString().indexOf(codicons.file_submodule + " ") === -1)) { return 1; } if ((a.detail.toString().indexOf(codicons.file_submodule + " ") === -1) && (b.detail.toString().indexOf(codicons.file_submodule + " ") === 0)) { return -1; } if ((a.detail.toString().indexOf(codicons.file_directory + " ") === 0) && (b.detail.toString().indexOf(codicons.file_directory + " ") === -1)) { return 1; } if ((a.detail.toString().indexOf(codicons.file_directory + " ") === -1) && (b.detail.toString().indexOf(codicons.file_directory + " ") === 0)) { return -1; } return 0; }); const options = <vscode.QuickPickOptions> { placeHolder: "Type a line number or a piece of code to navigate to", matchOnDescription: true, onDidSelectItem: item => { const itemT = <vscode.QuickPickItem> item; let filePath: string; // no detail - previously active document if (!itemT.detail) { filePath = activeTextEditorPath; } else { // with octicon - document outside project if (itemT.detail.toString().indexOf(codicons.file_directory + " ") === 0) { filePath = itemT.detail.toString().split(codicons.file_directory + " ").pop(); } else { // with octicon - documento from other workspaceFolder if (itemT.detail.toString().indexOf(codicons.file_submodule) === 0) { filePath = itemT.detail.toString().split(codicons.file_submodule + " ").pop(); for (const wf of vscode.workspace.workspaceFolders) { if (wf.name === filePath.split(path.sep).shift()) { filePath = path.join(wf.uri.fsPath, filePath.split(path.sep).slice(1).join(path.sep)); break; } } } else { // no octicon - document inside project if (currentWorkspaceFolder) { filePath = currentWorkspaceFolder.uri.fsPath + itemT.detail.toString(); } else { if (vscode.workspace.workspaceFolders) { filePath = vscode.workspace.workspaceFolders[0].uri.fsPath + itemT.detail.toString(); } else { filePath = itemT.detail.toString(); } } } } } const point: Point = parsePosition(itemT.description); if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document.uri.fsPath.toLowerCase() === filePath.toLowerCase()) { if (point) { revealPosition(point.line - 1, point.column - 1); } } else { const uriDocument: vscode.Uri = vscode.Uri.file(filePath); vscode.workspace.openTextDocument(uriDocument).then(doc => { vscode.window.showTextDocument(doc, { preserveFocus: true, preview: true }).then(() => { if (point) { revealPosition(point.line - 1, point.column - 1); } }); }); } } }; vscode.window.showQuickPick(itemsSorted, options).then(selection => { if (typeof selection === "undefined") { if (activeTextEditorPath === "") { return; } else { const uriDocument: vscode.Uri = vscode.Uri.file(activeTextEditorPath); vscode.workspace.openTextDocument(uriDocument).then(doc => { vscode.window.showTextDocument(doc).then(() => { revealLine(currentLine - 1); return; }); }); } } if (typeof selection === "undefined") { return; } const point: Point = parsePosition(selection.description); if (!selection.detail) { if (point) { revealPosition(point.line - 1, point.column - 1); } } else { let newPath: string; // with octicon - document outside project if (selection.detail.toString().indexOf(codicons.file_directory + " ") === 0) { newPath = selection.detail.toString().split(codicons.file_directory + " ").pop(); } else {// no octicon - document inside project if (selection.detail.toString().indexOf(codicons.file_submodule) === 0) { newPath = selection.detail.toString().split(codicons.file_submodule + " ").pop(); for (const wf of vscode.workspace.workspaceFolders) { if (wf.name === newPath.split(path.sep).shift()) { newPath = path.join(wf.uri.fsPath, newPath.split(path.sep).slice(1).join(path.sep)); break; } } } else { // no octicon - document inside project if (currentWorkspaceFolder) { newPath = currentWorkspaceFolder.uri.fsPath + selection.detail.toString(); } else { if (vscode.workspace.workspaceFolders) { newPath = vscode.workspace.workspaceFolders[0].uri.fsPath + selection.detail.toString(); } else { newPath = selection.detail.toString(); } } } } const uriDocument: vscode.Uri = vscode.Uri.file(newPath); vscode.workspace.openTextDocument(uriDocument).then(doc => { vscode.window.showTextDocument(doc).then(() => { if (point) { revealPosition(point.line - 1, point.column - 1); } }); }); } }); } ); } function jumpToNext(direction: Directions) { if (!vscode.window.activeTextEditor) { vscode.window.showInformationMessage("Open a file first to jump to bookmarks"); return; } if (!bookmarks.activeBookmark) { return; } // bookmarks.activeBookmark.nextBookmark(vscode.window.activeTextEditor.selection.active, direction) .then((next) => { if (typeof next === "number") { if (!checkBookmarks(next)) { return; } bookmarks.nextDocumentWithBookmarks(bookmarks.activeBookmark, direction) .then((nextDocument) => { if (nextDocument === NO_MORE_BOOKMARKS) { return; } // same document? const activeDocument = BookmarksController.normalize(vscode.window.activeTextEditor.document.uri.fsPath); if (nextDocument.toString() === activeDocument) { const bookmarkIndex = direction === Directions.Forward ? 0 : bookmarks.activeBookmark.bookmarks.length - 1; revealPosition(bookmarks.activeBookmark.bookmarks[bookmarkIndex].line, bookmarks.activeBookmark.bookmarks[bookmarkIndex].column); } else { vscode.workspace.openTextDocument(nextDocument.toString()).then(doc => { vscode.window.showTextDocument(doc).then(() => { const bookmarkIndex = direction === Directions.Forward ? 0 : bookmarks.activeBookmark.bookmarks.length - 1; revealPosition(bookmarks.activeBookmark.bookmarks[bookmarkIndex].line, bookmarks.activeBookmark.bookmarks[bookmarkIndex].column); }); }); } }) .catch(checkBookmarks); } else { revealPosition(next.line, next.character); } }) .catch((error) => { console.log("activeBookmark.nextBookmark REJECT" + error); }); } function checkBookmarks(result: number | vscode.Position): boolean { if (result === NO_BOOKMARKS_BEFORE || result === NO_BOOKMARKS_AFTER) { vscode.window.showInformationMessage("No more bookmarks"); return false; } return true; } function askForBookmarkLabel(index: number, position: vscode.Position, oldLabel?: string, jumpToPosition?: boolean, book?: BookmarkedFile) { const ibo = <vscode.InputBoxOptions> { prompt: "Bookmark Label", placeHolder: "Type a label for your bookmark", value: oldLabel }; vscode.window.showInputBox(ibo).then(bookmarkLabel => { if (typeof bookmarkLabel === "undefined") { return; } // 'empty' if (bookmarkLabel === "" && oldLabel === "") { vscode.window.showWarningMessage("You must define a label for the bookmark."); return; } if (index >= 0) { bookmarks.removeBookmark(index, position.line, book); } bookmarks.addBookmark(position, bookmarkLabel, book); // toggle editing mode if (jumpToPosition) { vscode.window.showTextDocument(vscode.window.activeTextEditor.document, { preview: false, viewColumn: vscode.window.activeTextEditor.viewColumn }); } // sorted /* let itemsSorted = [] =*/ const b: BookmarkedFile = book ? book : bookmarks.activeBookmark; b.sortBookmarks(); saveWorkspaceState(); updateDecorations(); }); } async function toggle() { if (!vscode.window.activeTextEditor) { vscode.window.showInformationMessage("Open a file first to toggle bookmarks"); return; } if (vscode.window.activeTextEditor.document.uri.scheme === SEARCH_EDITOR_SCHEME) { vscode.window.showInformationMessage("You can't toggle bookmarks in Search Editor"); return; } const selections = vscode.window.activeTextEditor.selections; // fix issue emptyAtLaunch if (!bookmarks.activeBookmark) { bookmarks.add(vscode.window.activeTextEditor.document.uri.fsPath); bookmarks.activeBookmark = bookmarks.fromUri(vscode.window.activeTextEditor.document.uri.fsPath); } if (await bookmarks.toggle(selections)) { vscode.window.showTextDocument(vscode.window.activeTextEditor.document, {preview: false, viewColumn: vscode.window.activeTextEditor.viewColumn} ); } bookmarks.activeBookmark.sortBookmarks(); saveWorkspaceState(); updateDecorations(); } async function toggleLabeled() { if (!vscode.window.activeTextEditor) { vscode.window.showInformationMessage("Open a file first to toggle bookmarks"); return; } const selections = vscode.window.activeTextEditor.selections; // fix issue emptyAtLaunch if (!bookmarks.activeBookmark) { bookmarks.add(vscode.window.activeTextEditor.document.uri.fsPath); bookmarks.activeBookmark = bookmarks.fromUri(vscode.window.activeTextEditor.document.uri.fsPath); } let suggestion = suggestLabel(vscode.window.activeTextEditor.selection); if (suggestion !== "" && useSelectionWhenAvailable()) { if (await bookmarks.toggle(selections, suggestion)) { vscode.window.showTextDocument(vscode.window.activeTextEditor.document, {preview: false, viewColumn: vscode.window.activeTextEditor.viewColumn} ); } bookmarks.activeBookmark.sortBookmarks(); saveWorkspaceState(); updateDecorations(); return; } // ask label let oldLabel = ""; if (suggestion === "" && selections.length === 1) { const index = bookmarks.activeBookmark.indexOfBookmark(selections[0].active.line); oldLabel = index > -1 ? bookmarks.activeBookmark.bookmarks[index].label : ""; suggestion = oldLabel; } // let oldLabel: string = ""; // if (selections.length === 1) { // const index = bookmarks.activeBookmark.indexOfBookmark(selections[0].active.line); // oldLabel = index > -1 ? bookmarks.activeBookmark.bookmarks[index].label : ""; // } const ibo = <vscode.InputBoxOptions> { prompt: "Bookmark Label", placeHolder: "Type a label for your bookmark", value: suggestion }; const newLabel = await vscode.window.showInputBox(ibo); if (typeof newLabel === "undefined") { return; } if (newLabel === "" && oldLabel === "") { vscode.window.showWarningMessage("You must define a label for the bookmark."); return; } if (await bookmarks.toggle(selections, newLabel)) { vscode.window.showTextDocument(vscode.window.activeTextEditor.document, {preview: false, viewColumn: vscode.window.activeTextEditor.viewColumn} ); } // sorted /* let itemsSorted = [] =*/ const b: BookmarkedFile = bookmarks.activeBookmark; b.bookmarks.sort((n1, n2) => { if (n1.line > n2.line) { return 1; } if (n1.line < n2.line) { return -1; } return 0; }); saveWorkspaceState(); updateDecorations(); } }<file_sep>/src/whats-new/contentProvider.ts /*--------------------------------------------------------------------------------------------- * Copyright (c) <NAME>. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ // tslint:disable-next-line:max-line-length import { ChangeLogItem, ChangeLogKind, ContentProvider, Header, Image, Sponsor, IssueKind } from "../../vscode-whats-new/src/ContentProvider"; export class WhatsNewBookmarksContentProvider implements ContentProvider { public provideHeader(logoUrl: string): Header { return <Header>{ logo: <Image>{ src: logoUrl, height: 50, width: 50 }, message: `<b>Bookmarks</b> helps you to navigate in your code, <b>moving</b> between important positions easily and quickly. No more need to <i>search for code</i>. It also supports a set of <b>selection</b> commands, which allows you to select bookmarked lines and regions between lines.`}; } public provideChangeLog(): ChangeLogItem[] { const changeLog: ChangeLogItem[] = []; changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "12.0.0", releaseDate: "November 2020" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Adds <b>Open Settings</b> command to the Side Bar", id: 352, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Adds <b>Toggle Labeled</b> command to the Context Menu", id: 342, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.CHANGED, detail: { message: "Switch initialization to <b>onStartupFinished</b> API", id: 343, kind: IssueKind.PR, kudos: "@jasonwilliams" } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Clearing bookmark label through <b>Toggle Labeled</b> command leaving leading spaces", id: 344, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Leading spaces while using Move Line Up/Down", id: 348, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "<b>Ghost</b> Bookmarks after renaming files", id: 209, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Use <b>vscode-ext-help-and-feedback</b> package", id: 346, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "11.4.0", releaseDate: "October 2020" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Support clear the bookmark label in <b>Toggle Labeled</b> and <b>Edit Label</b> commands", id: 320, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.CHANGED, detail: { message: "Localization support - zh-cn", id: 327, kind: IssueKind.PR, kudos: "@loniceras" } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Typo in Side Bar welcome page", id: 316, kind: IssueKind.PR, kudos: "@osteele" } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "11.3.1", releaseDate: "June 2020" } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "<b>Open Folder</b> command in Welcome view not working on Windows", id: 310, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Stars visibility on Marketplace", id: 314, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "11.3.0", releaseDate: "June 2020" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Auto-save bookmarks when changing <b>saveBookmarksInProject</b> setting", id: 242, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.CHANGED, detail: { message: "Internal commands can't be customisable", id: 306, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Migrate from TSLint to ESLint", id: 290, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Remove <b>vscode</b> dependency", id: 296, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Use <b>vscode-ext-codicons</b> package", id: 309, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "11.2.0", releaseDate: "May 2020" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Adds <b>Label suggestion</b> based on selection", id: 239, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "<b>Side bar</b> welcome message", id: 284, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.CHANGED, detail: { message: "The <b>Bookmark position</b> in the <b>Side Bar</b> became more subtle", id: 295, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.FIXED, detail: { message: "Avoid Bookmarks from being toggled in the new Search Editor", id: 279, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "11.1.0", releaseDate: "April 2020" } }); changeLog.push({ kind: ChangeLogKind.NEW, detail: { message: "Adds <b>Multi cursor</b> support", id: 77, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Support VS Code package split", id: 263, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Support <b>ThemeIcon</b>", id: 269, kind: IssueKind.Issue } }); changeLog.push({ kind: ChangeLogKind.INTERNAL, detail: { message: "Support Extension View Context Menu", id: 270, kind: IssueKind.Issue } }); return changeLog; } public provideSponsors(): Sponsor[] { const sponsors: Sponsor[] = []; const sponsorCodeStream: Sponsor = <Sponsor>{ title: "Learn more about Codestream", link: "https://sponsorlink.codestream.com/?utm_source=vscmarket&utm_campaign=bookmarks&utm_medium=banner", image: "https://alt-images.codestream.com/codestream_logo_bookmarks.png", width: 35, message: `<p>Eliminate context switching and costly distractions. Create and merge PRs and perform code reviews from inside your IDE while using jump-to-definition, your keybindings, and other IDE favorites.</p>`, extra: `<a title="Learn more about CodeStream" href="https://sponsorlink.codestream.com/?utm_source=vscmarket&utm_campaign=bookmarks&utm_medium=banner"> Learn more</a>` }; sponsors.push(sponsorCodeStream); return sponsors; } }<file_sep>/src/sidebar/helpAndFeedbackView.ts /*--------------------------------------------------------------------------------------------- * Copyright (c) <NAME>. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ExtensionContext } from "vscode"; import { HelpAndFeedbackView, Link, StandardLinksProvider, ProvideFeedbackLink, Command } from "vscode-ext-help-and-feedback-view"; export function registerHelpAndFeedbackView(context: ExtensionContext) { const items = new Array<Link | Command>(); const predefinedProvider = new StandardLinksProvider('alefragnani.Bookmarks'); items.push(predefinedProvider.getGetStartedLink()); items.push(new ProvideFeedbackLink('bookmarks')); items.push(predefinedProvider.getReviewIssuesLink()); items.push(predefinedProvider.getReportIssueLink()); items.push({ icon: 'heart', title: 'Support', command: 'bookmarks.supportBookmarks' }); new HelpAndFeedbackView(context, "bookmarksHelpAndFeedback", items); }<file_sep>/src/commands/supportBookmarks.ts /*--------------------------------------------------------------------------------------------- * Copyright (c) <NAME>. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { commands, env, MessageItem, Uri, window } from "vscode"; import { Container } from "../../vscode-bookmarks-core/src/container"; export function registerSupportBookmarks() { Container.context.subscriptions.push(commands.registerCommand("bookmarks.supportBookmarks", async () => { const actions: MessageItem[] = [ { title: 'Become a Sponsor' }, { title: 'Donate via PayPal' } ]; const option = await window.showInformationMessage(`While Bookmarks is offered for free, if you find it useful, please consider supporting it. Thank you!`, ...actions); let uri: Uri; if (option === actions[ 0 ]) { uri = Uri.parse('https://www.patreon.com/alefragnani'); } if (option === actions[ 1 ]) { uri = Uri.parse('https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=EP57F3B6FXKTU&lc=US&item_name=Alessandro%20Fragnani&item_number=vscode%20extensions&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted'); } if (uri) { await env.openExternal(uri); } })); } <file_sep>/src/commands/openSettings.ts /*--------------------------------------------------------------------------------------------- * Copyright (c) <NAME>. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { commands } from "vscode"; import { Container } from "../../vscode-bookmarks-core/src/container"; export function registerOpenSettings() { Container.context.subscriptions.push(commands.registerCommand("bookmarks.openSettings", async () => { commands.executeCommand("workbench.action.openSettings", "bookmarks"); })); }
f7e8d1b9ccbf6a9137781f239827c2abfbccb5f5
[ "TypeScript" ]
5
TypeScript
Bogdan-Lyashenko/vscode-bookmarks
8871f9197588dd890de047ce6d222a186d87a50d
ab613b7345dfd2d2261740da6433152acb16bbfe
refs/heads/master
<repo_name>alexliangshi/pycrawler<file_sep>/main/crawler.py # -*- coding: utf-8 -*- # @Desc : # @license : Copyright(C), CBR # @Contact : <EMAIL> # @Site : import requests import bs4 url="http://www.comnews.cn/" response= requests.get(url) soup=bs4.BeautifulSoup(response.text) links=[a.attrs.get('href') for a in soup.select('div.li a[href^=/local]')]
9e5f9129eb204b661cc1f78625dbfa7076f105b3
[ "Python" ]
1
Python
alexliangshi/pycrawler
379b078a9e9288b91342192e125cd451e4d29f02
981cdbc79053985f250e47f575e60ba4efb2a42e
refs/heads/main
<repo_name>busrakalkan/HRMS_Project<file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/PositionDao.java package kodlamaio.hrms.dataAccess.abstracts; import org.springframework.data.jpa.repository.JpaRepository; import kodlamaio.hrms.entities.concretes.Position; public interface PositionDao extends JpaRepository<Position,Integer>{ Position getByPositionName(String positionName); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/core/validators/abstracts/EmailService.java package kodlamaio.hrms.core.validators.abstracts; import org.springframework.stereotype.Service; @Service public interface EmailService { public boolean emailCheck(String email); public boolean emailDomainCheck(String email, String website); public String emailSend(String email); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/JobAdvertisementDao.java package kodlamaio.hrms.dataAccess.abstracts; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import kodlamaio.hrms.entities.concretes.JobAdvertisement; import kodlamaio.hrms.entities.dtos.JobAdvertisementDto; public interface JobAdvertisementDao extends JpaRepository<JobAdvertisement, Integer> { @Query("Select new kodlamaio.hrms.entities.dtos.JobAdvertisementDto" + "(e.companyName, p.positionName, c.cityName, j.releaseDate,j.deadlineDate,j.totalOpenPositions)" + "From JobAdvertisement j Inner Join j.employer e Inner Join j.city c " + "Inner Join j.position p where j.isActive=true") List<JobAdvertisementDto> findByIsActiveTrue(); @Query("Select new kodlamaio.hrms.entities.dtos.JobAdvertisementDto" + "(e.companyName, p.positionName, c.cityName, j.releaseDate,j.deadlineDate,j.totalOpenPositions)" + "From JobAdvertisement j Inner Join j.employer e Inner Join j.city c " + "Inner Join j.position p where j.isActive=true Order By j.releaseDate ASC") List<JobAdvertisementDto> findByIsActiveTrueOrderByReleaseDateAsc(); @Query("Select new kodlamaio.hrms.entities.dtos.JobAdvertisementDto" + "(e.companyName, p.positionName, c.cityName, j.releaseDate,j.deadlineDate,j.totalOpenPositions)" + "From JobAdvertisement j Inner Join j.employer e Inner Join j.city c " + "Inner Join j.position p where j.isActive=true Order By j.deadlineDate ASC") List<JobAdvertisementDto> findByIsActiveTrueOrderByDeadlineDateAsc(); @Query("Select new kodlamaio.hrms.entities.dtos.JobAdvertisementDto" + "(e.companyName, p.positionName, c.cityName, j.releaseDate,j.deadlineDate,j.totalOpenPositions)" + "From JobAdvertisement j Inner Join j.employer e Inner Join j.city c " + "Inner Join j.position p where j.isActive=true And e.companyName=:companyName") List<JobAdvertisementDto> findByIsActiveTrueAndEmployer(String companyName); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/cvInfo/ExperienceDao.java package kodlamaio.hrms.dataAccess.abstracts.cvInfo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import kodlamaio.hrms.entities.concretes.cvInfo.ResumeExperience; import kodlamaio.hrms.entities.dtos.ExperienceDto; public interface ExperienceDao extends JpaRepository<ResumeExperience, Integer>{ @Query("Select new kodlamaio.hrms.entities.dtos.ExperienceDto(e.companyName, e.position, e.startedDate, e.endedDate) " + "From ResumeExperience e Inner Join e.resume r where r.id=:id Order By e.endedDate DESC") List<ExperienceDto> getExperiencesOrderByEndedDateDesc(int id); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/entities/dtos/SchoolDto.java package kodlamaio.hrms.entities.dtos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class SchoolDto { private String schoolName; private String degree; private String department; private String startedDate; private String endedDate; } <file_sep>/hrms/src/main/java/kodlamaio/hrms/core/imageUpload/CloudinaryUploadAdapter.java package kodlamaio.hrms.core.imageUpload; import java.io.File; import java.io.IOException; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.cloudinary.utils.ObjectUtils; import kodlamaio.hrms.externalService.CloudinaryManager; @Service public class CloudinaryUploadAdapter implements CloudinaryUploadService{ @Override public Map<String, Object> upload(MultipartFile multipartFile) { CloudinaryManager cloudinaryUpload = new CloudinaryManager(); Map<String, Object> uploadResult; try { uploadResult = cloudinaryUpload.upload(multipartFile); return uploadResult; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } <file_sep>/hrms/src/main/java/kodlamaio/hrms/entities/dtos/ExperienceDto.java package kodlamaio.hrms.entities.dtos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class ExperienceDto { private String companyName; private String position; private String startedDate; private String endedDate; } <file_sep>/hrms/src/main/java/kodlamaio/hrms/business/abstracts/UserService.java package kodlamaio.hrms.business.abstracts; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.entities.concretes.User; public interface UserService { DataResult<User> getByEmail(String email); Result login(String email, String password); Result add(User user); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/cvInfo/LanguageDao.java package kodlamaio.hrms.dataAccess.abstracts.cvInfo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import kodlamaio.hrms.entities.concretes.cvInfo.ResumeLanguage; import kodlamaio.hrms.entities.dtos.LanguageDto; public interface LanguageDao extends JpaRepository<ResumeLanguage, Integer>{ @Query("Select new kodlamaio.hrms.entities.dtos.LanguageDto(l.language, l.languageLevel)" + "From ResumeLanguage l Inner Join l.resume r where r.id=:id") List<LanguageDto> getLanguages(int id); }<file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/cvInfo/SchollDao.java package kodlamaio.hrms.dataAccess.abstracts.cvInfo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import kodlamaio.hrms.entities.concretes.cvInfo.ResumeSchool; import kodlamaio.hrms.entities.dtos.SchoolDto; public interface SchollDao extends JpaRepository<ResumeSchool, Integer>{ @Query("Select new kodlamaio.hrms.entities.dtos.SchoolDto(s.school,s.degree, s.department, s.startedDate, s.endedDate)" + "From ResumeSchool s Inner Join s.resume r where r.id=:id Order By s.endedDate DESC") List<SchoolDto> getSchoolsOrderByEndedDateDesc(int id); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/entities/dtos/ResumeDto.java package kodlamaio.hrms.entities.dtos; import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class ResumeDto { private String name; private String surname; private String githubLink; private String linkedinLink; private String coverLetter; private List<ExperienceDto> experiences; private List<SchoolDto> schools; private List<SkillDto> skills; private List<LanguageDto> languages; } <file_sep>/hrms/src/main/java/kodlamaio/hrms/business/concretes/PositionManager.java package kodlamaio.hrms.business.concretes; import java.util.List; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.PositionService; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.ErrorResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.dataAccess.abstracts.PositionDao; import kodlamaio.hrms.entities.concretes.Position; import kodlamaio.hrms.core.utilities.results.SuccessResult; import kodlamaio.hrms.core.utilities.results.SuccessDataResult; @Service public class PositionManager implements PositionService{ private PositionDao positionDao; public PositionManager(PositionDao positionDao) { super(); this.positionDao=positionDao; } @Override public DataResult<List<Position>> getAll() { return new SuccessDataResult<List<Position>> (this.positionDao.findAll(),"Pozisyonlar listelendi"); } @Override public Result add(Position position) { Position check = this.positionDao.getByPositionName(position.getPositionName()); if(check == null) { this.positionDao.save(position); return new SuccessResult("Pozisyon eklendi"); }else { return new ErrorResult("Pozisyon zaten var"); } } @Override public DataResult<Position> getByPositionName(String positionName) { return new SuccessDataResult<Position>(this.positionDao.getByPositionName(positionName)); } } <file_sep>/hrms/src/main/java/kodlamaio/hrms/core/imageUpload/CloudinaryUploadService.java package kodlamaio.hrms.core.imageUpload; import java.util.Map; import org.springframework.web.multipart.MultipartFile; public interface CloudinaryUploadService { Map<String, Object> upload(MultipartFile multipartFile); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/business/abstracts/ResumeService.java package kodlamaio.hrms.business.abstracts; import java.io.IOException; import java.util.List; import org.springframework.web.multipart.MultipartFile; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.entities.concretes.Resume; import kodlamaio.hrms.entities.dtos.ResumeDto; public interface ResumeService { DataResult<List<Resume>> getAll(); Result add(Resume resume); DataResult<Resume> getByJobSeekerId(int id); DataResult<ResumeDto> getResumeDtoByJobSeekerId(int id); DataResult<String> uploadPhoto(Integer id,MultipartFile filePath) throws IOException ; } <file_sep>/hrms/src/main/java/kodlamaio/hrms/business/concretes/PersonnelManager.java package kodlamaio.hrms.business.concretes; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.PersonnelService; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.ErrorResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.core.utilities.results.SuccessDataResult; import kodlamaio.hrms.core.utilities.results.SuccessResult; import kodlamaio.hrms.dataAccess.abstracts.PersonnelDao; import kodlamaio.hrms.entities.concretes.Employer; import kodlamaio.hrms.entities.concretes.Personnel; @Service public class PersonnelManager implements PersonnelService{ private PersonnelDao personnelDao; @Autowired public PersonnelManager(PersonnelDao personnelDao) { super(); this.personnelDao = personnelDao; } @Override public DataResult<List<Personnel>> getAll() { return new SuccessDataResult<List<Personnel>>(this.personnelDao.findAll(),"Personeller listelendi"); } @Override public Result add(Personnel personnel) { this.personnelDao.save(personnel); return new SuccessResult("Personel eklendi"); } @Override public Result getById(int id) { return new SuccessDataResult<Personnel>(this.personnelDao.findById(id).get(), "Belirtilen sistem çalışanı başarıyla bulundu."); } @Override public boolean registerPermit(Employer employer) { //Employer register permit return true; } @Override public Result login(String email, String password) { if(this.personnelDao.getByEmailAndPassword(email,password)!= null){ return new SuccessResult("Giriş Bararıyla GErçekleştirildi"); }else { return new ErrorResult("Kullanıcı Bulunamadı!"); } } } <file_sep>/README.md # HRMS_Project java camp human resources manager system <file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/EmployerDao.java package kodlamaio.hrms.dataAccess.abstracts; import org.springframework.data.jpa.repository.JpaRepository; import kodlamaio.hrms.entities.concretes.Employer; public interface EmployerDao extends JpaRepository<Employer, Integer>{ boolean existsEmployerByEmail(String email); // uniqe mail kontrolü için Employer getByEmailAndPassword(String email,String password); //login için } <file_sep>/hrms/src/main/java/kodlamaio/hrms/dataAccess/abstracts/PersonnelDao.java package kodlamaio.hrms.dataAccess.abstracts; import org.springframework.data.jpa.repository.JpaRepository; import kodlamaio.hrms.entities.concretes.Personnel; public interface PersonnelDao extends JpaRepository<Personnel, Integer>{ Personnel getByEmailAndPassword(String email,String password); } <file_sep>/hrms/src/main/java/kodlamaio/hrms/business/concretes/UserManager.java package kodlamaio.hrms.business.concretes; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.UserService; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.ErrorResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.core.utilities.results.SuccessDataResult; import kodlamaio.hrms.core.utilities.results.SuccessResult; import kodlamaio.hrms.dataAccess.abstracts.UserDao; import kodlamaio.hrms.entities.concretes.User; @Service public class UserManager implements UserService{ private UserDao userDao; @Autowired public UserManager(UserDao userDao) { super(); this.userDao = userDao; } @Override public DataResult<User> getByEmail(String email) { return new SuccessDataResult<User>(this.userDao.getByEmail(email),"maile göre sonuçlar"); } @Override public Result login(String email, String password) { if(this.userDao.getByEmailAndPassword(email,password)!= null){ return new SuccessResult("Giriş Bararıyla Grçekleştirildi"); }else { return new ErrorResult("Email veya şifre yanlış!"); } } @Override public Result add(User user) { //this.userDao.save(user); return new SuccessResult("Kullanıcı eklendi"); } } <file_sep>/hrms/src/main/java/kodlamaio/hrms/entities/concretes/cvInfo/ResumeExperience.java package kodlamaio.hrms.entities.concretes.cvInfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import kodlamaio.hrms.entities.concretes.Resume; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @Table(name = "resume_experience") @NoArgsConstructor @AllArgsConstructor public class ResumeExperience { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "experience_name") private String companyName; @Column(name = "experience_position") private String position; @Column(name = "started_date") private String startedDate; @Column(name = "ended_date") private String endedDate; @ManyToOne() @JoinColumn(name="resume_id") private Resume resume; } <file_sep>/hrms/src/main/java/kodlamaio/hrms/core/validators/concretes/FakeEmailManager.java package kodlamaio.hrms.core.validators.concretes; import java.util.regex.Pattern; import org.springframework.stereotype.Component; import kodlamaio.hrms.core.validators.abstracts.EmailService; @Component public class FakeEmailManager implements EmailService{ private static final String EMAIL_PATTERN = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.(com|org|net|edu|gov|mil|biz|info|mobi)(.[A-Z]{2})?$"; @Override public boolean emailCheck(String email) { Pattern pattern = Pattern.compile(EMAIL_PATTERN, Pattern.CASE_INSENSITIVE); return pattern.matcher(email).find(); } @Override public String emailSend(String email) { return email + " adresine doğrulama linki gönderildi."; } @Override public boolean emailDomainCheck(String email, String website) { // fake email domain regex check return true; } } <file_sep>/hrms/src/main/java/kodlamaio/hrms/api/controllers/JobSeekerController.java package kodlamaio.hrms.api.controllers; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import kodlamaio.hrms.business.abstracts.JobSeekerService; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.ErrorDataResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.entities.concretes.JobSeeker; @RestController @RequestMapping("/api/jobSeeker") public class JobSeekerController { private JobSeekerService jobSeekerService; @Autowired public JobSeekerController(JobSeekerService jobSeekerService) { super(); this.jobSeekerService = jobSeekerService; } @GetMapping("/getall") public DataResult<List<JobSeeker>> getAll(){ return this.jobSeekerService.getAll(); } @PostMapping("/login") public Result login(@RequestParam String email, String password) { return this.jobSeekerService.login(email,password); } @GetMapping("/getById") public DataResult<JobSeeker> getById(@RequestParam Integer id){ return this.jobSeekerService.getByJobSeekerId(id); } @PostMapping("/register") public ResponseEntity<?> register(@Valid @RequestBody JobSeeker jobSeeker,@RequestParam String repeatPassword) { return ResponseEntity.ok(this.jobSeekerService.register(jobSeeker, repeatPassword)); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorDataResult<Object> handleValidationException(MethodArgumentNotValidException exceptions){ Map<String,String> validationErrors = new HashMap<String, String>(); for(FieldError fieldError : exceptions.getBindingResult().getFieldErrors()) { validationErrors.put(fieldError.getField(), fieldError.getDefaultMessage()); } ErrorDataResult<Object> errors = new ErrorDataResult<Object>(validationErrors,"Doğrulama hataları"); return errors; } }
3a5693a88a6c8df2497b30591c0dd4d24f4385e5
[ "Markdown", "Java" ]
22
Java
busrakalkan/HRMS_Project
164cbafeaf63bb367a89712d46883b14576687c8
2c31ba29e49c35f80946648a17c4e6421b2c805b
refs/heads/master
<repo_name>johnetrent/eslint-config-jet<file_sep>/__tests__/eslint-rules-test.js import test from 'ava'; import fs from 'fs'; import path from 'path'; import {rules as eslintRules} from 'eslint/conf/eslint-all'; import rulesTest from './utils'; let definedRules = {}; fs .readdirSync(path.join(__dirname, '..', 'rules')) .filter(name => name !== 'plugins') .forEach(name => { // eslint-disable-next-line global-require const {rules} = require(`../rules/${name}`); definedRules = Object.assign(definedRules, rules); }); test(rulesTest(eslintRules, definedRules)); <file_sep>/rules/plugins/babel.js const {ERROR, OFF} = require('../../shared'); module.exports = { plugins: ['babel'], rules: { 'babel/array-bracket-spacing': [ERROR, 'never'], 'babel/arrow-parens': [ERROR, 'as-needed'], 'babel/flow-object-type': [ERROR, 'comma'], 'babel/func-params-comma-dangle': [ERROR, 'always-multiline'], 'babel/generator-star-spacing': [ERROR, {before: true, after: false}], 'babel/new-cap': OFF, 'babel/no-await-in-loop': ERROR, 'babel/no-invalid-this': ERROR, 'babel/object-curly-spacing': [ERROR, 'never'], 'babel/object-shorthand': OFF, 'babel/semi': ERROR, }, }; <file_sep>/README.md # eslint-config-jet Extend `eslint-config-jet` in your `.eslintrc` file. # Installation You can install [ESLint] with yarn: ```sh yarn add --dev eslint \ eslint-config-jet \ eslint-plugin-babel \ eslint-plugin-prettier \ babel-eslint \ prettier ``` # Editor Integration * [linter-eslint] for Atom's [Linter][atom-linter]. [eslint]: http://eslint.org [linter-eslint]: https://atom.io/packages/linter-eslint [atom-linter]: https://atom.io/packages/linter <file_sep>/rules/node.js const {ERROR, OFF} = require('../shared'); module.exports = { env: { node: true, }, rules: { 'callback-return': ERROR, 'global-require': ERROR, 'handle-callback-err': OFF, 'no-buffer-constructor': ERROR, 'no-mixed-requires': OFF, 'no-new-require': OFF, 'no-path-concat': OFF, 'no-process-exit': ERROR, 'no-restricted-modules': OFF, 'no-sync': OFF, }, }; <file_sep>/Makefile BABEL_NODE := ./node_modules/.bin/babel-node TEST_CMD := ./node_modules/.bin/ava --verbose TEST_PATTERN := **/__tests__/**/*test*.js test: ${BABEL_NODE} ${TEST_CMD} ${TEST_PATTERN} .PHONY: test <file_sep>/rules/best-practices.js const {ERROR, OFF} = require('../shared'); module.exports = { rules: { 'accessor-pairs': OFF, 'array-callback-return': ERROR, 'block-scoped-var': ERROR, 'class-methods-use-this': [ ERROR, { exceptMethods: [], }, ], complexity: [OFF, 11], 'consistent-return': OFF, curly: [ERROR, 'multi-line'], 'default-case': OFF, 'dot-location': OFF, 'dot-notation': [ERROR, {allowKeywords: true}], eqeqeq: ERROR, 'guard-for-in': OFF, 'max-lines': ERROR, 'max-statements-per-line': OFF, 'no-alert': ERROR, 'no-caller': ERROR, 'no-case-declarations': ERROR, 'no-div-regex': OFF, 'no-else-return': OFF, 'no-empty-function': ERROR, 'no-empty-pattern': ERROR, 'no-eq-null': OFF, 'no-eval': ERROR, 'no-extend-native': ERROR, 'no-extra-bind': ERROR, 'no-extra-label': ERROR, 'no-fallthrough': ERROR, 'no-floating-decimal': ERROR, 'no-global-assign': [ERROR, {exceptions: []}], 'no-implicit-coercion': ERROR, 'no-implicit-globals': ERROR, 'no-implied-eval': ERROR, 'no-invalid-this': OFF, 'no-iterator': ERROR, 'no-labels': ERROR, 'no-lone-blocks': ERROR, 'no-loop-func': ERROR, 'no-magic-numbers': [ OFF, { ignore: [], ignoreArrayIndexes: true, enforceConst: true, detectObjects: false, }, ], 'no-multi-spaces': ERROR, 'no-multi-str': ERROR, 'no-new-func': ERROR, 'no-new-wrappers': ERROR, 'no-new': ERROR, 'no-octal': ERROR, 'no-octal-escape': ERROR, 'no-param-reassign': OFF, 'no-process-env': OFF, 'no-proto': ERROR, 'no-redeclare': ERROR, 'no-restricted-properties': [ ERROR, { object: 'arguments', property: 'callee', message: 'arguments.callee is deprecated', }, ], 'no-return-assign': ERROR, 'no-return-await': ERROR, 'no-script-url': ERROR, 'no-self-assign': ERROR, 'no-self-compare': OFF, 'no-sequences': ERROR, 'no-throw-literal': OFF, 'no-unmodified-loop-condition': ERROR, 'no-unused-expressions': ERROR, 'no-unused-labels': ERROR, 'no-useless-call': ERROR, 'no-useless-concat': ERROR, 'no-useless-escape': ERROR, 'no-useless-return': ERROR, 'no-void': OFF, 'no-warning-comments': [ OFF, {terms: ['todo', 'fixme', 'xxx'], location: 'start'}, ], 'no-with': ERROR, 'nonblock-statement-body-position': ['error', 'beside', {overrides: {}}], 'padding-line-between-statements': OFF, 'prefer-promise-reject-errors': ['error', {allowEmptyReject: true}], radix: OFF, 'require-await': ERROR, 'vars-on-top': OFF, 'wrap-iife': OFF, yoda: [ERROR, 'never'], }, }; <file_sep>/rules/style.js const {ERROR, OFF} = require('../shared'); module.exports = { rules: { 'array-bracket-newline': [ERROR, 'consistent'], 'array-bracket-spacing': [ERROR, 'never'], 'array-element-newline': [ERROR, {multiline: true, minItems: 3}], 'block-spacing': ERROR, 'brace-style': [ERROR, '1tbs', {allowSingleLine: true}], camelcase: ERROR, 'capitalized-comments': [ OFF, 'never', { line: { ignorePattern: '.*', ignoreInlineComments: true, ignoreConsecutiveComments: true, }, block: { ignorePattern: '.*', ignoreInlineComments: true, ignoreConsecutiveComments: true, }, }, ], 'comma-spacing': ERROR, 'comma-style': [ERROR, 'last'], 'computed-property-spacing': OFF, 'consistent-this': [ERROR, 'self'], 'eol-last': ERROR, 'func-call-spacing': [ERROR, 'never'], 'func-name-matching': [ OFF, 'always', { includeCommonJSModuleExports: false, }, ], 'func-names': OFF, 'func-style': [OFF, 'declaration'], 'function-paren-newline': [ERROR, 'multiline'], 'id-blacklist': [OFF, 'data', 'err', 'e', 'cb', 'callback'], 'id-length': OFF, 'id-match': OFF, 'implicit-arrow-linebreak': [ERROR, 'beside'], indent: [ERROR, 2, {SwitchCase: 1}], 'jsx-quotes': [ERROR, 'prefer-double'], 'key-spacing': [ERROR, {beforeColon: false, afterColon: true}], 'keyword-spacing': ERROR, 'lines-around-comment': OFF, 'lines-between-class-members': [ ERROR, 'always', {exceptAfterSingleLine: false}, ], 'line-comment-position': [ OFF, { position: 'above', ignorePattern: '', applyDefaultPatterns: true, }, ], 'linebreak-style': [OFF, 'unix'], 'max-nested-callbacks': [OFF, 2], 'multiline-comment-style': [OFF, 'starred-block'], 'multiline-ternary': OFF, 'new-cap': [ERROR, {newIsCap: true, capIsNew: false}], 'new-parens': ERROR, 'newline-per-chained-call': OFF, 'no-array-constructor': ERROR, 'no-continue': OFF, 'no-inline-comments': OFF, 'no-lonely-if': OFF, 'no-mixed-operators': ERROR, 'no-mixed-spaces-and-tabs': [ERROR, false], 'no-multiple-empty-lines': [OFF, {max: 2}], 'no-nested-ternary': OFF, 'no-negated-condition': ERROR, 'no-new-object': ERROR, 'no-restricted-syntax': OFF, 'no-tabs': ERROR, 'no-ternary': OFF, 'no-trailing-spaces': ERROR, 'no-underscore-dangle': ERROR, 'no-unneeded-ternary': OFF, 'no-whitespace-before-property': ERROR, 'object-curly-newline': OFF, 'object-curly-spacing': OFF, 'one-var': OFF, 'one-var-declaration-per-line': [OFF, 'always'], 'operator-assignment': [OFF, 'always'], 'operator-linebreak': OFF, 'padded-blocks': OFF, 'quote-props': [ERROR, 'as-needed'], quotes: [ERROR, 'single', 'avoid-escape'], 'require-jsdoc': OFF, semi: ERROR, 'semi-spacing': [ERROR, {before: false, after: true}], 'semi-style': [ERROR, 'last'], 'sort-keys': [OFF, 'asc', {caseSensitive: false, natural: true}], 'sort-vars': OFF, 'sort-imports': OFF, 'space-before-blocks': [ERROR, 'always'], 'space-before-function-paren': [ERROR, 'never'], 'space-in-parens': [ERROR, 'never'], 'space-infix-ops': ERROR, 'space-unary-ops': [ERROR, {words: true, nonwords: false}], 'spaced-comment': [ERROR, 'always'], 'switch-colon-spacing': [ERROR, {after: true, before: false}], 'template-tag-spacing': [ERROR, 'never'], 'unicode-bom': [OFF, 'never'], 'wrap-regex': OFF, }, }; <file_sep>/rules/variables.js const {ERROR, OFF} = require('../shared'); module.exports = { rules: { 'init-declarations': OFF, 'no-catch-shadow': ERROR, 'no-delete-var': ERROR, 'no-label-var': ERROR, 'no-restricted-globals': ERROR, 'no-shadow': ERROR, 'no-shadow-restricted-names': ERROR, 'no-undef': ERROR, 'no-undef-init': ERROR, 'no-undefined': OFF, 'no-unused-vars': [ERROR, {vars: 'all', args: 'after-used'}], 'no-use-before-define': OFF, }, }; <file_sep>/rules/plugins/prettier.js const {ERROR} = require('../../shared'); module.exports = { plugins: ['prettier'], rules: { 'prettier/prettier': [ ERROR, { trailingComma: 'all', singleQuote: true, bracketSpacing: false, parser: 'babylon', }, ], }, }; <file_sep>/rules/strict.js const {ERROR} = require('../shared'); module.exports = { rules: { strict: [ERROR, 'global'], }, };
118b375ede5bd4c06478946ac82435ed9ac6439d
[ "JavaScript", "Makefile", "Markdown" ]
10
JavaScript
johnetrent/eslint-config-jet
4d1b690d73a2e6cb3f0135c0bea335d9f31b5db0
9d26f0917ffc6cc3f921b3b516b905df3bf069a9
refs/heads/master
<repo_name>donkelly55331/anagrams2<file_sep>/python/anagram2_spec.py # Test anagrams_for import unittest from anagram2 import anagrams_for tests = [{'word': 'saltier', 'list_in': ['cognac', 'saltier', 'realist', 'retails'], 'expect': ['saltier', 'realist', 'retails']}, {'word': 'threads', 'list_in': ["threads", "trashed", "hardest", "hatreds"], 'expect': ["threads", "trashed", "hardest", "hatreds"]}, {'word': 'apple', 'list_in': [], 'expect': []}] print("test running") i = int(input("Which case: ")) class MyTestCases(unittest.TestCase): def test_af(self): result = anagrams_for(tests[i]['word'], tests[i]['list_in']) self.assertEqual(result, tests[i]['expect'], "They're different") print(result) print(tests[i]['word']) print(tests[i]['list_in']) print(tests[i]['expect']) if __name__ == '__main__': unittest.main() <file_sep>/python/anagram2.py def anagrams_for(word, list_of_words): # anagrams have the same letters as the source, but the sequence is not meaningful # we will sort both the source and the word to be tested word = sorted(word) result = [] for item in list_of_words: if sorted(item) == word: result.append(item) return result
2f482e07588bb5dcf8dba9796bddacdf1f242c11
[ "Python" ]
2
Python
donkelly55331/anagrams2
4fea3ed00feef00d9ada625a4f5286c1f9767a03
2724fdf97e27595f82ebfcfc269540e844b0c5ea
refs/heads/main
<repo_name>handezVN/QuizOnline<file_sep>/src/java/TestServlet.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import DAO.QuestionDao; import DAO.SubmitDao; import DTO.QuestionDTO; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author handez */ @WebServlet(urlPatterns = {"/TestServlet"}) public class TestServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ QuestionDao dao = new QuestionDao(); String subjectid = request.getParameter("subjectid"); String submitid = request.getParameter("submitid"); ArrayList<QuestionDTO> list = dao.getQuestionDTOsbySubjectID(subjectid); String seleted[] = request.getParameterValues("selected"); SubmitDao submitdao = new SubmitDao(); float point_total = 0; for(int i=0;i<list.size();i++){ point_total+=list.get(i).getPoint(); } float point_total_current= 0; HashMap<String, String> map = new HashMap<String, String>(); String correct = list.get(1).getCorrect(); for(int i=0;i<seleted.length;i++){ String s[] = seleted[i].split("/"); String questionid = s[0]; String ans = s[1]; if(map.get(questionid)!=null){ String tmp = map.get(questionid)+"/"+ans; map.replace(questionid, tmp); }else map.put(questionid, ans); } for (String questionid : map.keySet()) { String answer[] = dao.getAnswerCorrectbyQuestionId(questionid).split("/"); float point_qs = dao.getPointbyQuestionId(questionid); String selected = ""; for(int i=0;i<answer.length;i++){ boolean check = false; String ab[] = map.get(questionid).split("/"); for(int y=0;y<ab.length;y++){ if(Integer.parseInt(ab[y])==i) check = true; } selected+=check+"/"; } // get answer of student String selected_tmp[] = selected.split("/"); float qs_length = selected_tmp.length; float qs_current = qs_length; int count_true =0; for (int y=0;y<answer.length;y++){ if(answer[y].equals("true")) count_true++; } System.out.println(questionid); System.out.println(count_true); if(count_true>1){ for(int z=0;z<selected_tmp.length;z++){ if(!selected_tmp[z].equals(answer[z])) { qs_current--; } } point_total_current += point_qs*(qs_current/qs_length) ; submitdao.UpdateDetailSubmit( questionid, selected, (point_qs*(qs_current/qs_length))); }else{ if(selected.equals(dao.getAnswerCorrectbyQuestionId(questionid))) { point_total_current+=point_qs; submitdao.UpdateDetailSubmit( questionid, selected, point_qs); } else{ point_total_current+=0; submitdao.UpdateDetailSubmit( questionid, selected, 0); } } } int result = -1; int page = Integer.parseInt(request.getParameter("page_current")); System.out.println(page); String page_selected = null; page_selected = request.getParameter("page"); if(page_selected!=null){ if(page_selected.equals("Next Page")){ page++; } if(page_selected.equals("Privious Page")){ page--; } } request.setAttribute("submit",request.getParameter("submit")); request.setAttribute("page", page); request.setAttribute("submitid", submitid); request.getRequestDispatcher("QuizPage.jsp").forward(request, response); } catch (SQLException ex) { Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/src/java/Servlet/BeginQuizServlet.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Servlet; import DAO.QuestionDao; import DAO.SubjectDao; import DAO.SubmitDao; import DTO.QuestionDTO; import DTO.SubjectDTO; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; 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 javax.servlet.http.HttpSession; /** * * @author handez */ @WebServlet(name = "BeginQuizServlet", urlPatterns = {"/BeginQuizServlet"}) public class BeginQuizServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ SubmitDao dao = new SubmitDao(); SubjectDao subjectdao = new SubjectDao(); QuestionDao questiondao = new QuestionDao(); HttpSession session = request.getSession(); String subjectid = request.getParameter("subjectid"); String password = ""; password = request.getParameter("password"); if(password==null){ password=""; } System.out.println(password); SubjectDTO subjectDTO = subjectdao.getSubjectDTO(subjectid); String sb_password = subjectDTO.getPassword(); System.out.println(subjectDTO); System.out.println("ab"+sb_password); if(password==sb_password||password.equals(<PASSWORD>)){ String email =(String) session.getAttribute("email"); String submitid = "sm-"+ (dao.getSubmit().size()+1); // insert SubmitTbl long millis_begin=System.currentTimeMillis(); long millis_end=millis_begin+subjectDTO.getTime()*60*1000; DateFormat simple = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date result = new Date(millis_begin); Date result1 = new Date(millis_end); String date_begin = simple.format(result); String date_end = simple.format(result1); dao.insertSubmitbegin(submitid, email, subjectid,date_begin,date_end); // insert DetailSubmitTbl ArrayList<QuestionDTO> list = questiondao.getQuestionDTOsbySubjectID(subjectid); for(int i=0;i<list.size();i++){ if(list.get(i).isStatus()==false){ String count[] = list.get(i).getAnswer().split("/"); String select = ""; for(int y=0;y<count.length;y++){ select+="false/"; } dao.InsertDetailSubmit(submitid, list.get(i).getId(), select, 0,list.get(i).getCorrect(),list.get(i).getAnswer(),list.get(i).getPoint(),list.get(i).getQuestion()); }} session.setAttribute("submitid", submitid); session.setAttribute("subjectid", subjectDTO.getId()); session.setAttribute("time", subjectDTO.getTime()*60); session.setAttribute("user", "student"); response.sendRedirect("QuizPage.jsp"); }else{ request.setAttribute("Errpass", "<PASSWORD>!"); request.setAttribute("subjectid", request.getParameter("subjectid")); request.getRequestDispatcher("CheckQuizPage.jsp").forward(request, response); } } catch (SQLException ex) { Logger.getLogger(BeginQuizServlet.class.getName()).log(Level.SEVERE, null, ex); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/src/java/DTO/SubmitDTO.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DTO; /** * * @author handez */ public class SubmitDTO { private String submitid; private String subjectid; private String time_begin; private String time_end; private String email; private float point; private float point_total; private float point_current; public SubmitDTO() { } public SubmitDTO(String submitid, String subjectid, String time_begin, String time_end, String email, float point, float point_total, float point_current) { this.submitid = submitid; this.subjectid = subjectid; this.time_begin = time_begin; this.time_end = time_end; this.email = email; this.point = point; this.point_total = point_total; this.point_current = point_current; } public String getSubmitid() { return submitid; } public void setSubmitid(String submitid) { this.submitid = submitid; } public String getSubjectid() { return subjectid; } public void setSubjectid(String subjectid) { this.subjectid = subjectid; } public String getTime_begin() { return time_begin; } public void setTime_begin(String time_begin) { this.time_begin = time_begin; } public String getTime_end() { return time_end; } public void setTime_end(String time_end) { this.time_end = time_end; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public float getPoint() { return point; } public void setPoint(float point) { this.point = point; } public float getPoint_total() { return point_total; } public void setPoint_total(float point_total) { this.point_total = point_total; } public float getPoint_current() { return point_current; } public void setPoint_current(float point_current) { this.point_current = point_current; } } <file_sep>/src/java/DTO/SubjectDTO.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DTO; /** * * @author handez */ public class SubjectDTO { private String id ; private String name; private String email; private String password; private String date; private int time; private int attempts; private boolean status; private boolean isdelete; public SubjectDTO(String id, String name, String email, String password, String date, int time, int attempts, boolean status) { this.id = id; this.name = name; this.email = email; this.password = <PASSWORD>; this.date = date; this.time = time; this.attempts = attempts; this.status = status; } public SubjectDTO(String id, String name, String email, String password, String date, int time, int attempts) { this.id = id; this.name = name; this.email = email; this.password = <PASSWORD>; this.date = date; this.time = time; this.attempts = attempts; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public int getAttempts() { return attempts; } public void setAttempts(int attempts) { this.attempts = attempts; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public SubjectDTO(String id, String name, String email, String password, String date, int time) { this.id = id; this.name = name; this.email = email; this.password = <PASSWORD>; this.date = date; this.time = time; } public SubjectDTO(String id, String name, String email, String password, String date, int time, int attempts, boolean status, boolean isdelete) { this.id = id; this.name = name; this.email = email; this.password = <PASSWORD>; this.date = date; this.time = time; this.attempts = attempts; this.status = status; this.isdelete = isdelete; } public boolean isIsdelete() { return isdelete; } public void setIsdelete(boolean isdelete) { this.isdelete = isdelete; } public SubjectDTO() { } } <file_sep>/src/java/DAO/SubjectDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import DTO.SubjectDTO; import Utils.MyConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; /** * * @author handez */ public class SubjectDao { public int addNewSubject(String id,String email , String password , String name , String date , int time,int attempt,boolean status) throws SQLException{ Connection cn = MyConnection.MakeConnection(); int result = -1; if(cn!=null){ String sql = "insert SubjectTbl values(?,?,?,?,?,?,?,?)"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, id); pst.setString(3, email); pst.setString(5, password); pst.setString(2, name); pst.setString(4, date); pst.setInt(6, time); pst.setInt(7, attempt); pst.setBoolean(8, status); result=pst.executeUpdate(); cn.close(); } return result; } public ArrayList<SubjectDTO> getAllSubject() throws SQLException{ Connection cn = MyConnection.MakeConnection(); ArrayList<SubjectDTO> list = new ArrayList<>(); if(cn!=null){ String sql = "Select * from SubjectTbl order by date_exp"; PreparedStatement pst = cn.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while(rs.next()){ list.add( new SubjectDTO(rs.getString(1),rs.getString(2), rs.getString(3), rs.getString(5),rs.getString(4), rs.getInt(6),rs.getInt(7),rs.getBoolean(8),rs.getBoolean(9))); } cn.close(); } Collections.reverse(list); return list; } public SubjectDTO getSubjectDTO(String id ) throws SQLException{ Connection cn = MyConnection.MakeConnection(); SubjectDTO subjectDTO = null; if(cn!=null){ String sql = "Select * from SubjectTbl where subjectID=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, id); ResultSet rs = pst.executeQuery(); if(rs.next()){ subjectDTO= new SubjectDTO(rs.getString(1),rs.getString(2), rs.getString(3), rs.getString(5),rs.getString(4), rs.getInt(6),rs.getInt(7),rs.getBoolean(8)); } cn.close(); } return subjectDTO; } public int updateSubject(String name, String date, String password, int time , int attempt , String id,boolean status) throws SQLException{ Connection cn = MyConnection.MakeConnection(); int result = -1; if(cn!=null){ String sql = "update SubjectTbl set subject_Name=?,date_exp=?,password=?,subject_Time=?,attempt=? ,status=? where subjectID=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, name); pst.setString(2, date); pst.setString(3, password); pst.setInt(4, time); pst.setInt(5, attempt); pst.setString(7, id); pst.setBoolean(6, status); result= pst.executeUpdate(); cn.close(); } return result; } public int RemoveSubject(String subjectid) throws SQLException{ int result =-1; Connection cn = MyConnection.MakeConnection(); if(cn!=null){ String sql = "update SubjectTbl set isDelete=1 where subjectID=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, subjectid); result= pst.executeUpdate(); cn.close(); } return result; } } <file_sep>/src/java/Servlet/CreateSubjectServlet.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Servlet; import DAO.SubjectDao; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; 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 javax.servlet.http.HttpSession; /** * * @author handez */ @WebServlet(name = "CreateSubjectServlet", urlPatterns = {"/CreateSubjectServlet"}) public class CreateSubjectServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String name = request.getParameter("name"); String password = request.getParameter("password"); HttpSession session = request.getSession(); String email = (String) session.getAttribute("email"); String date_tmp = request.getParameter("date"); String time_tmp = request.getParameter("time"); int attempt = Integer.parseInt(request.getParameter("attempt")); int time = Integer.parseInt(time_tmp); time = Math.abs(time); SubjectDao dao = new SubjectDao(); String id = "Sb"+(dao.getAllSubject().size()+1) ; Boolean status = Boolean.parseBoolean(request.getParameter("status")); String date_tmp1[] = date_tmp.split("T"); String date = date_tmp1[0]; date = date +" "+date_tmp1[1]+":00"; System.out.println(date); int result = -1; result = dao.addNewSubject(id, email, password, name, date, time,attempt,status); if(result!=-1){ request.getRequestDispatcher("AdminPage.jsp").forward(request, response); } } catch (SQLException ex) { Logger.getLogger(CreateSubjectServlet.class.getName()).log(Level.SEVERE, null, ex); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/src/java/DAO/QuestionDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import DTO.QuestionDTO; import Utils.MyConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author handez */ public class QuestionDao { public int AddQuestion(String id , String question , String anwser , String correct , String subjectid,int point) throws SQLException{ int result =-1; Connection cn = MyConnection.MakeConnection(); if(cn!=null){ String sql = " insert QuestionTbl values(?,?,?,?,SYSDATETIME(),?,1,?)"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, id); pst.setString(2, question); pst.setString(3, anwser); pst.setString(4, correct); pst.setString(5, subjectid); pst.setInt(6, point); result=pst.executeUpdate(); cn.close(); } return result; } public ArrayList<QuestionDTO> getQuestionDTOsbySubjectID(String subjectid) throws SQLException{ Connection cn = MyConnection.MakeConnection(); ArrayList<QuestionDTO> list = new ArrayList<>(); if(cn!=null){ String sql = "Select * from QuestionTbl where subjectID=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, subjectid); ResultSet rs = pst.executeQuery(); while(rs.next()){ list.add(new QuestionDTO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(6), rs.getInt(8),rs.getBoolean(7) )); } cn.close(); } return list; } public ArrayList<QuestionDTO> getQuestionDTOsbySearch(String search,String subjectid) throws SQLException{ Connection cn = MyConnection.MakeConnection(); ArrayList<QuestionDTO> list = new ArrayList<>(); if(cn!=null){ String sql = "Select * from QuestionTbl where question_content like ? and subjectID=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, "%"+search+"%"); pst.setString(2, subjectid); ResultSet rs = pst.executeQuery(); while(rs.next()){ list.add(new QuestionDTO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(6), rs.getInt(8),rs.getBoolean(7) )); } cn.close(); } return list; } public String getAnswerCorrectbyQuestionId(String questionID) throws SQLException{ Connection cn = MyConnection.MakeConnection(); String result = ""; if(cn!=null){ String sql= "select answer_correct from QuestionTbl where questionid=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, questionID); ResultSet rs = pst.executeQuery(); if(rs.next()){ result = rs.getString(1); } cn.close(); } return result; } public float getPointbyQuestionId(String questionID) throws SQLException{ Connection cn = MyConnection.MakeConnection(); float result = 0; if(cn!=null){ String sql= "select point from QuestionTbl where questionid=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, questionID); ResultSet rs = pst.executeQuery(); if(rs.next()){ result = rs.getFloat(1); } cn.close(); } return result; } public QuestionDTO getQuestionDTObyQuestionID(String questionid) throws SQLException{ Connection cn = MyConnection.MakeConnection(); QuestionDTO questionDTO = null; if(cn!=null){ String sql = "Select * from QuestionTbl where questionid=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, questionid); ResultSet rs = pst.executeQuery(); while(rs.next()){ questionDTO =new QuestionDTO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(6), rs.getInt(8),rs.getBoolean(7) ); } cn.close(); } return questionDTO; } public int updateQuestion(String questionid,String question , String corrent , String answer , int point) throws SQLException{ Connection cn = MyConnection.MakeConnection(); int result =-1; if(cn!=null){ String sql = "update QuestionTbl set question_content=?,answer_content=?,answer_correct=?,createDate=SYSDATETIME(),point=? where questionid=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, question); pst.setString(2, answer); pst.setString(3, corrent); pst.setInt(4, point); pst.setString(5, questionid); result= pst.executeUpdate(); cn.close(); } return result; } public ArrayList<QuestionDTO> getQuestionDTOsbySubjectIDandIndex(String subjectid,int index1 , int index2) throws SQLException{ Connection cn = MyConnection.MakeConnection(); ArrayList<QuestionDTO> list = new ArrayList<>(); if(cn!=null){ String sql = "With ab AS (\n" + "SELECT * , ROW_NUMBER() Over (ORDER BY questionid) AS RowNum FROM QuestionTbl where subjectID=? and status=0\n" + ")\n" + "select * from ab\n" + "WHERE RowNum >=?\n" + "AND RowNum <= ?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, subjectid); pst.setInt(2, index1); pst.setInt(3, index2); ResultSet rs = pst.executeQuery(); while(rs.next()){ list.add(new QuestionDTO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(6), rs.getInt(8),rs.getBoolean(7) )); } cn.close(); } return list; } public int RemoveQuestion(String questionid) throws SQLException{ int result =-1; Connection cn = MyConnection.MakeConnection(); if(cn!=null){ String sql = "update QuestionTbl set status=1 where questionid=?"; PreparedStatement pst = cn.prepareStatement(sql); pst.setString(1, questionid); result= pst.executeUpdate(); cn.close(); } return result; } } <file_sep>/src/java/DTO/DetailSubmitDTO.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DTO; /** * * @author handez */ public class DetailSubmitDTO { private String submitid; private String answer_selected; private String answer_correct; private String question_content; private String answer_content; private float point_get; private float point; public DetailSubmitDTO(String submitid, String answer_selected, String answer_correct, String question_content, String answer_content, float point_get, float point) { this.submitid = submitid; this.answer_selected = answer_selected; this.answer_correct = answer_correct; this.question_content = question_content; this.answer_content = answer_content; this.point_get = point_get; this.point = point; } public String getSubmitid() { return submitid; } public void setSubmitid(String submitid) { this.submitid = submitid; } public String getAnswer_selected() { return answer_selected; } public void setAnswer_selected(String answer_selected) { this.answer_selected = answer_selected; } public String getAnswer_correct() { return answer_correct; } public void setAnswer_correct(String answer_correct) { this.answer_correct = answer_correct; } public String getQuestion_content() { return question_content; } public void setQuestion_content(String question_content) { this.question_content = question_content; } public String getAnswer_content() { return answer_content; } public void setAnswer_content(String answer_content) { this.answer_content = answer_content; } public float getPoint_get() { return point_get; } public void setPoint_get(float point_get) { this.point_get = point_get; } public float getPoint() { return point; } public void setPoint(float point) { this.point = point; } }
53ae7b864c17ad324fad47b3673a53b1fdacb3bb
[ "Java" ]
8
Java
handezVN/QuizOnline
21220b26a7c14f37cfb300dacacff84152d62e6a
37e6306cfe840a22e9567cb52599f649769eb3af
refs/heads/master
<repo_name>nishesh13/upwork<file_sep>/src/com/nishesh/Project1.java package com.nishesh; public class Project1 { public static void main (String[] args) { for(int i=1;i<=100;i++) { StringBuilder str= new StringBuilder(); if(i%3==0) { str.append("Fizz"); } if(i%5==0) { str.append("Buzz"); } if(str.length()==0) { str.append(i); } System.out.println(str.toString()); } } }
f4a1da5e89129a67c9959db4e2fce9c05f7d241a
[ "Java" ]
1
Java
nishesh13/upwork
73e1cba06f8069fd0300af0ae3fdc0cf95602865
9948af46c627c368d7cdf3a01780af380831603e
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400;500;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/style.css"> <title><NAME>chele Portfolio</title> </head> <body> <header> <div id="title"> <h1><NAME></h1> <h2>Creative Developer</h2> </div> <nav> <a href="#about-text"> <h2>About</h2> </a> <a href="#project1"> <h2>Project 1</h2> </a> <a href="#project2"> <h2>Project 2</h2> </a> <a href="#project3"> <h2>Project 3</h2> </a> <a href="resume.pdf"> <h2>Resume</h2> </a> <a href="#footer"> <h2>Contact</h2> </a> </nav> </header> <main> <div class="main-about"> <div id="about-image"> <img src="media/avatar.jpg" alt="avatar" style="width: 300px;"> </div> <div id="about-text"> <h2>About</h2> <p>Hi! My name is Sevan and I am a 2nd-year GDD student. My goals are to either work as a game dev at an already established studio or to start my own indie studio. I began learning game development about 7 years ago by making mods for various games. I eventually got into making more stand-alone titles and which is where I am today. I hope by taking IGME-235 I can sharpen my HTML and CSS skills and learn JavaScript. I also hope we can do some back end web development. I plan on graduating in 2023 with a major in GDD and possibly a minor in business. </p> </div> </div> <div id="projects-header"> <h1>Projects</h1> </div> <div class="main-flex"> <div class="main-items"> <div class="items-image"> <img src="media/project1.png" alt="stock" style="width: 225px;"> </div> <div class="items-text" id="project1"> <h2>The Floor Is Lava!</h2> <p>The Floor Is Lava was a project made for a web tech class using a tech stack known as PixiJS. It's a small little platformer where you have to climb from platform to platform in order to escape the lava. I was the sole developer of this project and learned how to program collision resolution and strengthened my javascript skills.</p> </div> <div class="items-image"> <img src="media/project2.png" alt="stock" style="width: 225px;"> </div> <div class="items-text" id="project2"> <h2>Crunch Time</h2> <p>Crunch Time is a 2D top-down shooter that allows you to slow down time when you stop moving. The technologies used were Microsoft XNA and my role in the project was programming the physics for the game. This was one of the first projects I've done that could be considered a full standalone game.</p> </div> <div class="items-image"> <img src="media/project3.png" alt="stock" style="width: 225px;"> </div> <div class="items-text" id="project3"> <h2>Asteroids</h2> <p>Asteroids is a remake of an old arcade game where you have to break apart asteroids by shooting them. I built this game in the Unity game engine and was the sole developer of the game. I was able to learn more about Unity's engine through this project.</p> </div> </div> </div> </main> <footer id="footer"> <h1>Contact Info</h1> <h2>Cell: 773-372-5635</h2> <h2>Email: <EMAIL></h2> </footer> </body> </html><file_sep> class Vector2D { constructor(x, y) { this.x = x; this.y = y; } // If only JS had operator overloading. add(otherVector) { this.x = this.x + otherVector.x; this.y = this.y + otherVector.y; } sub(otherVector) { this.x = this.x - otherVector.x; this.y = this.y - otherVector.y; } mul(scalar) { this.x = this.x * scalar; this.y = this.y * scalar; } div(scalar) { this.x = this.x / scalar; this.y = this.y / scalar; } addNew(otherVector) { return new Vector2D(this.x + otherVector.x, this.y + otherVector.y); } subNew(otherVector) { return new Vector2D(this.x - otherVector.x, this.y - otherVector.y); } mulNew(scalar) { return new Vector2D(this.x * scalar, this.y * scalar); } divNew(scalar) { return new Vector2D(this.x / scalar, this.y / scalar); } } class Camera { constructor(width, height) { this.position = new Vector2D(0, 0); this.width = width / 2; this.height = height / 2; } transformSprite(sprite, position) { let offset = new Vector2D(position.x - this.position.x, this.position.y - position.y); let rd = 100; sprite.x = offset.x + this.width; sprite.y = offset.y + this.height; sprite.visible = true; /*if (sprite.x < 0 - rd || sprite.x > (this.width * 2) + rd || sprite.y < 0 - rd || sprite.y > (this.height * 2) + rd) { sprite.visible = false; }*/ } } class Entity { constructor(spriteImage) { this.sprite = new PIXI.Sprite.from(spriteImage); this.sprite.anchor.set(0.5); this.sprite.visible = true; this.position = new Vector2D(0, 0); this.velocity = new Vector2D(0, 0); this.acceleration = new Vector2D(0, 0); this.mass = 1.0; } updateTransform(deltaTime) { // Transform Object let newPos = new Vector2D(this.position.x, this.position.y); this.acceleration.mul(deltaTime) this.velocity.x += this.acceleration.x * deltaTime; this.velocity.y += this.acceleration.y * deltaTime; newPos.x += this.velocity.x; newPos.y += this.velocity.y; // Zero out acceleration this.acceleration.x = 0; this.acceleration.y = 0; this.position = newPos; } applyForce(forceVector) { this.acceleration.add(forceVector.divNew(this.mass)); } collide(target) { let aBounds = this.sprite.getBounds(); let bBounds = target.sprite.getBounds(); let a = { top: aBounds.y, left: aBounds.x, bottom: aBounds.y + aBounds.height, right: aBounds.x + aBounds.width, x: aBounds.x, y: aBounds.y, hWidth: aBounds.width / 2, hHeight: aBounds.height / 2 } let b = { top: bBounds.y, left: bBounds.x, bottom: bBounds.y + bBounds.height, right: bBounds.x + bBounds.width, x: bBounds.x, y: bBounds.y, hWidth: bBounds.width / 2, hHeight: bBounds.height / 2 } if (a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom) { return false; } let aC = new Vector2D(a.x + a.hWidth, a.y + a.hHeight); let bC = new Vector2D(b.x + b.hWidth, b.y + b.hHeight); let dx = bC.x - aC.x; let dy = bC.y - aC.y; let cW = a.hWidth + b.hWidth; let cH = a.hHeight + b.hHeight; let oX = cW - Math.abs(dx); let oY = cH - Math.abs(dy); if (oX > oY) { if (dy > 0) { //console.log("B"); this.position.y = target.position.y + cH + 0.01; } else { //console.log("T"); this.position.y = target.position.y - cH - 0.01; } this.velocity.y = target.velocity.y; if (target.velocity.x != 0) { this.velocity.x = target.velocity.x * 1.3; } this.grounded = true; } else { if (dx > 0) { //console.log("R"); this.position.x = target.position.x - cW - 0.01; } else { //console.log("L"); this.position.x = target.position.x + cW + 0.01; } this.velocity.x = target.velocity.x; } return true; } } class Player extends Entity { constructor(spriteImage) { super(spriteImage); this.sprite.height = 32; this.sprite.width = 32; } } class Platform extends Entity { constructor(spriteImage) { super(spriteImage); this.sprite.height = 24; this.sprite.width = 100; this.sprite.tint = 0xff0000; } } class PlatformTall extends Entity { constructor(spriteImage) { super(spriteImage); this.sprite.height = 180; this.sprite.width = 12; this.sprite.tint = 0xff0000; } } class Lava extends Entity { constructor(spriteImage) { super(spriteImage); } }<file_sep> // Grabs results from site. function httpGetResult(url, method) { let xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", url); xmlHttp.send(); xmlHttp.onload = method } let breeds = new Array(); let options = document.getElementById('breed'); function GetBreeds(e) { breeds = JSON.parse(e.target.responseText).message; let options = document.getElementById('breed'); for (let key in breeds) { console.log(breeds[key]); let option = document.createElement('option'); option.value = key; option.innerHTML = key; options.appendChild(option); } } function GetRandomImage(e) { let result = JSON.parse(e.target.responseText); randomImage.src = result.message; let breed = result.message; breed = breed.replace("https://images.dog.ceo/breeds/", ""); breed = breed.substr(0, breed.search("/")); breed = breed.replace("/", ""); breed = breed.replace("-", " "); dogBreed.innerHTML = breed; } function GetSpesificBreed(e) { let result = JSON.parse(e.target.responseText); randomImage.src = result.message; let breed = result.message; dogBreed.innerHTML = options.value; } let randomImage = document.getElementById('randomizer_image'); let randomButton = document.getElementById('randomizer_button'); let searchButton = document.getElementById('search_button'); let dogBreed = document.getElementById('dogbreed'); httpGetResult('https://dog.ceo/api/breeds/list/all', GetBreeds) randomButton.addEventListener("click", function name() { httpGetResult('https://dog.ceo/api/breeds/image/random', GetRandomImage); }) searchButton.addEventListener("click", function name() { httpGetResult('https://dog.ceo/api/breed/' + options.value + '/images/random/1', GetSpesificBreed); }) httpGetResult('https://dog.ceo/api/breeds/image/random', GetRandomImage);<file_sep>let app; window.onload = function () { app = new PIXI.Application( { width: 500, height: 500, backgroundColor: 0x000000 } ); document.body.appendChild(app.view); setUp(); } //#region Variables /* Containers */ let menuScene; let mainScene; let endScene; let hud; let camera; /* Main Variables */ let paused = true; let player; let platforms; let lava; let score; let deltaTime; let gravity; //#endregion //#region Setup & Helpers function SpawnPlatform(xPos, yPos, width, height) { let entity = new Platform("images/blank.png"); entity.position.x = xPos; entity.position.y = yPos; entity.sprite.width = width; entity.sprite.height = height; platforms.push(entity); mainScene.addChild(entity.sprite); return entity; } function SpawnPlatformTall(xPos, yPos) { let entity = new PlatformTall("images/blank.png"); entity.position.x = xPos; entity.position.y = yPos; platforms.push(entity); mainScene.addChild(entity.sprite); return entity; } function RemovePlatform(entity) { entity.shouldDelete = true; mainScene.removeChild(entity.sprite); } function setUp() { // Containers hud = new PIXI.Container(); hud.visible = true; menuScene = new PIXI.Container(); menuScene.visible = true; mainScene = new PIXI.Container(); mainScene.visible = false; endScene = new PIXI.Container(); endScene.visible = false; app.stage.addChild(hud); app.stage.addChild(menuScene); app.stage.addChild(mainScene); app.stage.addChild(endScene); camera = new Camera(app.view.width, app.view.height); player = new Player("images/blank.png"); player.mass = 1; player.position.x = 0 mainScene.addChild(player.sprite); /* lava = new Lava("images/blank.png"); lava.sprite.width = 500; lava.position.y = -250; lava.rect = lava.sprite.getBounds(); mainScene.addChild(lava.sprite); */ startGame(); app.ticker.add(mainLoop); } //#endregion //#region Main Game let lr = { 68: false, 65: false, } let movingPlat; let movingPlat2; function testLevel() { SpawnPlatform(0, -150, 1000, 20); SpawnPlatform(0, 300, 1000, 20); SpawnPlatform(-500, 60, 20, 500); SpawnPlatform(500, 60, 20, 500); SpawnPlatform(100, -80, 100, 20); SpawnPlatform(240, 50, 100, 20); SpawnPlatform(100, 100, 100, 20); SpawnPlatform(180, -20, 20, 20); movingPlat = SpawnPlatform(-200, 50, 100, 20); movingPlat2 = SpawnPlatform(-200, 230, 100, 20); SpawnPlatform(-400, 50, 100, 20); SpawnPlatform(-490, 140, 60, 20); } function startGame() { menuScene.visible = false; mainScene.visible = true; platforms = []; gravity = new Vector2D(0, 300); paused = false; player.grounded = false; testLevel(); } Math.clamp = function (a, b, c) { return Math.max(b, Math.min(c, a)); } let ticker = 0; function mainLoop() { if (paused) return; deltaTime = 1 / app.ticker.FPS; if (deltaTime > 1 / 12) deltaTime = 1 / 12; player.acceleration.sub(gravity); player.updateTransform(deltaTime); camera.transformSprite(player.sprite, player.position); //camera.transformSprite(lava.sprite, lava.position); ticker = ticker + (deltaTime); if (Math.round(ticker * 0.5) % 2 == 0) { movingPlat.velocity.x = -1; movingPlat2.velocity.x = 1; } else { movingPlat.velocity.x = 1; movingPlat2.velocity.x = -1; } player.grounded = false; for (let index = 0; index < platforms.length; index++) { let platform = platforms[index]; platform.updateTransform(deltaTime); camera.transformSprite(platform.sprite, platform.position); if (player.collide(platform, deltaTime)) { } } if (lr[65]) { player.velocity.x = -3; } else if (lr[68]) { player.velocity.x = 3; } else { player.velocity.x = player.velocity.x * 0.7; } //lava.position.y += 30 * deltaTime; camera.position = player.position; } let controls = { 68: function () { lr[68] = true; }, 65: function () { lr[65] = true; }, 87: function () { if (player.grounded) { player.velocity.y += 4; } } } let controlsUp = { 68: function () { lr[68] = false; }, 65: function () { lr[65] = false; } } function keyUp(e) { //console.log(e.keyCode) if (controlsUp[e.keyCode]) { controlsUp[e.keyCode](); } } function keyDown(e) { if (controls[e.keyCode]) { controls[e.keyCode](); } } window.addEventListener("keydown", keyDown); window.addEventListener("keyup", keyUp); //#endregion<file_sep># IGME-235 <file_sep>class Entity { constructor(spriteImage, width, height) { this.sprite = new PIXI.Sprite.from(spriteImage); this.sprite.width = width || this.sprite.width; this.sprite.height = height || this.sprite.height; this.sprite.anchor.set(0.5); this.sprite.visible = true; this.position = new Vector2D(0, 0); this.velocity = new Vector2D(0, 0); this.acceleration = new Vector2D(0, 0); } getRectangle() { let bounds = this.sprite.getBounds(); let rect = { top: bounds.y, left: bounds.x, bottom: bounds.y + bounds.height, right: bounds.x + bounds.width, x: bounds.x, y: bounds.y, hWidth: bounds.width / 2, hHeight: bounds.height / 2 } return rect; } // Simple AABB checker. intersects(target) { let a = this.getRectangle(); let b = target.getRectangle(); return (a.right > b.left && a.left < b.right && a.bottom > b.top && a.top < b.bottom); } collide(target) { let a = this.getRectangle(); let b = target.getRectangle(); if (a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom) { return false; } let aC = new Vector2D(a.x + a.hWidth, a.y + a.hHeight); let bC = new Vector2D(b.x + b.hWidth, b.y + b.hHeight); let dx = bC.x - aC.x; let dy = bC.y - aC.y; let cW = a.hWidth + b.hWidth; let cH = a.hHeight + b.hHeight; let oX = cW - Math.abs(dx); let oY = cH - Math.abs(dy); // We first need to check which axis we want to resolve. if (oX > oY) { // Resolves on the Y if (dy > 0) { this.position.y = target.position.y + cH + 0.01; // Sets grounded. Basically just used for the player to see if they can jump. this.grounded = true; this.velocity.y = target.velocity.y; } else { this.position.y = target.position.y - cH - 0.01; if (this.velocity.y > 0) { this.velocity.y = target.velocity.y; } } // This is also just for the player & moving platforms. if (target.velocity.x != 0) { this.velocity.x = target.velocity.x * 1.3; } } else { // Resolves on the X if (dx > 0) { this.position.x = target.position.x - cW - 0.01; } else { this.position.x = target.position.x + cW + 0.01; } this.velocity.x = target.velocity.x; } return true; } updateTransform(deltaTime) { // Transform Object let newPos = new Vector2D(this.position.x, this.position.y); this.acceleration = Vector2D.mul(this.acceleration, deltaTime); this.velocity.x += this.acceleration.x * deltaTime; this.velocity.y += this.acceleration.y * deltaTime; newPos.x += this.velocity.x; newPos.y += this.velocity.y; // Zero out acceleration this.acceleration.x = 0; this.acceleration.y = 0; this.position = newPos; } // While not used by all ents this is good for adding more custom behavior. update(deltaTime) { this.updateTransform(deltaTime); } } class Player extends Entity { constructor() { super("images/character.png", 32, 32); } } class Platform extends Entity { constructor(spriteImage, scale) { super(spriteImage, 40 * scale, 10 * scale); } } class MovingPlatform extends Entity { constructor(spriteImage, scale) { super(spriteImage, 40 * scale, 10 * scale); this.rng = Util.getRandom(0, 1); } update(deltaTime) { if (Math.ceil(timer.curTime()) % 2 == 0) { if (this.rng > 0.5) { this.velocity.x = -1; } else { this.velocity.x = 1; } } else { if (this.rng > 0.5) { this.velocity.x = 1; } else { this.velocity.x = -1; } } super.update(deltaTime); } } class Barrier extends Entity { constructor(spriteImage, width, height) { super(spriteImage, width, height); this.sprite.tint = 0x000000; } } class Lava extends Entity { constructor(spriteImage) { super(spriteImage, 3000, 500); this.sprite.tint = 0xFF7F00; } }<file_sep>class Util { constructor() { } static clamp(a, b, c) { return Math.max(b, Math.min(c, a)); } static lerp(start, end, amt) { return start * (1 - amt) + amt * end; } static getRandom(min, max) { return Math.random() * (max - min) + min; } } class Clock { constructor() { this.time = 0; } tick(deltaTime) { this.time += deltaTime; } curTime() { return this.time; } } class Vector2D { constructor(x, y) { this.x = x; this.y = y; } // If only JS had operator overloading. // So instead I just made static methods. static add(vector, vector2) { let newVector = new Vector2D(0, 0); newVector.x = vector.x + vector2.x; newVector.y = vector.y + vector2.y; return newVector; } static sub(vector, vector2) { let newVector = new Vector2D(0, 0); newVector.x = vector.x - vector2.x; newVector.y = vector.y - vector2.y; return newVector; } static mul(vector, scalar) { let newVector = new Vector2D(vector.x, vector.y); newVector.x = newVector.x * scalar; newVector.y = newVector.y * scalar; return newVector; } static div(vector, scalar) { let newVector = new Vector2D(vector.x, vector.y); newVector.x = newVector.x / scalar; newVector.y = newVector.y / scalar; return newVector; } } class Camera { constructor(width, height) { this.position = new Vector2D(0, 0); this.width = width / 2; this.height = height / 2; } transformSprite(sprite, position) { // This offset lets us get the correct position for the sprite on screen. let offset = new Vector2D(position.x - this.position.x, this.position.y - position.y); sprite.x = offset.x + this.width; sprite.y = offset.y + this.height; } }<file_sep>PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST let app; window.onload = function () { app = new PIXI.Application( { width: 800, height: 600, backgroundColor: 0x000000, } ); document.body.appendChild(app.view); setUp(); } window.WebFontConfig = { google: { families: ['Snippet', 'Roboto:700', 'Roboto:400', "MedievalSharp:700", "MedievalSharp:400"] }, }; //#region Variables // Containers let menuScene; let mainScene; let endScene; let hud; // General let camera; let paused = true; let timer = new Clock(); let deltaTime = 0; let gravity = new Vector2D(0, 420); let background; let timerText; let scoreText; let jump; let music; // Player & Platforms let player; let playerControls = { 68: false, 65: false, } let jumpVelocity = 5; let platforms; let lava; let procStage = 0; let procInc = 0; //#endregion //#region VGUI Functions function StartText() { let startStyle = { fontFamily: 'MedievalSharp', fill: '#ffffff', fontSize: 28, align: 'center', } let box = new PIXI.Sprite.from("images/border.png"); box.width = 700; box.height = 180; box.anchor.set(0.5); box.x = app.view.width / 2; box.y = (app.view.height / 2) - 95; menuScene.addChild(box); let controlsText = new PIXI.Text('Welcome Traveller\n You must scale the castle and escape the lava \nControls: WASD to move. Space to jump.', startStyle); controlsText.position.x = app.view.width / 2; controlsText.position.y = (app.view.height / 2) - 150; controlsText.anchor.x = 0.5; menuScene.addChild(controlsText); let button = new PIXI.Sprite.from("images/border_start.png"); button.width = 256; button.height = 64; button.buttonMode = true; button.anchor.set(0.5); button.x = app.view.width / 2; button.y = (app.view.height / 2) + 70; button.interactive = true; button.on('mousedown', startGame); menuScene.addChild(button); let startText = new PIXI.Text('Start', startStyle); startText.position.x = app.view.width / 2; startText.position.y = (app.view.height / 2) + 50; startText.anchor.x = 0.5; menuScene.addChild(startText); } function EndText() { let endStyle = { fontFamily: 'MedievalSharp', fill: '#ffffff', fontSize: 28, align: 'center', } let box = new PIXI.Sprite.from("images/border.png"); box.width = 700; box.height = 180; box.anchor.set(0.5); box.x = app.view.width / 2; box.y = (app.view.height / 2) - 95; endScene.addChild(box); let deathText = new PIXI.Text('You have perished\n Would you like to try again?', endStyle); deathText.position.x = app.view.width / 2; deathText.position.y = (app.view.height / 2) - 150; deathText.anchor.x = 0.5; endScene.addChild(deathText); let button = new PIXI.Sprite.from("images/border_start.png"); button.width = 256; button.height = 64; button.buttonMode = true; button.anchor.set(0.5); button.x = app.view.width / 2; button.y = (app.view.height / 2) + 70; button.interactive = true; button.on('mousedown', startGame); endScene.addChild(button); scoreText = new PIXI.Text('00:00', endStyle); scoreText.position.x = app.view.width / 2; scoreText.position.y = (app.view.height / 2) - 80; scoreText.anchor.x = 0.5; endScene.addChild(scoreText); let retryText = new PIXI.Text('Retry', endStyle); retryText.position.x = app.view.width / 2; retryText.position.y = (app.view.height / 2) + 50; retryText.anchor.x = 0.5; endScene.addChild(retryText); } function HUD() { let box = new PIXI.Sprite.from("images/border.png"); box.width = 128; box.height = 32; box.anchor.set(0.5); box.x = app.view.width / 2; box.y = 25; hud.addChild(box); let timerStyle = { fontFamily: 'MedievalSharp', fill: '#ffffff', fontSize: 26, align: 'center', } timerText = new PIXI.Text('00:00', timerStyle); timerText.position.x = app.view.width / 2; timerText.position.y = 10; timerText.anchor.x = 0.5; hud.addChild(timerText); } //#endregion //#region Proc Gen & Milestones function CheckMilestone() { let distance = Math.abs(player.position.y - lava.position.y); let diff = Util.clamp((timer.curTime() / 60), 0, 1); if (distance > 500) { lava.velocity.y = 5 * diff; } else if (distance > 1000) { lava.velocity.y = 8 * diff; } else { lava.velocity.y = 2 * diff; } } function RunProcGen() { if (player.position.y > procStage - 300) { procStage = procStage + 100; let origin = new Vector2D(0, procStage); let rng = Util.getRandom(0, 100); let xOffset = 0; if (procInc % 2 == 0) { xOffset = 100; } else { xOffset = -100; } xOffset += Util.getRandom(-5, 5); // 60% chance of moving platform if (rng > 60) { SpawnMovingPlatform(origin.x + xOffset, origin.y - Util.getRandom(0, 10)); } else { SpawnPlatform(origin.x + xOffset, origin.y); } // Proc inc is just so we alternate which side we place a platform on. procInc += 1; // Place some platforms on the sides to give it more randomness. SpawnPlatform(origin.x + 400 - Util.getRandom(0, 200), origin.y); SpawnPlatform(origin.x - 400 + Util.getRandom(0, 200), origin.y); } } //#endregion //#region Helpers function SpawnBarrier(xPos, yPos, width, height) { let entity = new Barrier("images/blank.png", width, height); entity.position.x = xPos; entity.position.y = yPos; platforms.push(entity); mainScene.addChild(entity.sprite); return entity; } function SpawnPlatform(xPos, yPos) { let entity = new Platform("images/static_platform.png", 2.5); entity.position.x = xPos; entity.position.y = yPos; platforms.push(entity); mainScene.addChild(entity.sprite); return entity; } function SpawnMovingPlatform(xPos, yPos) { let entity = new MovingPlatform("images/moving_platform.png", 2.5); entity.position.x = xPos; entity.position.y = yPos; platforms.push(entity); mainScene.addChild(entity.sprite); return entity; } function RemovePlatform(entity) { entity.shouldDelete = true; mainScene.removeChild(entity.sprite); } function UpdatePlayerMovement() { if (playerControls[65]) { player.velocity.x = -3; } else if (playerControls[68]) { player.velocity.x = 3; } else { player.velocity.x = player.velocity.x * 0.7; } } function FormatTimeText(string) { let rawTime = parseInt(string, 10); let minutes = Math.floor(rawTime / 60); let seconds = rawTime - (minutes * 60); if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } return minutes + ":" + seconds; } function setUp() { // Containers hud = new PIXI.Container(); hud.visible = false; menuScene = new PIXI.Container(); menuScene.visible = true; mainScene = new PIXI.Container(); mainScene.visible = false; endScene = new PIXI.Container(); endScene.visible = false; // Adds the background to the stage. Is not added to any scene because its used in all of them. background = new PIXI.Sprite.from("images/bg.png"); background.anchor.set(0.5); background.visible = true; let bgRatio = background.width / background.height; background.width = app.view.width; background.height = app.view.height * bgRatio; background.x = app.view.width / 2; background.y = app.view.height / 2; // Adds Containers app.stage.addChild(background); app.stage.addChild(menuScene); app.stage.addChild(mainScene); app.stage.addChild(endScene); app.stage.addChild(hud); // Sets up the camera, player, and lava. camera = new Camera(app.view.width, app.view.height); player = new Player(); mainScene.addChild(player.sprite); lava = new Lava("images/blank.png"); hud.addChild(lava.sprite); // Sounds jump = new Howl({ src: ['sounds/jump.wav'] }); jump.volume(0.4); music = new Howl({ src: ['sounds/music.wav'], }); // Adds all the VGUI. StartText(); EndText(); HUD(); // Starts ticker app.ticker.add(mainLoop); } //#endregion //#region Main Game function startingPlatforms() { SpawnPlatform(0, -100); } function startGame() { menuScene.visible = false; endScene.visible = false; mainScene.visible = true; hud.visible = true; if (platforms) { for (let index = 0; index < platforms.length; index++) { RemovePlatform(platforms[index]) } } platforms = []; startingPlatforms(); player.position = new Vector2D(0, 0); player.velocity = new Vector2D(0, 0); camera.position = player.position; lava.position.y = -500; lava.velocity.y = 0.3; procStage = player.position.y - 120; paused = false; music.volume(0.15); music.loop(true); music.play(); } function endGame() { menuScene.visible = false; mainScene.visible = false; endScene.visible = true; hud.visible = false; paused = true; timer.time = 0; scoreText.text = "Survived Time: " + timerText.text; music.stop(); } function mainLoop() { if (paused) return; // Gets delta time and increases timer. deltaTime = 1 / app.ticker.FPS; if (deltaTime > 1 / 12) deltaTime = 1 / 12; timer.tick(deltaTime); // Updates cameras position and the player. camera.position.x = Util.lerp(camera.position.x, player.position.x, deltaTime * 2); camera.position.y = Util.lerp(camera.position.y, player.position.y, deltaTime * 2); player.acceleration = Vector2D.sub(player.acceleration, gravity); player.update(deltaTime); camera.transformSprite(player.sprite, player.position); // Checks for collisions with platforms and updates platforms. player.grounded = false; for (let index = 0; index < platforms.length; index++) { let platform = platforms[index]; platform.update(deltaTime); camera.transformSprite(platform.sprite, platform.position); player.collide(platform, deltaTime); if (platform.position.y < lava.position.y) { RemovePlatform(platform); } } // Move Lava & Update Player Movement lava.update(deltaTime); camera.transformSprite(lava.sprite, lava.position); UpdatePlayerMovement(); // Filters out platforms long gone. platforms = platforms.filter(p => !p.shouldDelete); // Update Timer Text timerText.text = FormatTimeText(timer.curTime()); // Runs proc gen & Lava Milestones RunProcGen(); CheckMilestone(); // Checks if the lava has got the player. if (lava.intersects(player)) { endGame(); } } //#endregion //#region Controls let keysDown = { 68: function () { playerControls[68] = true; }, 65: function () { playerControls[65] = true; }, 87: function () { if (player.grounded) { jump.play(); player.velocity.y += jumpVelocity; } }, 32: function () { if (player.grounded) { jump.play(); player.velocity.y += jumpVelocity; } } } let keysUp = { 68: function () { playerControls[68] = false; }, 65: function () { playerControls[65] = false; } } function keyUp(e) { if (keysUp[e.keyCode]) { keysUp[e.keyCode](); } } function keyDown(e) { if (keysDown[e.keyCode]) { keysDown[e.keyCode](); } } window.addEventListener("keydown", keyDown); window.addEventListener("keyup", keyUp); //#endregion
166d5e1d9a5a1d04f95a2c3ea934aa40d14104f4
[ "JavaScript", "HTML", "Markdown" ]
8
HTML
stb6897/IGME-235
66d13f4c888d2d362e763946b2d504e4ba6081df
97c6bf5c8391aad34a3fd52924a55c4737a75b34
refs/heads/master
<repo_name>EugenSeko/Unity-sandbox<file_sep>/Assets/Scripts/PanicLab/Multiplayer/MouseClick_M.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseClick_M : MonoBehaviour { //Звук [SerializeField] private AudioSource[] soundSources; [SerializeField] private AudioClip[] audioClips; //Звук private GameHelper _gameHelper; private SceneController_M _sceneController; private void Start() { _gameHelper = GameObject.FindObjectOfType<GameHelper>(); _sceneController = GameObject.FindObjectOfType<SceneController_M>(); } public void OnMouseDown() { if (gameObject.tag!="button" && gameObject.tag != "levels" && gameObject.tag != "dices" && Static_M.isCardButtonsActive ) { //нажатие на карту во время игры. Static_M.myId = gameObject.GetComponent<Card_M>().id; if (Static_M.myId == Static_M.id) { _gameHelper.SetGoogAnswer(); } else { _sceneController.StartCoroutine("QuickPulse"); } } else if(gameObject.tag != "levels") { if (gameObject.name == "start_button" && Static_M.isStartButtonActive) { //нажатие на кнопку старт. _gameHelper.StartCoroutine("LabelsReadyFill",false);// заполняются поля готовности игроков. // Static_M.throwDice = true; Static_M.isStartButtonActive = false; } if (gameObject.name == "levelsEnterButton") { soundSources[0].PlayOneShot(audioClips[0]);//звуковой эффект. GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(19.23f, 0, -100); CheckPositionSet(); } if (gameObject.name == "exitMenu") { GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(0, 0, -100); SceneController_M.ScoringExit(); } } else if(gameObject.tag == "levels") { Static_M.wait = 1f; Static_M.gamesCount = 0; Static_M.score = 0; Static_M.myScore=0; GameObject check = GameObject.FindGameObjectWithTag("check"); switch (gameObject.name) { case "level1": Static_M.level = 1; check.transform.position = new Vector3(12.98f, -3.86f, -2f); break; case "level2": Static_M.level = 2; Static_M.wait -=0.15f; check.transform.position = new Vector3(20.47f, -3.87f, -2f); break; case "level3": Static_M.level = 3; Static_M.wait -= 0.3f; check.transform.position = new Vector3(16.57f, -2.58f, -2f); break; case "level4": Static_M.level = 4; Static_M.wait -=0.45f; check.transform.position = new Vector3(13.83f, -0.95f, -2f); break; case "level5": Static_M.level = 5; Static_M.wait -= 0.6f; check.transform.position = new Vector3(19.18f, -0.18f, -2f); break; case "level6": Static_M.level = 6; Static_M.wait -= 0.75f; check.transform.position = new Vector3(16.07f, 1.15f, -2f); break; case "level7": Static_M.level = 7; Static_M.wait -= 0.9f; check.transform.position = new Vector3(13.36f, 3.15f, -2f); break; } StartCoroutine("Pulse"); } } private IEnumerator Pulse() { float wait = 0.03f; Vector3 scale = gameObject.transform.localScale; for (int i = 0; i < 4; i++) { gameObject.transform.localScale = new Vector3(scale.x * 0.5f, scale.y * 0.5f, scale.z * 0.5f); yield return new WaitForSeconds(wait); gameObject.transform.localScale = scale; yield return new WaitForSeconds(wait); } } private void CheckPositionSet() { GameObject check = GameObject.FindGameObjectWithTag("check"); switch (Static_M.level) { case 1: check.transform.position = new Vector3(12.98f, -3.86f, -2f); break; case 2: check.transform.position = new Vector3(20.47f, -3.87f, -2f); break; case 3: check.transform.position = new Vector3(16.57f, -2.58f, -2f); break; case 4: check.transform.position = new Vector3(13.83f, -0.95f, -2f); break; case 5: check.transform.position = new Vector3(19.18f, -0.18f, -2f); break; case 6: check.transform.position = new Vector3(16.4f, 1.4f, -2f); break; case 7: check.transform.position = new Vector3(13.36f, 3.15f, -2f); break; } } } <file_sep>/Assets/Scripts/PanicLab/MouseClick.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MouseClick : MonoBehaviour { private SceneController _sceneController; //Звук [SerializeField] private AudioSource[] soundSources; [SerializeField] private AudioClip[] audioClips; //Звук private void Start() { _sceneController = GameObject.FindObjectOfType<SceneController>(); } public void OnMouseDown() { if (gameObject.tag!="button" && gameObject.tag != "levels" && gameObject.tag != "dices" && Static.isCardButtonsActive ) { Static.myId = gameObject.GetComponent<Card>().id; if (Static.myId == Static.id) { Static.goodAnswer = 1; } else { Static.goodAnswer = -1; } Static.isCardButtonsActive = false; } else if(gameObject.tag != "levels") { if (gameObject.name == "start_button" && Static.isStartButtonActive) { Static.throwDice = true; Static.isStartButtonActive = false; Static.isCardButtonsActive = true;//делаем карточки активными. } if (gameObject.name == "MainMenu") { soundSources[0].PlayOneShot(audioClips[0]);//звуковой эффект. GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(-2.38f, -10.97f, -100); GameObject.FindObjectOfType<Canvas>().enabled = true; } if (gameObject.name == "exitMenu") { GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(-2.38f, -10.97f, -100); GameObject.FindObjectOfType<Canvas>().enabled = true; SceneController.ScoringExit(); _sceneController.ScoringTextClean(); } } else if(gameObject.tag == "levels") { Static.wait = 1f; Static.gamesCount = 0; Static.score = 0; Static.myScore=0; GameObject check = GameObject.FindGameObjectWithTag("check"); switch (gameObject.name) { case "level1": Static.level = 1; check.transform.position = new Vector3(12.98f, -3.86f, -2f); break; case "level2": Static.level = 2; Static.wait -=0.15f; check.transform.position = new Vector3(20.47f, -3.87f, -2f); break; case "level3": Static.level = 3; Static.wait -= 0.3f; check.transform.position = new Vector3(16.57f, -2.58f, -2f); break; case "level4": Static.level = 4; Static.wait -=0.45f; check.transform.position = new Vector3(13.83f, -0.95f, -2f); break; case "level5": Static.level = 5; Static.wait -= 0.6f; check.transform.position = new Vector3(19.18f, -0.18f, -2f); break; case "level6": Static.level = 6; Static.wait -= 0.75f; check.transform.position = new Vector3(16.07f, 1.15f, -2f); break; case "level7": Static.level = 7; Static.wait -= 0.9f; check.transform.position = new Vector3(13.36f, 3.15f, -2f); break; } StartCoroutine("Pulse"); } } public void LoadMultiplayer() { SceneManager.LoadScene("NetworkLobby"); } public void GoToGame() { gameObject.GetComponent<Canvas>().enabled = false; GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(0, 0, -100); } public void GoToSettings() { gameObject.GetComponent<Canvas>().enabled = false; soundSources[0].PlayOneShot(audioClips[0]);//звуковой эффект. GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(19.23f, 0, -100); CheckPositionSet(); } public void ExitGame() { Application.Quit(); } private IEnumerator Pulse() { float wait = 0.03f; Vector3 scale = gameObject.transform.localScale; for (int i = 0; i < 4; i++) { gameObject.transform.localScale = new Vector3(scale.x * 0.5f, scale.y * 0.5f, scale.z * 0.5f); yield return new WaitForSeconds(wait); gameObject.transform.localScale = scale; yield return new WaitForSeconds(wait); } } private void CheckPositionSet() { GameObject check = GameObject.FindGameObjectWithTag("check"); switch (Static.level) { case 1: check.transform.position = new Vector3(12.98f, -3.86f, -2f); break; case 2: check.transform.position = new Vector3(20.47f, -3.87f, -2f); break; case 3: check.transform.position = new Vector3(16.57f, -2.58f, -2f); break; case 4: check.transform.position = new Vector3(13.83f, -0.95f, -2f); break; case 5: check.transform.position = new Vector3(19.18f, -0.18f, -2f); break; case 6: check.transform.position = new Vector3(16.4f, 1.4f, -2f); break; case 7: check.transform.position = new Vector3(13.36f, 3.15f, -2f); break; } } } <file_sep>/Assets/Scripts/PanicLab/Multiplayer/UIController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIController : MonoBehaviour { public void CanvasOnOff(bool b) { if (b) { gameObject.GetComponent<Canvas>().enabled=true; } else gameObject.GetComponent<Canvas>().enabled = false; } } <file_sep>/README.md # Unity-sandbox sandbox <file_sep>/Assets/Scripts/PanicLab/Multiplayer/NetworkManager_Custom.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; using UnityEngine.Networking.Match; using UnityEngine.Networking.Types; using System; public class NetworkManager_Custom : NetworkManager { } <file_sep>/Assets/Scripts/PanicLab/Multiplayer/GameHelper.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using UnityEngine.SceneManagement; public class GameHelper : MonoBehaviour { public InputField input; public Text textBlock; private PlayerHelper _currentPlayer; private SceneController_M _sceneController; private UIController _uiController; [SerializeField] private TextMesh[] PlayersLabels; [SerializeField] private TextMesh[] PlayersScoreLabels; [SerializeField] private TextMesh[] PlayersReadyLabels; [SerializeField] private Text[] PlayersRate; [SerializeField] private Text[] PlayersRateScore; [SerializeField] private TextMesh countdown; public PlayerHelper currentPlayer { get { return _currentPlayer; } set { _currentPlayer = value; } } void Start () { _sceneController = GameObject.FindObjectOfType<SceneController_M>(); _uiController = GameObject.FindObjectOfType<UIController>(); StartCoroutine(LabelsFill()); StartCoroutine(InitID()); _uiController.CanvasOnOff(false); } private void Update() { if (Static_M.server && Static_M.go) { if (Static_M.numOfPlayers == Static_M.numOfPlayersReady)//автоматически бросит кости когда все готовы. { _currentPlayer.RpcCountDown(); Static_M.go = false; } } } //chat----------------------- public void Send() { _currentPlayer.Send(input.text); } //chat---------------------- public void PlayerLabelFill(int id, string name) { PlayersLabels[id].text = name; PlayersScoreLabels[id].text = ""; } public void PlayerReadyFill(int id, bool empty) { if (empty) { PlayersReadyLabels[id].text = ""; Static_M.numOfPlayersReady = 0; } else PlayersReadyLabels[id].text = "Ready"; if (Static_M.server) { Static_M.go = true; } } public void PlayerScoreFill(int id) { Static_M.isCardButtonsActive = false;//деактивирует нажатие на карточки. Static_M.PlayersScore[id]++; if (Static_M.playerId==id) { _sceneController.StartCoroutine("Rotation"); } else { _sceneController.StartCoroutine("Pulse"); } PlayersScoreLabels[id].text = Static_M.PlayersScore[id].ToString();//заполняет поле очков в игре. } public void CountDown() { StartCoroutine(Countdown()); } public void ThrowDices() { _sceneController.ThrowingDice(); } public void SetDicesOnClient(int[]diceIndexes) { if (!Static_M.server) { for (int i = 0; i < Static_M.DiceIndexes.Length; i++) { Static_M.DiceIndexes[i] = diceIndexes[i]; Debug.Log("Static_M.DiceIndexes"+i+" = " + Static_M.DiceIndexes[i]); } ThrowDices(); } } public void SetSearchDataOnClient(int id) { if (!Static_M.server) { Static_M.id = id; } } public void SendSearchDataOnClient() { _currentPlayer.RpcSetSearchDataOnClients(Static_M.id); } public void SetGoogAnswer() { _currentPlayer.CmdSetGoodAnswer(); } public void SendLoadScore() { _currentPlayer.CmdLoadScore(); } public void LoadScores()//метод переключает камеру, включает канвас и выводит игровые достижения и обнуляет эти достижения. { _uiController.CanvasOnOff(true); Static_M.gamesCount = 0; GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(0, -11.06f, -100); Scoring(); for (int i = 0; i < Static_M.PlayersScore.Length; i++) { Static_M.PlayersScore[i] = 0; } } private void Scoring()//метод выводит имена и очки игроков на экран в порядке набранных очков. { int ind = 0; for (int i = Static_M.numOfGames; i >-1; i--) { for (int j=0; j< Static_M.PlayersScore.Length; j++) { if (Static_M.PlayersScore[j] == i) { PlayersRate[ind].text = PlayersLabels[j].text; PlayersRateScore[ind].text = PlayersScoreLabels[j].text;//заполняет поле очков в чате. ind++; break; } } } } private void PlayerRateClean() { foreach (Text pr in PlayersRate) { pr.text = ""; } foreach (Text pr in PlayersRateScore) { pr.text = ""; } }//очищает данные игроков отображаемые в чате. private void PlayerScoreClean() { foreach (TextMesh ps in PlayersScoreLabels) { ps.text = ""; } }//очищает данные игроков отображаемые в игре. public void SetDeactiveCanvas()// метод на кнопку старт. { PlayerRateClean(); PlayerScoreClean(); _currentPlayer.CmdPlayersLabelsFill(); _uiController.CanvasOnOff(false); GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(0, -0.55f, -100); } IEnumerator LabelsFill() { bool b = true; while (b) { if (_currentPlayer != null) { _currentPlayer.CmdPlayersLabelsFill(); b = false; } else { yield return new WaitForSeconds(0.5f); } } } IEnumerator LabelsReadyFill(bool empty) { bool b = true; while (b) { if (_currentPlayer != null) { _currentPlayer.CmdPlayerReadyFill(empty); b = false; } else { yield return new WaitForSeconds(0.5f); } } } IEnumerator Countdown( ) { for (int i = 3; i > 0; i--) { countdown.text = i.ToString(); yield return new WaitForSeconds(0.5f); countdown.text = ""; } _currentPlayer.CmdPlayerReadyFill(true); if (Static_M.server) { ThrowDices(); _currentPlayer.RpcSetDicesOnClients(Static_M.DiceIndexes);//рассылаем клиентам значения костей. } Static_M.isCardButtonsActive = true;//делаем карточки активными. } IEnumerator InitID() { bool b = true; while (b) { if (_currentPlayer != null) { Static_M.playerId = _currentPlayer.playerId; b = false; } else { yield return new WaitForSeconds(0.5f); } } } } <file_sep>/Assets/Scripts/PanicLab/Multiplayer/SceneController_M.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SceneController_M : MonoBehaviour { //Звук [SerializeField] private AudioSource[] soundSources; [SerializeField] private AudioClip[] audioClips; //Звук [SerializeField] private Sprite[] images; [SerializeField] private Sprite[] dice_images0; [SerializeField] private Sprite[] dice_images1; [SerializeField] private Sprite[] dice_images2; [SerializeField] private Sprite[] dice_images3; [SerializeField] private TextMesh gamesCountLabel; [SerializeField] private TextMesh message; [SerializeField] private TextMesh myScore; [SerializeField] private TextMesh score; [SerializeField] private TextMesh scoringMessage; [SerializeField] private TextMesh levelLabel; [SerializeField] private Card_M originalCard; private int[] _cardValuesSequence; private int[] _sequence; private GameHelper _gameHelper; private void Start () { _gameHelper = GameObject.FindObjectOfType<GameHelper>();//ссылка на на объект GameHelper и его скрипт. _sequence = Static_M.sequences(Static_M.numOfSequence); _cardValuesSequence = new int[26]; for (int i = 0; i < 26; i++) { _cardValuesSequence[i] = Static_M.cardValuesSequence[_sequence[i]]; } for (int i = 0; i < 26 ; i++) { int index = _sequence[i]; Card_M card; // ссылка на контейнер для карты. card = Instantiate(originalCard) as Card_M; // создание карты согласно базовой. card.setCard(index, images[index], Static_M.getCoordinates(i));//расположение объекта согласно координатам. card.gameObject.name = _cardValuesSequence[i].ToString();//изменение имени объекта согласно кодировки. card.gameObject.tag = index.ToString();// добавление тэга для поиска. } } private void Update() { //score.text = Static_M.score.ToString(); //myScore.text = Static_M.myScore.ToString(); //gamesCountLabel.text = "Round " + Static_M.gamesCount;//выводим на экран число игр. //levelLabel.text = "Level "+Static_M.level.ToString(); } public void ThrowingDice() { if (!Static_M.freezeThrowingDice) { Static_M.gamesCount++; if (Static_M.gamesCount % 3 == 0)//периодически меняем раскладку карт. { if (Static_M.numOfSequence == 3) { Static_M.numOfSequence = 0; } else { Static_M.numOfSequence++; } DestroyCards(); Start(); } int diceValue = 1000; int labValue = 10; int direction = 1; int index; int[] indexes = ShuffleArray(new int[4] { 0, 1, 2, 3 }); if (GameObject.FindGameObjectsWithTag("dices").Length > 0)//удаление костей, если они не успели удалиться автоматически. { for (int i = 0; i < GameObject.FindGameObjectsWithTag("dices").Length; i++) { Destroy(GameObject.FindGameObjectsWithTag("dices")[i]); } } Card_M card; // ссылка на контейнер для карты. card = Instantiate(originalCard) as Card_M; // создание карты согласно базовой. if (Static_M.server) { Static_M.DiceIndexes[0] = Random.Range(0, dice_images0.Length); } card.setCard(0, dice_images0[index = Static_M.DiceIndexes[0]], Static_M.diceCoordinates(indexes[0])); card.tag = "dices"; switch (Static_M.numOfSequence) // определяем направление в соответствии с раскладкой карт. { case 0: if (index < 3) direction = -1; break; case 1: if (index == 2 || index > 3) direction = -1; break; case 2: if (index < 3) direction = -1; break; case 3: if (index < 3) direction = -1; break; } if (index == 0 || index == 4) { labValue += 3; } else if (index == 1 || index == 5) { labValue += 2; } else { labValue += 1; } card = Instantiate(originalCard) as Card_M; // создание карты согласно базовой. if (Static_M.server) { Static_M.DiceIndexes[1] = Random.Range(0, dice_images1.Length); } card.setCard(0, dice_images1[index = Static_M.DiceIndexes[1]], Static_M.diceCoordinates(indexes[1])); card.tag = "dices"; if (index == 0) diceValue += 10; card = Instantiate(originalCard) as Card_M; // создание карты согласно базовой. if (Static_M.server) { Static_M.DiceIndexes[2] = Random.Range(0, dice_images2.Length); } card.setCard(0, dice_images2[index = Static_M.DiceIndexes[2]], Static_M.diceCoordinates(indexes[2])); card.tag = "dices"; if (index == 1) diceValue += 1; card = Instantiate(originalCard) as Card_M; // создание карты согласно базовой. if (Static_M.server) { Static_M.DiceIndexes[3] = Random.Range(0, dice_images3.Length); } card.setCard(0, dice_images3[index = Static_M.DiceIndexes[3]], Static_M.diceCoordinates(indexes[3])); card.tag = "dices"; if (index == 0) diceValue += 100; //??? for (int i = 0; i < GameObject.FindGameObjectsWithTag("dices").Length; i++) { Destroy(GameObject.FindGameObjectsWithTag("dices")[i],60); //удаление карточек костей через 60сек. }//??? Static_M.diceValue = diceValue; Static_M.startPoint = labValue; Static_M.direction = direction; Static_M.throwDice = false; // отключаем автоматический запуск метода. Static_M.freezeThrowingDice = true;//замораживаем бросание костей. soundSources[0].PlayOneShot(audioClips[0]);//звуковой эффект. if (Static_M.server) { Searching(); //запускаем поиск. } } } private void Searching() { int[] cardValueSequence = _cardValuesSequence.Clone() as int[]; int value = Static_M.diceValue; int startIndex = -1; bool ventel = false; int iterations = 0; //количество итераций поиска. for (int i = 0; i < cardValueSequence.Length; i++) // находим стартовый индекс с которого начнем движение. { if (cardValueSequence[i] == Static_M.startPoint) { startIndex = i; break; } iterations++; } if (Static_M.direction == 1) // создание бесконечного цикла по часовой стрелке. { int i; for ( i = startIndex; i <= cardValueSequence.Length; i++) { iterations++; if (i == cardValueSequence.Length) i = 0;// создание бесконечного цикла по часовой стрелке. if (cardValueSequence[i] == value && !ventel) // проверка на соответствие значения. { Static_M.iterations = iterations; Static_M.id = _sequence[i]; _gameHelper.SendSearchDataOnClient();//рассылаем клиентам значение правильного выбора. return; } if (cardValueSequence[i] == 0 && !ventel) // проверка на вход в вентиляцию. { ventel = true; } else if (cardValueSequence[i] == 0 && ventel)// проверка на выход из вентиляции. { ventel = false; } if (cardValueSequence[i] < 4 && cardValueSequence[i] > 0 && !ventel) // проверка на мутацию. { if (cardValueSequence[i] == 1) // меняем форму. { if (value >= 1100) { value -= 100; } else { value += 100; } } else if (cardValueSequence[i] == 2) // меняем цвет. { if (value - 1010 == 100 || value - 1010 == 101 || value - 1010 == 0 || value - 1010 == 1) { value -= 10; } else { value += 10; } } else // меняем маркировку. { if (value % 2 != 0) { value -= 1; } else { value += 1; } } } } } else if (Static_M.direction == -1) // создание бесконечного цикла против часовой стрелки. { int i; for (i = startIndex; i > -2; i--) { iterations++; if (i == -1) i = cardValueSequence.Length-1; // создание бесконечного цикла против часовой стрелки. if (cardValueSequence[i] == value && !ventel) // проверка на соответствие значения. { Static_M.iterations = iterations; Static_M.id = _sequence[i]; _gameHelper.SendSearchDataOnClient();//рассылаем клиентам значение правильного выбора. return; } if (cardValueSequence[i] == 0 && !ventel) // проверка на вход в вентиляцию. { ventel = true; } else if (cardValueSequence[i] == 0 && ventel) // проверка на выход из вентиляции. { ventel = false; } if (cardValueSequence[i] < 4 && cardValueSequence[i] > 0 && !ventel) // проверка на мутацию. { if (cardValueSequence[i] == 1) // меняем форму. { if (value >= 1100) { value -= 100; } else { value += 100; } } else if (cardValueSequence[i] == 2) // меняем цвет. { if(value-1010==100 || value - 1010 == 101 || value - 1010 == 0 || value - 1010 == 1) { value -= 10; } else { value += 10; } } else // меняем маркировку. { if (value % 2 != 0) { value -= 1; } else { value += 1; } } } } } } private IEnumerator Pulse() { // yield return new WaitForSeconds(Static_M.wait*Static_M.iterations);//ожидаем Static_M.isCardButtonsActive = false; GameObject obj = GameObject.FindGameObjectWithTag(Static_M.id.ToString()); // Static_M.id = -2; // Static_M.myId = -1;//сбрасываем значение ручного выбора. Static_M.goodAnswer = 0; message.text = "не успел!"; for (int i = 0; i < 8; i++) { obj.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); soundSources[0].PlayOneShot(audioClips[1]);//звуковой эффект yield return new WaitForSeconds(0.05f); obj.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f); soundSources[0].PlayOneShot(audioClips[1]);//звуковой эффект yield return new WaitForSeconds(0.05f); } message.text = ""; Static_M.isStartButtonActive = true;//делаем кнопку старт активной. Static_M.freezeThrowingDice = false;//размораживаем бросание костей. Static_M.diceValue = 0;//сбрасываем значения } private IEnumerator Rotation() { Static_M.isCardButtonsActive = false; message.text = "правильно"; Static_M.myScore++; GameObject obj = GameObject.FindGameObjectWithTag(Static_M.myId.ToString()); // Static_M.myId = -1;//сбрасываем значение ручного выбора. // Static_M.id = -2;//сбрасываем значение ручного выбора. Quaternion pos = obj.transform.rotation;//сохраняем исходное значение вращения for (int i = 0; i < 8; i++) { yield return new WaitForSeconds(0.05f); obj.transform.Rotate(0, 0, -26); soundSources[0].PlayOneShot(audioClips[0]);//звуковой эффект } message.text = ""; obj.transform.rotation = pos;//возвращаем в исходное положение вращения. Static_M.freezeThrowingDice = false;//размораживаем бросание костей. Static_M.diceValue = 0;//сбрасываем значения Static_M.isStartButtonActive = true;//делаем кнопку старт активной. IsScoring();//проверка на количество сыгранных игр с запуском подсчета очков. } private IEnumerator QuickPulse() { GameObject obj = GameObject.FindGameObjectWithTag(Static_M.id.ToString()); // Static_M.myId = -1;//сбрасываем значение ручного выбора. //Static_M.id = -2; Static_M.isCardButtonsActive = false;//делаем карточки неактивными. Static_M.score++; message.text = "не верно!"; for (int i = 0; i < 8; i++) { soundSources[0].PlayOneShot(audioClips[1]);//звуковой эффект obj.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); yield return new WaitForSeconds(0.05f); soundSources[0].PlayOneShot(audioClips[1]);//звуковой эффект obj.transform.localScale = new Vector3(0.6f, 0.6f, 0.6f); yield return new WaitForSeconds(0.05f); } message.text = ""; Static_M.freezeThrowingDice = false;//размораживаем бросание костей. Static_M.diceValue = 0;//сбрасываем значения Static_M.isStartButtonActive = true;//делаем кнопку старт активной. IsScoring();//проверка на количество сыгранных игр с запуском подсчета очков. } private void Scoring() { GameObject.FindGameObjectWithTag("MainCamera").transform.position = new Vector3(0, -11.8f, -100); if (Static_M.score < Static_M.myScore) { int diff = Static_M.myScore - Static_M.score; if (diff == 10) { GameObject.Find("sc1").transform.position = new Vector3(0.06f, -11.33f, -2); scoringMessage.text = "Крутая победа без потерь, достойная настоящего чемпиона."; } else if (diff >6) { GameObject.Find("sc2").transform.position = new Vector3(0.06f, -11.33f, -2); scoringMessage.text = "Ровная победа, переход на уровень " + Static_M.level+1; } else if (diff >2) { GameObject.Find("sc3").transform.position = new Vector3(0.06f, -11.33f, -2); scoringMessage.text = "Трудное противостояние, и Вы переходите на уровень " + Static_M.level+1; } else { GameObject.Find("sc4").transform.position = new Vector3(0.06f, -11.33f, -2); scoringMessage.text = "Ух, чуть не проиграл, на следующем уровне будет реально трудно!"; } Static_M.wait -= 0.15f;//переход на другой уровень. Static_M.level++; } else if (Static_M.score == Static_M.myScore) { GameObject.Find("draw").transform.position = new Vector3(0.06f, -11.33f, -2); scoringMessage.text = "Бег на месте общепримеряющий..."; } else { GameObject.Find("loser").transform.position = new Vector3(0.06f, -11.33f, -2); scoringMessage.text = "Ничего, это был тяжелый уровень, в другой раз повезет."; if (Static_M.wait != 1f) { Static_M.wait += 0.15f;//переход на более низкий уровень. Static_M.level--; } } Static_M.gamesCount = 0; Static_M.score = 0; Static_M.myScore = 0; } public static void ScoringExit() { GameObject.Find("sc1").transform.position = new Vector3(0.06f, -11.33f, 1); GameObject.Find("sc2").transform.position = new Vector3(0.06f, -11.33f, 1); GameObject.Find("sc3").transform.position = new Vector3(0.06f, -11.33f, 1); GameObject.Find("sc4").transform.position = new Vector3(0.06f, -11.33f, 1); GameObject.Find("draw").transform.position = new Vector3(0.06f, -11.33f, 1); GameObject.Find("loser").transform.position = new Vector3(0.06f, -11.33f, 1); } private void IsScoring() { if (Static_M.gamesCount >= Static_M.numOfGames)//запускаем подсчет очков. { _gameHelper.SendLoadScore(); } } private void DestroyCards() { for (int i = 0; i < 26; i++) { // Destroy(GameObject.Find(_cardValuesSequence[i].ToString())); Destroy(GameObject.FindGameObjectWithTag(i.ToString())); } } private int[] ShuffleArray(int[] array) { int[] newArray = array.Clone() as int[]; for (int i = 0; i < newArray.Length; i++) { int r = Random.Range(i, newArray.Length); int tmp = newArray[i]; newArray[i] = newArray[r]; newArray[r] = tmp; } return newArray; } } <file_sep>/Assets/Scripts/PanicLab/Card.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Card : MonoBehaviour { [SerializeField] private SceneController sceneController; private int _id; public int id { get { return _id; } } public void setCard(int id, Sprite image, float[]coordinates) { GetComponent<SpriteRenderer>().sprite = image; transform.position = new Vector3(coordinates[0], coordinates[1], coordinates[2]); _id = id; } } <file_sep>/Assets/Scripts/PanicLab/SetActive.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SetActive : MonoBehaviour { public void setActive() { if (Static.gamesCount == 3) { GameObject.Find("CARDS_1").SetActive(false); } else if(Static.gamesCount == 6) { GameObject.Find("CARDS_0").SetActive(false); } Static.gamesCount++; } } <file_sep>/Assets/Scripts/PanicLab/Multiplayer/PlayerHelper.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using System; public class PlayerHelper : NetworkBehaviour { private GameHelper _gameHelper; [SyncVar] public string playerName; [SyncVar] public int playerId; // Use this for initialization void Start () { _gameHelper = GameObject.FindObjectOfType<GameHelper>(); if (isLocalPlayer) { _gameHelper.currentPlayer = this;//передача ссылки в свойство currentPlayer на этот объект. } } //chat-------------------------------- public void Send(string message) { // CmdSend(Network.player.guid, message); CmdSend(playerName, message); } [Command] public void CmdSend(string id, string message) { // int rand = UnityEngine.Random.Range(0, 100); RpcSend(id, message); } [ClientRpc] public void RpcSend(string id, string message) { _gameHelper.textBlock.text += System.Environment.NewLine +id+": "+message; } //chat----------------------------------- [Command] public void CmdPlayersLabelsFill() { RpcPlayersLabelsFill(playerId, playerName); } [Command] public void CmdPlayerReadyFill(bool empty) { RpcPlayerReadyFill(playerId, empty); Static_M.numOfPlayersReady++; } [Command] public void CmdSetGoodAnswer() { RpcSendGoodAnswer(playerId); } [Command] public void CmdLoadScore() { RpcLoadScenes(); } [ClientRpc] public void RpcPlayersLabelsFill(int id, string name) { _gameHelper.PlayerLabelFill(id, name); } [ClientRpc] public void RpcPlayerReadyFill(int id,bool empty) { _gameHelper.PlayerReadyFill(id,empty); } [ClientRpc] public void RpcCountDown() { _gameHelper.CountDown(); } [ClientRpc] public void RpcSetDicesOnClients(int[] diceIndexes) { _gameHelper.SetDicesOnClient(diceIndexes ); } [ClientRpc] public void RpcSetSearchDataOnClients(int id) { _gameHelper.SetSearchDataOnClient(id); } [ClientRpc] public void RpcSendGoodAnswer(int id) { _gameHelper.PlayerScoreFill(id); } [ClientRpc] public void RpcLoadScenes() { _gameHelper.LoadScores(); } } <file_sep>/Assets/Scripts/PanicLab/Static.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public static class Static { public static int gamesCount = 0;//количество сыгранных игр. public static bool throwDice = false;//активность запуска бросания кубиков. public static bool freezeThrowingDice = false;//активность бросание кубиков. public static bool isCardButtonsActive = false;//активность карточек. public static int diceValue = 0;//значение выпавших кубиков. public static int direction = 0;//направление поиска (по часой или против.) public static int startPoint = 0;// код лаборатории из которой начинается поиск. public static int iterations = 0;// количество итераций поиска. public static float wait = 1f; // задержка в секундах. public static int goodAnswer = 0; public static int numOfSequence = 0; public static int level = 1; public static bool isStartButtonActive = true;//значение активности стартовой кнопки. public static int id = -2;//ячейка для автоматически найденной карты. public static int myId = -1;//ячейка для найденной карты вручную. public static int myScore = 0; public static int score = 0; public static void init() { gamesCount = 0;//количество сыгранных игр. throwDice = false;//активность запуска бросания кубиков. freezeThrowingDice = false;//активность бросание кубиков. isCardButtonsActive = false;//активность карточек. diceValue = 0;//значение выпавших кубиков. direction = 0;//направление поиска (по часой или против.) startPoint = 0;// код лаборатории из которой начинается поиск. iterations = 0;// количество итераций поиска. wait = 0.5f; // задержка в секундах. goodAnswer = 0; isStartButtonActive = true;//значение активности стартовой кнопки. id = -2;//ячейка для автоматически найденной карты. myId = -1;//ячейка для найденной карты вручную. myScore = 0; score = 0; } public static float[] getCoordinates(int id) { switch (id) { case 0: return new float[3] { -5.21f, -3.75f, -1f }; case 1: return new float[3] { -5.21f, -2.5f, -1f }; case 2: return new float[3] { -5.21f, -1.23f, -1f }; case 3: return new float[3] { -5.21f, 0.07f, -1f }; case 4: return new float[3] { -5.21f, 1.34f, -1f }; case 5: return new float[3] { -5.21f, 2.65f, -1f }; case 6: return new float[3] { -3.84f, 2.65f, -1f }; case 7: return new float[3] { -2.51f, 2.65f, -1f }; case 8: return new float[3] { -1.2f, 2.65f, -1f }; case 9: return new float[3] { 0.04f, 2.65f, -1f }; case 10: return new float[3] { 1.33f, 2.65f, -1f }; case 11: return new float[3] { 2.61f, 2.65f, -1f }; case 12: return new float[3] { 3.91f, 2.65f, -1f }; case 13: return new float[3] { 5.29f, 2.65f, -1f }; case 14: return new float[3] { 5.29f, 1.37f, -1f }; case 15: return new float[3] { 5.29f, 0.1f, -1f }; case 16: return new float[3] { 5.29f, -1.16f, -1f }; case 17: return new float[3] { 5.29f, -2.42f, -1f }; case 18: return new float[3] { 5.29f, -3.75f, -1f }; case 19: return new float[3] { 3.94f, -3.75f, -1f }; case 20: return new float[3] { 2.61f, -3.75f, -1f }; case 21: return new float[3] { 1.25f, -3.75f, -1f }; case 22: return new float[3] { 0.01f, -3.75f, -1f }; case 23: return new float[3] { -1.32f, -3.75f, -1f }; case 24: return new float[3] { -2.67f, -3.75f, -1f }; case 25: return new float[3] { -3.95f, -3.75f, -1f }; default: return null; } } public static float[]diceCoordinates(int id) { switch (id) { case 0: return new float[] { -1.46f, 1.06f, -1 }; case 1: return new float[] { 1.44f, 1.03f, -1 }; case 2: return new float[] { 1.44f, -1.75f, -1 }; case 3: return new float[] { -1.37f, -1.78f, -1 }; default: return null; } } public static int[]sequences(int i) { switch (i) { case 0: return new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; case 1: return new int[] { 3, 4, 2, 9, 8, 22, 6, 14, 15, 13, 7, 11, 17, 21, 1, 10, 16, 12, 23, 19, 20, 0, 25, 18, 24, 5 }; case 2: return new int[] { 2, 1, 0, 3, 25, 6, 5, 7, 8, 9, 24, 11, 12, 13, 15, 14, 16, 18, 17, 19, 10, 22, 21, 23, 20, 4 }; case 3: return new int[] { 0, 1, 22, 13, 4, 8, 6, 7, 5, 10, 9, 11, 12, 3, 14, 15, 16, 17, 18, 21, 24, 19, 2, 23, 20, 25 }; default: return null; } } // 1.живой1 2.двуглазый1 3.светлый1 4.крапчатый1 // 1.лаборатория1 2.красный1 желтый2 синий3 // 1.мутация0 2.форма1 цвет2 маркировка3 public static int[] cardValuesSequence = new int[26] { 0, 1111, 1000, 1010, 2, 12, 1110, 1100, 1011, 0, 1001, 1, 1001, 1011, 11, 1101, 1111, 0, 1000, 1010, 1110, 13, 3, 1100, 1101, 1}; } <file_sep>/Assets/Scripts/PanicLab/Multiplayer/NetworkLobbyHookMy.cs using UnityEngine;
using System;
using Prototype.NetworkLobby;
using System.Collections;
using UnityEngine.Networking;

public class NetworkLobbyHookMy : LobbyHook
{
 
 public override void OnLobbyServerSceneLoadedForPlayer(NetworkManager manager, GameObject lobbyPlayer, GameObject gamePlayer)
 {
 LobbyPlayer lobby = lobbyPlayer.GetComponent<LobbyPlayer>();
 PlayerHelper player = gamePlayer.GetComponent<PlayerHelper>();

 Static_M.server = true; // статическое поле заполняется только на сервере.
 player.playerId = Static_M.numOfPlayers++;// статическое поле заполняется только на сервере. if (lobby.nameInput.text.Length > 12) { player.playerName = lobby.nameInput.text.Substring(0, 12);// задаем имя игрока из лобби и обрезаем его до 12 символов. } else { player.playerName = lobby.nameInput.text; } }
}

266199c89740e4e2306b82a23a123cbd284a710f
[ "Markdown", "C#" ]
12
C#
EugenSeko/Unity-sandbox
eee2ea9b2d0c26122e99bfd470a6659ac98783aa
97e9e61882ffb8cdd721785e266267be36a09c61
refs/heads/master
<repo_name>kaleshaTBD/application<file_sep>/application/src/main/java/com/company/application/model/Student.java package com.company.application.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Student implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String mf11_compCode; private String mf11_compCodeHRIS; private String mf11_compName; private String mf11_compAbbrName; private String mf11_compRegNo; private String mf11_compLogo ; private String Mf11_compActiveDate; private Boolean mf11_isActive; private String mf11_createdOn; private String mf11_createdBy; private String mf11_lastModifiedOn ; private String mf11_deactivatedBy; private String mf11_lastModifiedBy; private String mf11_deactivatedOn; private String mf11_reactivatedBye; private String mf11_reactivatedOn; public Student(String mf11_compCode, String mf11_compCodeHRIS, String mf11_compName, String mf11_compAbbrName, String mf11_compRegNo, String mf11_compLogo, String mf11_compActiveDate, Boolean mf11_isActive, String mf11_createdOn, String mf11_createdBy, String mf11_lastModifiedOn, String mf11_deactivatedBy, String mf11_lastModifiedBy, String mf11_deactivatedOn, String mf11_reactivatedBye, String mf11_reactivatedOn) { super(); this.mf11_compCode = mf11_compCode; this.mf11_compCodeHRIS = mf11_compCodeHRIS; this.mf11_compName = mf11_compName; this.mf11_compAbbrName = mf11_compAbbrName; this.mf11_compRegNo = mf11_compRegNo; this.mf11_compLogo = mf11_compLogo; Mf11_compActiveDate = mf11_compActiveDate; this.mf11_isActive = mf11_isActive; this.mf11_createdOn = mf11_createdOn; this.mf11_createdBy = mf11_createdBy; this.mf11_lastModifiedOn = mf11_lastModifiedOn; this.mf11_deactivatedBy = mf11_deactivatedBy; this.mf11_lastModifiedBy = mf11_lastModifiedBy; this.mf11_deactivatedOn = mf11_deactivatedOn; this.mf11_reactivatedBye = mf11_reactivatedBye; this.mf11_reactivatedOn = mf11_reactivatedOn; } public String getMf11_compCode() { return mf11_compCode; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getMf11_lastModifiedBy() { return mf11_lastModifiedBy; } public void setMf11_lastModifiedBy(String mf11_lastModifiedBy) { this.mf11_lastModifiedBy = mf11_lastModifiedBy; } public void setMf11_compCode(String mf11_compCode) { this.mf11_compCode = mf11_compCode; } public String getMf11_compCodeHRIS() { return mf11_compCodeHRIS; } public void setMf11_compCodeHRIS(String mf11_compCodeHRIS) { this.mf11_compCodeHRIS = mf11_compCodeHRIS; } public String getMf11_compName() { return mf11_compName; } public void setMf11_compName(String mf11_compName) { this.mf11_compName = mf11_compName; } public String getMf11_compAbbrName() { return mf11_compAbbrName; } public void setMf11_compAbbrName(String mf11_compAbbrName) { this.mf11_compAbbrName = mf11_compAbbrName; } public String getMf11_compRegNo() { return mf11_compRegNo; } public void setMf11_compRegNo(String mf11_compRegNo) { this.mf11_compRegNo = mf11_compRegNo; } public String getMf11_compLogo() { return mf11_compLogo; } public void setMf11_compLogo(String mf11_compLogo) { this.mf11_compLogo = mf11_compLogo; } public String getMf11_compActiveDate() { return Mf11_compActiveDate; } public void setMf11_compActiveDate(String mf11_compActiveDate) { Mf11_compActiveDate = mf11_compActiveDate; } public Boolean getMf11_isActive() { return mf11_isActive; } public void setMf11_isActive(Boolean mf11_isActive) { this.mf11_isActive = mf11_isActive; } public String getMf11_createdOn() { return mf11_createdOn; } public void setMf11_createdOn(String mf11_createdOn) { this.mf11_createdOn = mf11_createdOn; } public String getMf11_createdBy() { return mf11_createdBy; } public void setMf11_createdBy(String mf11_createdBy) { this.mf11_createdBy = mf11_createdBy; } public String getMf11_lastModifiedOn() { return mf11_lastModifiedOn; } public void setMf11_lastModifiedOn(String mf11_lastModifiedOn) { this.mf11_lastModifiedOn = mf11_lastModifiedOn; } public String getMf11_deactivatedBy() { return mf11_deactivatedBy; } public void setMf11_deactivatedBy(String mf11_deactivatedBy) { this.mf11_deactivatedBy = mf11_deactivatedBy; } public String getMf11_deactivatedOn() { return mf11_deactivatedOn; } public void setMf11_deactivatedOn(String mf11_deactivatedOn) { this.mf11_deactivatedOn = mf11_deactivatedOn; } public String getMf11_reactivatedBye() { return mf11_reactivatedBye; } public void setMf11_reactivatedBye(String mf11_reactivatedBye) { this.mf11_reactivatedBye = mf11_reactivatedBye; } public String getMf11_reactivatedOn() { return mf11_reactivatedOn; } public void setMf11_reactivatedOn(String mf11_reactivatedOn) { this.mf11_reactivatedOn = mf11_reactivatedOn; } public Student() {} }<file_sep>/application/src/main/java/com/company/application/Application.java package com.company.application; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CrossOrigin; 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.multipart.MultipartFile; @SpringBootApplication @ComponentScan(basePackages = "com.company.application") @EntityScan(basePackages = "com.company.application.model") @EnableJpaRepositories(basePackages = "com.company.application.repository") @Configuration public class Application{ public static void main(String[] args) { SpringApplication.run(Application.class, args); } } <file_sep>/application/src/main/java/com/company/application/repository/StudentRepository.java package com.company.application.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.company.application.model.Student; @Repository public interface StudentRepository extends CrudRepository<Student, Long> { Student findById(long id); } <file_sep>/application/src/main/java/com/company/application/service/UserService.java package com.company.application.service; import com.company.application.model.User; public interface UserService { public User findUserByEmail(String email); public void saveUser(String fname, String lname, String email, String pwd); }
3e7f0d65d69da880ece17cb1010a79a867e4f3a5
[ "Java" ]
4
Java
kaleshaTBD/application
558ce91a6c7746386506686ee4506418880f5922
860394fae3e9fc1cfce40eea572bed22af2609a5
refs/heads/master
<repo_name>ksk-t/HabitTracker<file_sep>/HabitTracker/Drivers/ExternalPeripherals/IOStreamUART.cpp /* * IOStreamUART.cpp * * Created on: Apr 22, 2021 * Author: keisu */ #include "IOStreamUART.h" static const size_t RX_BUFFER_SIZE = 128; static uint8_t m_rx_buffer[RX_BUFFER_SIZE]; static const size_t RX_INTERRUPT_BUFFER_SIZE = 1; static uint8_t m_rx_interrupt_buffer[RX_INTERRUPT_BUFFER_SIZE]; static volatile size_t m_bytes_available = 0; void HAL_UART_RxCpltCallback(UART_HandleTypeDef* huart) { // Assume interrupt buffer is only one byte long if (m_bytes_available < RX_BUFFER_SIZE) { m_rx_buffer[m_bytes_available] = m_rx_interrupt_buffer[0]; // Receive next byte HAL_UART_Receive_IT(huart, m_rx_interrupt_buffer, RX_INTERRUPT_BUFFER_SIZE); m_bytes_available++; } } IOStreamUART::IOStreamUART(UART_HandleTypeDef* uart_handle) : m_uart_handle(uart_handle), m_read_offset(0) { std::fill_n(m_rx_buffer, RX_BUFFER_SIZE, 0); HAL_UART_Receive_IT(m_uart_handle, m_rx_interrupt_buffer, RX_INTERRUPT_BUFFER_SIZE); } size_t IOStreamUART::Read(uint8_t* buffer, size_t size) { size_t bytes_read = 0; // Fill read buffer with available data while ((bytes_read < size) && (bytes_read < m_bytes_available)) { buffer[bytes_read] = m_rx_buffer[bytes_read]; bytes_read++; } // Resets buffer even if all bytes weren't read. This simplifies the logic for now. HAL_UART_AbortReceive_IT(m_uart_handle); m_bytes_available = 0; HAL_UART_Receive_IT(m_uart_handle, m_rx_interrupt_buffer, RX_INTERRUPT_BUFFER_SIZE); return bytes_read; } size_t IOStreamUART::Write(uint8_t* buffer, size_t size) { HAL_UART_Transmit(m_uart_handle, buffer, size,0xffff); return size; } size_t IOStreamUART::BytesAvailable() { return m_bytes_available; } bool IOStreamUART::IsRxBufferFull() { return m_bytes_available == RX_BUFFER_SIZE; } bool IOStreamUART::Peak(size_t index, uint8_t &value) { if (index < m_bytes_available) { value = m_rx_buffer[index]; return true; }else { return false; } } void IOStreamUART::TransmitStartChars() { uint8_t start_chars[] = "\n\r>"; HAL_UART_Transmit(m_uart_handle, start_chars, sizeof(start_chars) / sizeof(start_chars[0]), 0xffff); } <file_sep>/HabitTracker/Core/Src/LoggerTask.h /* * LoggerTask.h * * Created on: Apr 1, 2021 * Author: keisu */ #ifndef SRC_LOGGERTASK_H_ #define SRC_LOGGERTASK_H_ class LoggerTask { public: void Run(); }; #endif /* SRC_LOGGERTASK_H_ */ <file_sep>/HabitTracker/Core/Src/GUIStateBase.h /* * GUIStateBase.h * * Created on: Mar 30, 2021 * Author: keisu */ #ifndef SRC_GUISTATEBASE_H_ #define SRC_GUISTATEBASE_H_ #include "GraphicsEngine.h" class GUIControllerTask; class GUIStateBase { public: GUIStateBase(GraphicsEngine* gfx_engine, GUIControllerTask* controller) : m_gfx_engine(gfx_engine), m_controller(controller) {}; virtual void UILeft(){}; virtual void UIRight(){}; virtual void UISelect(){}; virtual void UIDraw(){}; virtual void OnLoaded(){}; virtual ~GUIStateBase() {}; protected: GraphicsEngine* m_gfx_engine; GUIControllerTask* m_controller; }; #endif /* SRC_GUISTATEBASE_H_ */ <file_sep>/HabitTrackerUnitTests/src/IOStreamMock.h /* * IOStreamMoch.h * * Created on: Apr 17, 2021 * Author: keisu */ #ifndef IOSTREAMMOCH_H_ #define IOSTREAMMOCH_H_ #include "IOStreamBase.h" #include <array> class IOStreamMock : public IOStreamBase { public: size_t Read(uint8_t* buffer, size_t size) override; size_t Write(uint8_t* buffer, size_t size) override {return 0;}; void WriteReadBuffer(uint8_t* buffer, size_t size); private: std::array<uint8_t, 128> m_buffer; size_t m_size; }; #endif /* IOSTREAMMOCH_H_ */ <file_sep>/HabitTracker/Core/Src/GUIStateHabits.h /* * GUIStateHabits.h * * Created on: Apr 5, 2021 * Author: keisu */ #ifndef SRC_GUISTATEHABITS_H_ #define SRC_GUISTATEHABITS_H_ #include "GUIStateBase.h" #include "RealTimeClock.h" #include "HabitManager.h" class GUIStateHabits : public GUIStateBase { public: GUIStateHabits(GraphicsEngine* gfx_engine, GUIControllerTask* controller, RealTimeClock* rtc, HabitManager *habit_manager); void UILeft() override; void UIRight() override; void UISelect() override; void UIDraw() override; void OnLoaded() override; protected: RealTimeClock* m_rtc; HabitManager* m_habit_manager; private: void DrawHabit(Habit_t); void DrawStringWithTime(std::string str); size_t m_habit_index{0}; }; #endif /* SRC_GUISTATEHABITS_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Color.h /* * Color.h * * Created on: Mar 28, 2021 * Author: keisu */ #ifndef COLOR_H_ #define COLOR_H_ #include <cstdint> struct Color_t { Color_t (uint8_t r_val = 0, uint8_t g_val = 0, uint8_t b_val = 0) : R(r_val), G(g_val), B(b_val) {} uint8_t R{0}; uint8_t G{0}; uint8_t B{0}; bool operator==(const Color_t &c) { return (R == c.R) && (G == c.G) && (B == c.B); } }; struct BasicColors { static const Color_t Black; static const Color_t White; }; #endif /* COLOR_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/GraphicsEngine.cpp /* * GraphicsEngine.cpp * * Created on: Mar 28, 2021 * Author: keisu */ #include "GraphicsEngine.h" #include "GraphicsUtilities.h" #include "Logger.h" const static std::string MODULE_NAME = "GraphicsEngine"; GraphicsEngine::GraphicsEngine(Display* display) : m_display(display) { m_font = &Font_7x10; } void GraphicsEngine::Update() { if (Status_t::OK != m_display->Update()) { Logger(LoggingLevel::Error, MODULE_NAME).Get() << "Failed to update display"; } } void GraphicsEngine::Initialize() { if (Status_t::OK != m_display->Initialize()) { Logger(LoggingLevel::Error, MODULE_NAME).Get() << "Failed to initialize"; } } void GraphicsEngine::DrawChar(const Point_t point, const Color_t color, const char ch) { uint32_t i, b, j; Point_t curr_point{}; // Check if character is valid if (ch < 32 || ch > 126) return; // Check remaining space on current line if (m_display->GetWidth() < (point.X + m_font->FontWidth) || m_display->GetHeight() < (point.Y + m_font->FontHeight)) { // Not enough space on current line return; } // Use the font to write for (i = 0; i < m_font->FontHeight; i++) { b = m_font->data[(ch - 32) * m_font->FontHeight + i]; for (j = 0; j < m_font->FontWidth; j++) { if ((b << j) & 0x8000) { curr_point.X = point.X + j; curr_point.Y = point.Y + m_font->FontHeight - i; // the " + font.FontHeight - i" flips the character upside down m_display->DrawPixel(curr_point, color); } } } } void GraphicsEngine::DrawString(Point_t point, Color_t color, std::string str) { Point_t curr_point = point; for (std::string::const_iterator iter = str.begin(); iter != str.end(); iter++) { this->DrawChar(curr_point, color, *iter); curr_point.X += m_font->FontWidth; } } void GraphicsEngine::DrawStringWrap(Point_t point, Color_t color, std::string string) { if (string.length() == 0) { return; } const size_t max_lines = 10; std::string lines[max_lines]; size_t num_lines = GraphicsUtilities::WrapText(string, lines, max_lines, m_font->FontWidth, m_display->GetWidth() - point.X); if (num_lines == 0) { return; } for (size_t i = 0; i < num_lines; i++) { this->DrawString(point, color, lines[i]); point.Y -= m_font->FontHeight; } } void GraphicsEngine::DrawBox(Point_t point, uint32_t width, uint32_t height, const Color_t outline_color, const Color_t fill_color) { Point_t current_point{point.X, point.Y}; for (uint32_t x = 0; x < width; x++) { for (uint32_t y = 0; y < height; y++) { current_point.X = point.X + x; current_point.Y = point.Y + y; if (current_point.X < m_display->GetWidth() && current_point.Y < m_display->GetHeight()) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { m_display->DrawPixel(current_point, outline_color); }else { m_display->DrawPixel(current_point, fill_color); } } } } } void GraphicsEngine::Fill(const Color_t color) { Point_t current_point{}; for (uint32_t x = 0; x < m_display->GetWidth(); x++) { for (uint32_t y = 0; y < m_display->GetHeight(); y++) { current_point.X = x; current_point.Y = y; m_display->DrawPixel(current_point, color); } } } void GraphicsEngine::SetFont(BasicFont* font) { m_font = font; } uint32_t GraphicsEngine::GetDisplayHeight() { return m_display->GetHeight(); } uint32_t GraphicsEngine::GetDisplayWidth() { return m_display->GetWidth(); } void GraphicsEngine::DrawLine(Point_t point1, Point_t point2, const Color_t color) { int32_t deltaX = abs(point2.X - point1.X); int32_t deltaY = abs(point2.Y - point1.Y); int32_t signX = ((point1.X < point2.X) ? 1 : -1); int32_t signY = ((point1.Y < point2.Y) ? 1 : -1); int32_t error = deltaX - deltaY; int32_t error2; m_display->DrawPixel(point2, color); while ((point1.X != point2.X) || (point1.Y != point2.Y)) { m_display->DrawPixel(point1, color); error2 = error * 2; if (error2 > -deltaY) { error -= deltaY; point1.X += signX; } else { /*nothing to do*/ } if (error2 < deltaX) { error += deltaX; point1.Y += signY; } else { /*nothing to do*/ } } } <file_sep>/HabitTrackerUnitTests/src/RotaryEncoderTests.cpp /* * RotaryEncoderTests.cpp * * Created on: Apr 12, 2021 * Author: keisu */ #include "RotaryEncoder.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(RotaryEncoderTests) { RotaryEncoder *encoder; const uint32_t initial_pos = 0; void setup() { encoder = new RotaryEncoder(initial_pos); } void teardown() { delete encoder; } }; TEST(RotaryEncoderTests, no_movement) { CHECK_FALSE(encoder->HasMoved(0)); CHECK_FALSE(encoder->HasMoved(1)); CHECK_FALSE(encoder->HasMoved(65535)); } TEST(RotaryEncoderTests, movement_no_overflow) { CHECK(encoder->HasMoved(2)); } TEST(RotaryEncoderTests, movement_with_overflow) { CHECK(encoder->HasMoved(65534)); } TEST(RotaryEncoderTests, movement_after_no_movement) { CHECK(encoder->HasMoved(2)); CHECK_FALSE(encoder->HasMoved(2)); CHECK(encoder->HasMoved(0)); } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/GraphicsEngine.h /* * GraphicsEngine.h * * Created on: Mar 28, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_GRAPHICSENGINE_H_ #define EXTERNALPERIPHERALS_GRAPHICSENGINE_H_ #include "Display.h" #include "BasicFonts.h" #include <string> class GraphicsEngine { public: GraphicsEngine(Display* display); void Initialize(); void Fill(); void Update(); void InvertRegion(); void DrawChar(const Point_t point, const Color_t, const char ch); void SetFont(BasicFont* font); void DrawString(Point_t point, Color_t color, std::string string); void DrawStringWrap(Point_t point, Color_t color, std::string string); void DrawBox(const Point_t point, const uint32_t width, const uint32_t height, const Color_t outline_color, const Color_t fill_color); void DrawLine(const Point_t point1, const Point_t point2, const Color_t color); void Fill(const Color_t color); uint32_t GetDisplayHeight(); uint32_t GetDisplayWidth(); private: Display* m_display; BasicFont* m_font; }; #endif /* EXTERNALPERIPHERALS_GRAPHICSENGINE_H_ */ <file_sep>/HabitTracker/Core/Src/GUIStateClock.cpp /* * GUIStateClock.cpp * * Created on: Mar 30, 2021 * Author: keisu */ #include "GUIStateClock.h" #include "Logger.h" static const std::string MODULE_NAME = "GUIStateClock"; void GUIStateClock::OnLoaded() { this->DrawTime(); } void GUIStateClock::UIDraw() { this->DrawTime(); } void GUIStateClock::DrawTime() { if (m_gfx_engine == nullptr) { Logger(LoggingLevel::Error, MODULE_NAME).Get() << "GFX Engine null"; return; } BasicFont* font = &Font_16x26; m_gfx_engine->SetFont(font); Point_t point{0, m_gfx_engine->GetDisplayHeight() / 2 - font->FontHeight / 2}; m_gfx_engine->Fill(BasicColors::Black); m_gfx_engine->DrawString(point, BasicColors::White, "testval"); m_gfx_engine->Update(); } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/RotaryEncoder.cpp /* * RotaryEncoder.cpp * * Created on: Apr 12, 2021 * Author: keisu */ #include "RotaryEncoder.h" RotaryEncoder::RotaryEncoder(uint16_t init_pos) : m_prev_pos(init_pos) { } bool RotaryEncoder::HasMoved(uint16_t current_pos) { uint16_t encoder_diff = current_pos - m_prev_pos; if (encoder_diff <= 65534 && encoder_diff >= 2) // This ensures that there is at least a difference of 2 in the count value. 1 notch on the encoder = 2 counter values { m_prev_pos = current_pos; return true; } return false; } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/RotaryEncoder.h /* * RotaryEncoder.h * * Created on: Apr 12, 2021 * Author: keisu * * NOTE: This only works for a 16 bit encoder * */ #ifndef EXTERNALPERIPHERALS_ROTARYENCODER_H_ #define EXTERNALPERIPHERALS_ROTARYENCODER_H_ #include <cstdint> class RotaryEncoder { public: RotaryEncoder(uint16_t init_pos); bool HasMoved(uint16_t current_pos); private: uint16_t m_prev_pos; }; #endif /* EXTERNALPERIPHERALS_ROTARYENCODER_H_ */ <file_sep>/HabitTracker/Core/Src/Habit.h /* * Habit.h * * Created on: Apr 8, 2021 * Author: keisu */ #ifndef SRC_HABITS_H_ #define SRC_HABITS_H_ #include <string> #include <cstdint> struct Habit_t { std::string Name{""}; bool IsComplete{false}; uint32_t Streak{0}; }; #endif <file_sep>/HabitTracker/Core/Src/GUIStateHabits.cpp /* * GUIStateHabits.cpp * * Created on: Apr 5, 2021 * Author: keisu */ #include "GUIStateHabits.h" #include "GUIControllerTask.h" // Required to use controller. Header file for GUIStateBase only includes forward delaration. Not only implementation details #include "HabitManager.h" GUIStateHabits::GUIStateHabits(GraphicsEngine* gfx_engine, GUIControllerTask* controller, RealTimeClock* rtc, HabitManager *habit_manager) : GUIStateBase(gfx_engine, controller), m_rtc(rtc), m_habit_manager(habit_manager) { Habit_t habit; habit.Name = "test habit"; habit.IsComplete = true; habit.Streak = 123; m_habit_manager->AddHabit(habit); habit.Name = "habit 2"; habit.IsComplete = false; habit.Streak = 1; m_habit_manager->AddHabit(habit); } void GUIStateHabits::UILeft() { if (m_habit_index > 0) { Habit_t habit; if (m_habit_manager->GetHabit(--m_habit_index, habit)) { DrawHabit(habit); }else { DrawStringWithTime("Error getting habit"); } } } void GUIStateHabits::UIRight() { if (m_habit_index < m_habit_manager->Count() - 1) { Habit_t habit; if (m_habit_manager->GetHabit(++m_habit_index, habit)) { DrawHabit(habit); }else { DrawStringWithTime("Error getting habit"); } } } void GUIStateHabits::UISelect() { Habit_t habit; m_habit_manager->ToggleHabit(m_habit_index); m_habit_manager->GetHabit(m_habit_index, habit); DrawHabit(habit); } void GUIStateHabits::UIDraw() { Habit_t habit; m_habit_manager->GetHabit(m_habit_index, habit); DrawHabit(habit); } void GUIStateHabits::OnLoaded() { Habit_t habit; m_habit_index = 0; if (m_habit_manager->GetHabit(m_habit_index, habit)) { DrawHabit(habit); }else { DrawStringWithTime("No Habits"); } m_controller->RefreshInterval = 200; } void GUIStateHabits::DrawStringWithTime(std::string str) { BasicFont* font = &Font_7x10; Point_t cursor{0, m_gfx_engine->GetDisplayHeight() - font->FontHeight - 1}; // Display time on top row // Draw clock on top row m_gfx_engine->SetFont(&Font_7x10); m_gfx_engine->Fill(BasicColors::Black); m_gfx_engine->DrawString(cursor, BasicColors::White, m_rtc->GetTime().ToString()); Point_t end_of_line{m_gfx_engine->GetDisplayWidth() - 1, cursor.Y}; m_gfx_engine->DrawLine(cursor, end_of_line, BasicColors::White); cursor.Y -= font->FontHeight + 1; // Draw string m_gfx_engine->DrawStringWrap(cursor, BasicColors::White, str); m_gfx_engine->Update(); } void GUIStateHabits::DrawHabit(Habit_t habit) { std::string habit_string = habit.Name; habit_string += "\nStatus: "; habit_string += (habit.IsComplete) ? "Complete" : "Incomplete"; habit_string += "\nStreak: " + std::to_string(habit.Streak); DrawStringWithTime(habit_string); } <file_sep>/HabitTrackerUnitTests/src/BasicTimerTests.cpp /* * BasicTimerTests.cpp * * Created on: Apr 25, 2021 * Author: keisu */ #include "BasicTimer.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(BasicTimerTests) { BasicTimer* timer; void setup() { timer = new BasicTimer(); } void teardown() { delete timer; } }; TEST(BasicTimerTests, time_not_expired) { timer->Start(0, 10); CHECK_FALSE(timer->HasExpired(9)); timer->Start(10, 10); CHECK_FALSE(timer->HasExpired(19)); } TEST(BasicTimerTests, time_expired) { timer->Start(0, 10); CHECK(timer->HasExpired(10)); } TEST(BasicTimerTests, time_not_expired_overflow) { timer->Start(UINT32_MAX, 10); CHECK_FALSE(timer->HasExpired(5)); } TEST(BasicTimerTests, time_expired_overflow) { timer->Start(UINT32_MAX, 10); CHECK(timer->HasExpired(10)); } <file_sep>/HabitTracker/Core/Src/GUIControllerTask.cpp /* * GUIController.cpp * * Created on: Apr 2, 2021 * Author: keisu */ #include "GUIControllerTask.h" #include "Logger.h" static const std::string MODULE_NAME = "GUIController"; GUIControllerTask::GUIControllerTask() { m_states.fill(nullptr); } bool GUIControllerTask::AddState(GUIStateBase* state_ptr, GUIState state_enum) { uint32_t state_int = static_cast<uint32_t>(state_enum); if (state_int >= m_states.size()) { Logger(LoggingLevel::Error, MODULE_NAME).Get() << "AddState: Failed to add state. Max number of states reached"; return false; } m_states[state_int] = state_ptr; return true; } void GUIControllerTask::SetState(GUIState new_state) { if (m_states[static_cast<uint32_t>(new_state)] != nullptr) { m_curr_state = m_states[static_cast<uint32_t>(new_state)]; m_curr_state->OnLoaded(); }else { Logger(LoggingLevel::Error, MODULE_NAME).Get() << "SetState: State enum has no state referenced to it"; } } void GUIControllerTask::UIDraw() { if (m_curr_state != nullptr) { m_curr_state->UIDraw(); }else { Logger(LoggingLevel::Error, MODULE_NAME).Get() << "UIDraw: current state null"; } }; void GUIControllerTask::Run() { // Read inputi tespting test for(;;) { // Add timer to trigger ui to redraw? } } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Time.h /* * Time.h * * Created on: Apr 4, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_TIME_H_ #define EXTERNALPERIPHERALS_TIME_H_ #include <cstdint> #include <string> enum class TimeFormat_t { Format_12_AM, Format_12_PM }; enum class DayLightSaving_t { Sub_1H, Add_1H, None }; enum class StoreOperation_t { Reset, Set }; struct Time_t { uint8_t Hours{12}; uint8_t Minutes{0}; uint8_t Seconds{0}; TimeFormat_t TimeFormat{TimeFormat_t::Format_12_AM}; DayLightSaving_t DayLightSaving{DayLightSaving_t::None}; StoreOperation_t StoreOperation{StoreOperation_t::Reset}; std::string ToString(bool toggle_colon = false); }; #endif /* EXTERNALPERIPHERALS_TIME_H_ */ <file_sep>/HabitTracker/Core/Src/Logger.cpp /* * Logger.cpp * * Created on: Apr 1, 2021 * Author: keisu */ #include "Logger.h" #include "StatusLED.h" #include "cmsis_os.h" extern osMessageQueueId_t g_logger_queueHandle; #define LOGGING_DEBUG_ENABLE #define LOGGING_ERROR_ENABLE #define LOGGING_LED_ALERT_ENABLE std::ostringstream& Logger::Get() { os << "[" << std::string(osThreadGetName(osThreadGetId())) << "][" << m_module << "]: "; return os; } Logger::~Logger() { switch (m_level) { case LoggingLevel::Debug: #ifndef LOGGING_DEBUG_ENABLE return; #endif break; case LoggingLevel::Error: #ifdef LOGGING_LED_ALERT_ENABLE StatusLED::SetErrorEvent(); #endif #ifndef LOGGING_ERROR_ENABLE return; #endif break; } std::string message = os.str() + "\n"; osMessageQueuePut(g_logger_queueHandle, message.c_str(), 0U, 0U); } <file_sep>/HabitTrackerUnitTests/src/IOStreamMock.cpp /* * IOStreamMock.cpp * * Created on: Apr 17, 2021 * Author: keisu */ #include "IOStreamMock.h" void IOStreamMock::WriteReadBuffer(uint8_t* buffer, size_t size) { size_t index; for (index = 0; index < size && index < m_buffer.size(); index++) { m_buffer[index] = buffer[index]; } m_size = index; } size_t IOStreamMock::Read(uint8_t* buffer, size_t size) { size_t index; for (index = 0; index < size && index < m_size; index++) { buffer[index] = m_buffer[index]; } return index; } <file_sep>/HabitTrackerUnitTests/src/main.cpp //============================================================================ // Name : HabitTrackerUnitTests.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include "CppUTest/CommandLineTestRunner.h" int main(int ac, char** av) { return CommandLineTestRunner::RunAllTests(ac, av); } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/RealTimeClock.h /* * RealTimeClock.h * * Created on: Apr 4, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_REALTIMECLOCK_H_ #define EXTERNALPERIPHERALS_REALTIMECLOCK_H_ #include "stm32f2xx_hal.h" #include "Time.h" class RealTimeClock { public: RealTimeClock(RTC_HandleTypeDef* handle) : m_handle(handle) {}; void Initialize(); Time_t GetTime(); private: RTC_HandleTypeDef* m_handle; }; #endif /* EXTERNALPERIPHERALS_REALTIMECLOCK_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Status.h /* * Status.h * * Created on: Apr 6, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_STATUS_H_ #define EXTERNALPERIPHERALS_STATUS_H_ enum class Status_t { OK = 0, ERROR = 1 << 0, BUSY = 1 << 1, TIMEOUT = 1 << 2 }; inline Status_t operator|(Status_t a, Status_t b) { return static_cast<Status_t>(static_cast<int>(a) | static_cast<int>(b)); } inline Status_t& operator |=(Status_t& a, Status_t b) { return a = a | b; } #endif /* EXTERNALPERIPHERALS_STATUS_H_ */ <file_sep>/HabitTracker/Core/Src/IOStreamBase.h /* * IOStream.h * * Created on: Apr 17, 2021 * Author: keisu */ #ifndef SRC_IOSTREAMBASE_H_ #define SRC_IOSTREAMBASE_H_ #include <cstdint> #include <cstddef> #include <array> class IOStreamBase { public: // Reads data from stream and copies data to buffer // // @param buffer Buffer to write the read data to // @param size of the buffer // @return Number of bytes actually read virtual size_t Read(uint8_t* buffer, size_t size) {return 0;}; // Write data stream // // @param buffer Buffer containing data to write // @param size Size of buffer // @return number of bytes actually written virtual size_t Write(uint8_t* buffer, size_t size) {return 0;}; virtual ~IOStreamBase() {}; }; #endif /* SRC_IOSTREAM_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/IOStreamUART.h /* * IOStreamUART.h * * Created on: Apr 22, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_IOSTREAMUART_H_ #define EXTERNALPERIPHERALS_IOSTREAMUART_H_ #include "IOStreamBase.h" #include "stm32f2xx_hal.h" class IOStreamUART : public IOStreamBase { public: /* * Construtor */ IOStreamUART(UART_HandleTypeDef* uart_handle); /* * Read data available in the receive buffer * * @param buffer Buffer to write the received data to * @param size Size size of buffer * * @return numbers of bytes actually read */ size_t Read(uint8_t* buffer, size_t size) override; /* * Write data to the io stream * * @param buffer Buffer containing data to write to io stream * @param size Number of bytes in buffer * * @return Number of bytes written */ size_t Write(uint8_t* buffer, size_t size) override; /* * Peak at a certain value in the receive buffer * * @param index Index of the value to peak * @param value Value of the element at index * * @return True on success, false otherwise */ bool Peak(size_t index, uint8_t &value); /* * Returns the number of bytes availabe in the read buffer * * @return number of bytes in the read buffer */ size_t BytesAvailable(); /* * Determines if the receive buffer is full * * @param Returns true if the receive buffer is full, false otherwise */ bool IsRxBufferFull(); /* * Set up UART to receive input */ void TransmitStartChars(); private: UART_HandleTypeDef* m_uart_handle; size_t m_read_offset; }; #endif /* EXTERNALPERIPHERALS_IOSTREAMUART_H_ */ <file_sep>/HabitTracker/Core/Src/HabitManager.cpp /* * HabitManager.cpp * * Created on: Apr 8, 2021 * Author: keisu */ #include "HabitManager.h" size_t HabitManager::Count() { return m_count; } size_t HabitManager::MaxCount() { return m_habits.size(); } bool HabitManager::AddHabit(Habit_t habit) { if (m_count >= m_habits.size()) { return false; } m_habits[m_count++] = habit; return true; } bool HabitManager::GetHabit(size_t index, Habit_t &habit) { if (index >= m_count) { return false; } habit = m_habits[index]; return true; } bool HabitManager::ToggleHabit(size_t index) { if (index >= m_count) { return false; } Habit_t habit = m_habits[index]; if (habit.IsComplete) { habit.IsComplete = false; habit.Streak--; }else { habit.IsComplete = true; habit.Streak++; } m_habits[index] = habit; return true; } void HabitManager::Reset() { for (Habit_t &habit : m_habits) { if (!habit.IsComplete) { habit.Streak = 0; } habit.IsComplete = false; } } cmd_status_t HabitManager::CommandCallback(uint8_t* buffer, size_t size, uint32_t code, IOStreamBase* iostream) { switch(code) { case HABIT_MANAGER_CMD_RESET: { Reset(); uint8_t msg[] = "Habit manager has been reset"; iostream->Write(msg, sizeof(msg) / sizeof(msg[0])); break; } case HABIT_MANAGER_CMD_ADD_HABIT: { if (size > 0) { Habit_t habit; for (size_t i = 0; i < size; i++) { habit.Name += (char)buffer[i]; } if (AddHabit(habit)) { uint8_t msg[] = "Habit added"; iostream->Write(msg, sizeof(msg) / sizeof(msg[0])); }else { uint8_t msg[] = "FAILED TO ADD HABIT"; iostream->Write(msg, sizeof(msg) / sizeof(msg[0])); } }else { uint8_t msg[] = "FAILED TO ADD HABIT: Empty name string"; iostream->Write(msg, sizeof(msg) / sizeof(msg[0])); } break; } default: return cmd_status_t::InvalidCode; } return cmd_status_t::Ok; } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/SSD1306.h /* * SSD1306.h * * Created on: Mar 28, 2021 * Author: keisu */ /* * SSD1306.h * * Created on: Aug 29, 2020 * Author: keisu */ #ifndef DISPLAY_SSD1306_SSD1306_H_ #define DISPLAY_SSD1306_SSD1306_H_ #include "Display.h" #include "stm32f2xx_hal.h" class SSD1306 : public Display { public: SSD1306(I2C_HandleTypeDef* i2c_handler) : m_i2c_handler(i2c_handler){}; Status_t Initialize() override; Status_t Update() override; Status_t DrawPixel(Point_t point, Color_t color) override; Status_t SetContrast(const uint8_t contrast); uint32_t GetHeight() { return HEIGHT; }; uint32_t GetWidth() { return WIDTH; }; private: static const uint32_t HEIGHT = 64; static const uint32_t WIDTH = 128; static const uint16_t I2C_ADDR = (0x3C << 1); static const uint32_t BUFFER_SIZE = WIDTH * HEIGHT / 8; // Command List enum class CMD : uint8_t { // Memory addressing modes HOR_ADDR_MODE = 0x00, SET_MEM_ADDR_MODE = 0x20, DISPLAY_ON = 0xAF, DISPLAY_OFF = 0xAE, PAGE_START_ADDR = 0xB0, COM_SCAN_DIR_63_TO_0 = 0xC8, LOW_COLUMN_ADDR_0 = 0x00, HIGH_COLUMN_ADDR_0 = 0x10, START_LINE_ADDR_0 = 0x40, SET_CONTRAST = 0x81, SEG_REMAP_0_127 = 0xA1, INVERSE_OFF = 0xA6, MULTIPLEX_RATIO_1_64 = 0xA8, UNKNOWN = 0x3F, // From reference project, not sure what this does exactly OUTPUT_FOLLOWS_RAM = 0xA4, SET_DISPLAY_OFFSET = 0xD3, SET_DISPLAY_CLOCK_RATIO = 0xD5, SET_PRECHARGE_PERIOD = 0xD9, SET_COM_PIN_HW_CONFIG = 0xDA, SET_VCOMH = 0xDB, SET_DCDC_ENABLE = 0x8D, }; uint8_t m_buffer[BUFFER_SIZE] = {0}; // Frame buffer bool m_is_enabled; I2C_HandleTypeDef* m_i2c_handler; Status_t WriteCommandByte(uint8_t byte); Status_t WriteCommand(CMD cmd); Status_t WriteCommandBytes(uint8_t* buffer, size_t buffer_size); Status_t WriteData(uint8_t* buffer, size_t buff_size); Status_t SetDisplayEnable(bool enable); }; #endif /* DISPLAY_SSD1306_SSD1306_H_ */ <file_sep>/HabitTracker/Core/Src/main.cpp /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "cmsis_os.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "Color.h" #include "SSD1306.h" #include "Display.h" #include "GraphicsEngine.h" #include "BasicFonts.h" #include "Logger.h" #include "LoggerTask.h" #include "RealTimeClock.h" #include "GUIStateHabits.h" #include "GUIStateClock.h" #include "GUIControllerTask.h" #include "HabitManager.h" #include "RotaryEncoder.h" #include "StatusLED.h" #include "Button.h" #include "IOStreamUART.h" #include "CommandParser.h" #include "BasicTimer.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ typedef StaticTask_t osStaticThreadDef_t; /* USER CODE BEGIN PTD */ typedef StaticQueue_t osStaticMessageQDef_t; typedef StaticTask_t osStaticThreadDef_t; typedef StaticEventGroup_t osStaticEventGroupDef_t; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ I2C_HandleTypeDef hi2c1; RTC_HandleTypeDef hrtc; TIM_HandleTypeDef htim4; UART_HandleTypeDef huart3; /* Definitions for defaultTask */ /* USER CODE BEGIN PV */ // Threads uint64_t loggerTaskBuffer[ 512 ]; // 64 bit to ensure 8 byte alignment osStaticThreadDef_t loggerTaskControlBlock; osThreadId_t logger_taskHandle;; osThreadAttr_t loggerTaskAttributes; uint64_t guiControllerTaskBuffer[ 4096 ]; // 64 bit to ensure 8 byte alignment osStaticThreadDef_t guiControllerControlBlock; osThreadId_t gui_controllerHandle;; osThreadAttr_t gui_controllerAttributes; // Logger Queue Configuration static const uint32_t g_logger_queueSize = 3; static const uint32_t g_logger_queueItemSize = Logger::BufferItemSize; osMessageQueueId_t g_logger_queueHandle; uint8_t g_logger_queueBuffer[g_logger_queueItemSize * g_logger_queueSize]; osStaticMessageQDef_t g_logger_queueControlBlock; osMessageQueueAttr_t g_logger_queue_attributes; // Events // Shared resources RealTimeClock rtc{&hrtc}; volatile bool resetHabitEvent = false; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_USART3_UART_Init(void); static void MX_I2C1_Init(void); static void MX_RTC_Init(void); static void MX_TIM4_Init(void); void StartDefaultTask(void *argument); /* USER CODE BEGIN PFP */ void LoggerTaskThread(void *argument); void GUIControllerTaskThread(void *argument); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ void HAL_RTC_AlarmAEventCallback (RTC_HandleTypeDef * hrtc) { resetHabitEvent = true; // Work Around: Calling osEventFlagsSet() fails when called inside this ISR } /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_USART3_UART_Init(); MX_I2C1_Init(); MX_RTC_Init(); MX_TIM4_Init(); /* USER CODE BEGIN 2 */ //Initialize HAL HAL_TIM_Encoder_Start(&htim4, TIM_CHANNEL_ALL); // Start shared resources rtc.Initialize(); /* USER CODE END 2 */ /* Init scheduler */ osKernelInitialize(); /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* USER CODE BEGIN RTOS_QUEUES */ g_logger_queue_attributes.name = "g_logger_queue"; g_logger_queue_attributes.cb_mem = &g_logger_queueControlBlock; g_logger_queue_attributes.cb_size = sizeof(g_logger_queueControlBlock); g_logger_queue_attributes.mq_mem = &g_logger_queueBuffer; g_logger_queue_attributes.mq_size = sizeof(g_logger_queueBuffer); g_logger_queueHandle = osMessageQueueNew (g_logger_queueSize, g_logger_queueItemSize, &g_logger_queue_attributes); if (g_logger_queueHandle == NULL) { StatusLED::SetErrorEvent(); } /* USER CODE END RTOS_QUEUES */ /* Create the thread(s) */ /* creation of defaultTask */ /* USER CODE BEGIN RTOS_THREADS */ loggerTaskAttributes.name = "LoggerTask"; loggerTaskAttributes.cb_mem = &loggerTaskControlBlock; loggerTaskAttributes.cb_size = sizeof(loggerTaskControlBlock); loggerTaskAttributes.stack_mem = &loggerTaskBuffer[0]; loggerTaskAttributes.stack_size = sizeof(loggerTaskBuffer); loggerTaskAttributes.priority = (osPriority_t) osPriorityNormal; logger_taskHandle = osThreadNew(LoggerTaskThread, NULL, &loggerTaskAttributes); if (g_logger_queueHandle == NULL) { StatusLED::SetErrorEvent(); } gui_controllerAttributes.name = "GUIControllerTask"; gui_controllerAttributes.cb_mem = &guiControllerControlBlock; gui_controllerAttributes.cb_size = sizeof(guiControllerControlBlock); gui_controllerAttributes.stack_mem = &guiControllerTaskBuffer[0]; gui_controllerAttributes.stack_size = sizeof(guiControllerTaskBuffer); gui_controllerAttributes.priority = (osPriority_t) osPriorityNormal; gui_controllerHandle = osThreadNew(GUIControllerTaskThread, NULL, &gui_controllerAttributes); if (gui_controllerHandle == NULL) { StatusLED::SetErrorEvent(); } /* USER CODE END RTOS_THREADS */ /* USER CODE BEGIN RTOS_EVENTS */ /* USER CODE END RTOS_EVENTS */ /* Start scheduler */ osKernelStart(); /* We should never get here as control is now taken by the scheduler */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.LSIState = RCC_LSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 13; RCC_OscInitStruct.PLL.PLLN = 195; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 5; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) { Error_Handler(); } PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { Error_Handler(); } } /** * @brief I2C1 Initialization Function * @param None * @retval None */ static void MX_I2C1_Init(void) { /* USER CODE BEGIN I2C1_Init 0 */ /* USER CODE END I2C1_Init 0 */ /* USER CODE BEGIN I2C1_Init 1 */ /* USER CODE END I2C1_Init 1 */ hi2c1.Instance = I2C1; hi2c1.Init.ClockSpeed = 400000; hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2; hi2c1.Init.OwnAddress1 = 0; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.OwnAddress2 = 0; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; if (HAL_I2C_Init(&hi2c1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN I2C1_Init 2 */ /* USER CODE END I2C1_Init 2 */ } /** * @brief RTC Initialization Function * @param None * @retval None */ static void MX_RTC_Init(void) { /* USER CODE BEGIN RTC_Init 0 */ /* USER CODE END RTC_Init 0 */ RTC_TimeTypeDef sTime = {0}; RTC_DateTypeDef sDate = {0}; RTC_AlarmTypeDef sAlarm = {0}; /* USER CODE BEGIN RTC_Init 1 */ /* USER CODE END RTC_Init 1 */ /** Initialize RTC Only */ hrtc.Instance = RTC; hrtc.Init.HourFormat = RTC_HOURFORMAT_12; hrtc.Init.AsynchPrediv = 127; hrtc.Init.SynchPrediv = 249; hrtc.Init.OutPut = RTC_OUTPUT_DISABLE; hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; if (HAL_RTC_Init(&hrtc) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN Check_RTC_BKUP */ /* USER CODE END Check_RTC_BKUP */ /** Initialize RTC and set the Time and Date */ sTime.Hours = 0x1; sTime.Minutes = 0x0; sTime.Seconds = 0x0; sTime.TimeFormat = RTC_HOURFORMAT12_AM; sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; sTime.StoreOperation = RTC_STOREOPERATION_RESET; if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK) { Error_Handler(); } sDate.WeekDay = RTC_WEEKDAY_MONDAY; sDate.Month = RTC_MONTH_JANUARY; sDate.Date = 0x1; sDate.Year = 0x0; if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BCD) != HAL_OK) { Error_Handler(); } /** Enable the Alarm A */ sAlarm.AlarmTime.Hours = 0x12; sAlarm.AlarmTime.Minutes = 0x0; sAlarm.AlarmTime.Seconds = 0x0; sAlarm.AlarmTime.TimeFormat = RTC_HOURFORMAT12_AM; sAlarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; sAlarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET; sAlarm.AlarmMask = RTC_ALARMMASK_DATEWEEKDAY; sAlarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE; sAlarm.AlarmDateWeekDay = 0x1; sAlarm.Alarm = RTC_ALARM_A; if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BCD) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN RTC_Init 2 */ /* USER CODE END RTC_Init 2 */ } /** * @brief TIM4 Initialization Function * @param None * @retval None */ static void MX_TIM4_Init(void) { /* USER CODE BEGIN TIM4_Init 0 */ /* USER CODE END TIM4_Init 0 */ TIM_Encoder_InitTypeDef sConfig = {0}; TIM_MasterConfigTypeDef sMasterConfig = {0}; /* USER CODE BEGIN TIM4_Init 1 */ /* USER CODE END TIM4_Init 1 */ htim4.Instance = TIM4; htim4.Init.Prescaler = 0; htim4.Init.CounterMode = TIM_COUNTERMODE_UP; htim4.Init.Period = 65535; htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; sConfig.EncoderMode = TIM_ENCODERMODE_TI1; sConfig.IC1Polarity = TIM_ICPOLARITY_RISING; sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI; sConfig.IC1Prescaler = TIM_ICPSC_DIV1; sConfig.IC1Filter = 0; sConfig.IC2Polarity = TIM_ICPOLARITY_RISING; sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI; sConfig.IC2Prescaler = TIM_ICPSC_DIV1; sConfig.IC2Filter = 0; if (HAL_TIM_Encoder_Init(&htim4, &sConfig) != HAL_OK) { Error_Handler(); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN TIM4_Init 2 */ /* USER CODE END TIM4_Init 2 */ } /** * @brief USART3 Initialization Function * @param None * @retval None */ static void MX_USART3_UART_Init(void) { /* USER CODE BEGIN USART3_Init 0 */ /* USER CODE END USART3_Init 0 */ /* USER CODE BEGIN USART3_Init 1 */ /* USER CODE END USART3_Init 1 */ huart3.Instance = USART3; huart3.Init.BaudRate = 115200; huart3.Init.WordLength = UART_WORDLENGTH_8B; huart3.Init.StopBits = UART_STOPBITS_1; huart3.Init.Parity = UART_PARITY_NONE; huart3.Init.Mode = UART_MODE_TX_RX; huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart3.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&huart3) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN USART3_Init 2 */ /* USER CODE END USART3_Init 2 */ } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOB, LD1_Pin|LD3_Pin|LD2_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(USB_PowerSwitchOn_GPIO_Port, USB_PowerSwitchOn_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : USER_Btn_Pin */ GPIO_InitStruct.Pin = USER_Btn_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(USER_Btn_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : RMII_MDC_Pin RMII_RXD0_Pin RMII_RXD1_Pin */ GPIO_InitStruct.Pin = RMII_MDC_Pin|RMII_RXD0_Pin|RMII_RXD1_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /*Configure GPIO pins : RMII_REF_CLK_Pin RMII_MDIO_Pin RMII_CRS_DV_Pin */ GPIO_InitStruct.Pin = RMII_REF_CLK_Pin|RMII_MDIO_Pin|RMII_CRS_DV_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pins : LD1_Pin LD3_Pin LD2_Pin */ GPIO_InitStruct.Pin = LD1_Pin|LD3_Pin|LD2_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pin : BUTTON_SELECT_Pin */ GPIO_InitStruct.Pin = BUTTON_SELECT_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(BUTTON_SELECT_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : RMII_TXD1_Pin */ GPIO_InitStruct.Pin = RMII_TXD1_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(RMII_TXD1_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : USB_PowerSwitchOn_Pin */ GPIO_InitStruct.Pin = USB_PowerSwitchOn_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(USB_PowerSwitchOn_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : USB_OverCurrent_Pin */ GPIO_InitStruct.Pin = USB_OverCurrent_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(USB_OverCurrent_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : USB_SOF_Pin USB_ID_Pin USB_DM_Pin USB_DP_Pin */ GPIO_InitStruct.Pin = USB_SOF_Pin|USB_ID_Pin|USB_DM_Pin|USB_DP_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pin : USB_VBUS_Pin */ GPIO_InitStruct.Pin = USB_VBUS_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(USB_VBUS_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : RMII_TX_EN_Pin RMII_TXD0_Pin */ GPIO_InitStruct.Pin = RMII_TX_EN_Pin|RMII_TXD0_Pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF11_ETH; HAL_GPIO_Init(GPIOG, &GPIO_InitStruct); } /* USER CODE BEGIN 4 */ void GUIControllerTaskThread(void *argument) { SSD1306 ssd1306{&hi2c1}; GraphicsEngine gEngine{&ssd1306}; GUIControllerTask controller{}; HabitManager habit_manager{}; gEngine.Initialize(); // Setup GUI States GUIStateHabits state_habits{&gEngine, &controller, &rtc, &habit_manager}; controller.AddState(&state_habits, GUIState::HABITS); controller.SetState(GUIState::HABITS); // Setup user inputs Button select_btn{}; RotaryEncoder encoder{(uint16_t)TIM4->CNT}; const uint32_t TIMER_DIRECTION_MASK = 0b10000; IOStreamUART uart_stream{&huart3}; uart_stream.TransmitStartChars(); uint8_t end_of_line = '\r'; uint8_t msg_invalid_cmd[] = "Invalid command"; // Register commands CommandParser parser{}; parser.RegisterModule(Module_t::HabitManager, &habit_manager); Command_t cmd; cmd.Code = HABIT_MANAGER_CMD_RESET; cmd.Name = "resethabits"; cmd.Module = Module_t::HabitManager; cmd.Help = "Reset all habits"; parser.RegisterCommand(cmd); cmd.Code = HABIT_MANAGER_CMD_ADD_HABIT; cmd.Name = "addhabit"; cmd.Module = Module_t::HabitManager; cmd.Help = "Add habit"; parser.RegisterCommand(cmd); // Setup refresh timer BasicTimer gui_refresh_timer{}; gui_refresh_timer.Start(osKernelGetTickCount(), controller.RefreshInterval); for(;;) { if (gui_refresh_timer.HasExpired(osKernelGetTickCount())) { controller.UIDraw(); gui_refresh_timer.Start(osKernelGetTickCount(), controller.RefreshInterval); } if (resetHabitEvent) { habit_manager.Reset(); controller.UIDraw(); resetHabitEvent = false; } if (select_btn.IsPressed(HAL_GPIO_ReadPin(BUTTON_SELECT_GPIO_Port, BUTTON_SELECT_Pin) == GPIO_PIN_SET)) { controller.UISelect(); } if (encoder.HasMoved(TIM4->CNT)) { if (TIM4->CR1 & TIMER_DIRECTION_MASK) { controller.UILeft(); }else { controller.UIRight(); } } size_t bytes_available = 0; if ((bytes_available = uart_stream.BytesAvailable())) { uint8_t last_char = 0; if ((uart_stream.Peak(bytes_available - 1, last_char) && last_char == end_of_line) || uart_stream.IsRxBufferFull()) { if (false == parser.Execute(&uart_stream)) { uart_stream.Write(msg_invalid_cmd, sizeof(msg_invalid_cmd) / sizeof(msg_invalid_cmd[0])); } uart_stream.TransmitStartChars(); } } osDelay(10); } } void LoggerTaskThread(void *argument) { LoggerTask logger_task{}; logger_task.Run(); } /* USER CODE END 4 */ /* USER CODE BEGIN Header_StartDefaultTask */ /** * @brief Function implementing the defaultTask thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartDefaultTask */ void StartDefaultTask(void *argument) { /* USER CODE BEGIN 5 */ /* Infinite loop */ for(;;) { osDelay(1); } /* USER CODE END 5 */ } /** * @brief Period elapsed callback in non blocking mode * @note This function is called when TIM1 interrupt took place, inside * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment * a global variable "uwTick" used as application time base. * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { /* USER CODE BEGIN Callback 0 */ /* USER CODE END Callback 0 */ if (htim->Instance == TIM1) { HAL_IncTick(); } /* USER CODE BEGIN Callback 1 */ /* USER CODE END Callback 1 */ } /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Display.h /* * Display.h * * Created on: Mar 28, 2021 * Author: keisu * * Description: Interface for displays */ #ifndef DISPLAY_H_ #define DISPLAY_H_ #include "Color.h" #include "Point.h" #include "Status.h" class Display { public: virtual Status_t Initialize() { return Status_t::OK; }; virtual Status_t DrawPixel(Point_t point, Color_t color) { return Status_t::OK; }; virtual uint32_t GetHeight() { return 0; }; virtual uint32_t GetWidth() { return 0; }; virtual Status_t Update() { return Status_t::OK; }; }; #endif /* DISPLAY_H_ */ <file_sep>/HabitTrackerUnitTests/src/IOStreamMockTests.cpp /* * IOStreamMockTests.cpp * * Created on: Apr 17, 2021 * Author: keisu */ #include "IOStreamMock.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(IOStreamMockTests) { IOStreamMock *iostream; void setup() { iostream = new IOStreamMock(); } void teardown() { delete iostream; } }; TEST(IOStreamMockTests, write_to_read_buffer) { const size_t buffer_size = 20; uint8_t readbuffer[buffer_size] = "testvalue"; uint8_t receivebuffer[buffer_size] = {0}; iostream->WriteReadBuffer(readbuffer, 10); LONGS_EQUAL(10, iostream->Read(receivebuffer, buffer_size)); MEMCMP_EQUAL(readbuffer, receivebuffer, 10); } <file_sep>/HabitTracker/Core/Src/GUIControllerTask.h /* * GUI.h * * Created on: Mar 28, 2021 * Author: keisu */ #ifndef SRC_GUICONTROLLER_H_ #define SRC_GUICONTROLLER_H_ #include "GUIStateBase.h" #include <array> enum class GUIState : uint32_t { Clock, SET_TIME, HABITS }; class GUIControllerTask { public: GUIControllerTask(); bool AddState(GUIStateBase *state_ptr, GUIState state_enum); void SetState(GUIState new_state); void Initialize(); void Run(); void UIDraw(); void UILeft() { m_curr_state->UILeft(); }; void UIRight() { m_curr_state->UIRight(); }; void UISelect() { m_curr_state->UISelect(); }; uint32_t RefreshInterval{UINT32_MAX}; private: static const size_t MAX_NUM_STATES = 32; GUIStateBase *m_curr_state = nullptr; std::array<GUIStateBase*, MAX_NUM_STATES> m_states; }; #endif /* SRC_GUICONTROLLER_H_ */ <file_sep>/HabitTrackerUnitTests/src/CommandParserTest.cpp /* * CommandControllerTest.cpp * * Created on: Apr 17, 2021 * Author: keisu */ #include "CommandParser.h" #include "IOStreamMock.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" class MockCommandCallable : public CommandCallableBase { public: cmd_status_t CommandCallback(uint8_t* buffer, size_t size, uint32_t code, IOStreamBase* iostream) override { mock().actualCall("test_callback").withParameter("size", size).withParameter("code", code); return cmd_status_t::Ok; } }; TEST_GROUP(CommandParserTests) { CommandParser *parser; MockCommandCallable* mockcallable; IOStreamMock* iostream; void setup() { parser = new CommandParser(); mockcallable = new MockCommandCallable(); iostream = new IOStreamMock(); } void teardown() { delete parser; delete mockcallable; delete iostream; mock().clear(); } size_t leading_whitespace(std::string str) { size_t count = 0; std::string::const_iterator iter = str.begin(); while (*iter == ' ' && iter != str.end()) { iter++; count++; } return count; } }; TEST(CommandParserTests, register_commands) { Command_t command; command.Code = 1; command.Help = "Help string"; command.Module = Module_t::HabitManager; command.Name = "testcmd"; // Try to register a command with a module was not registered CHECK_FALSE(parser->RegisterCommand(command)); CHECK(parser->RegisterModule(Module_t::HabitManager, mockcallable)); // Should register now that the module has been registered CHECK(parser->RegisterCommand(command)); } TEST(CommandParserTests, execute_basic_command) { // Register Module CHECK(parser->RegisterModule(Module_t::HabitManager, mockcallable)); // Register command and execute it with the string Command_t command; command.Code = 1; command.Help = "Help string"; command.Module = Module_t::HabitManager; command.Name = "testcmd"; CHECK(parser->RegisterCommand(command)); mock().expectOneCall("test_callback").withParameter("size", 0).withParameter("code", command.Code); iostream->WriteReadBuffer((uint8_t*)command.Name.c_str(), command.Name.size()); CHECK(parser->Execute(iostream)); // Register and execute second command command.Code = 2; command.Help = "Help string2"; command.Module = Module_t::HabitManager; command.Name = "testcmd2"; CHECK(parser->RegisterCommand(command)); mock().expectOneCall("test_callback").withParameter("size", 0).withParameter("code", command.Code); iostream->WriteReadBuffer((uint8_t*)command.Name.c_str(), command.Name.size()); CHECK(parser->Execute(iostream)); // Try to execute a command that wasn't registered command.Name = "testcmd3"; iostream->WriteReadBuffer((uint8_t*)command.Name.c_str(), command.Name.size()); CHECK_FALSE(parser->Execute(iostream)); mock().checkExpectations(); } TEST(CommandParserTests, exectute_with_extra_data_in_stream) { // Register Module CHECK(parser->RegisterModule(Module_t::HabitManager, mockcallable)); // Register command and execute it with the string Command_t command; command.Code = 1; command.Help = "Help string"; command.Module = Module_t::HabitManager; command.Name = "testcmd"; CHECK(parser->RegisterCommand(command)); // Append extra data to the command std::string extra_string = " randomdata"; std::string iostream_str = command.Name + extra_string; iostream->WriteReadBuffer((uint8_t*)iostream_str.c_str(), iostream_str.size()); mock().expectOneCall("test_callback").withParameter("size", iostream_str.size() - command.Name.size() - leading_whitespace(extra_string)).withParameter("code", command.Code); CHECK(parser->Execute(iostream)); mock().checkExpectations(); } TEST(CommandParserTests, register_too_many_commands) { Command_t command; command.Code = 1; command.Help = "Help string"; command.Module = Module_t::HabitManager; command.Name = "testcmd"; CHECK(parser->RegisterModule(Module_t::HabitManager, mockcallable)); for (size_t i = 0; i < parser->MaxCommands(); i++) { CHECK(parser->RegisterCommand(command)); } CHECK_FALSE(parser->RegisterCommand(command)); } <file_sep>/HabitTracker/Core/Src/BasicTimer.h /* * BasicTimer.h * * Created on: Apr 25, 2021 * Author: keisu */ #ifndef SRC_BASICTIMER_H_ #define SRC_BASICTIMER_H_ #include <cstdint> class BasicTimer { public: /* * Starts timer * * @param initial_tick Tick count at the start of the timer */ void Start(uint32_t inital_tick, uint32_t interval); /* * Determines if timer has expired * * @param uint32_t tick Current system tick value * * @return True if timer has expired, false otherwise */ bool HasExpired(uint32_t tick); private: uint32_t m_initial_tick{0}; uint32_t m_interval{0}; }; #endif /* SRC_BASICTIMER_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/GraphicsUtilities.h /* * GraphicsUtilities.h * * Created on: Mar 29, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_GRAPHICSUTILITIES_H_ #define EXTERNALPERIPHERALS_GRAPHICSUTILITIES_H_ #include <cstddef> #include <string> class GraphicsUtilities { public: static size_t SplitString(std::string input, std::string output[], size_t output_size, uint32_t font_width, uint32_t screen_width); static size_t WrapText(std::string input, std::string output[], size_t output_size, uint32_t font_width, uint32_t screen_width); }; #endif /* EXTERNALPERIPHERALS_GRAPHICSUTILITIES_H_ */ <file_sep>/HabitTracker/Core/Src/Logger.h /* * Logger.h * * Created on: Mar 31, 2021 * Author: keisu */ #ifndef LOGGER_H_ #define LOGGER_H_ #include <string> #include <sstream> #include "cmsis_os.h" enum class LoggingLevel { Error, Debug }; class Logger { public: Logger(LoggingLevel level, std::string module) : m_level(level), m_module(module) {}; virtual ~Logger(); std::ostringstream& Get(); const static size_t BufferItemSize{256}; protected: std::ostringstream os; private: // Private to hide these Logger(const Logger&); Logger& operator =(const Logger&); LoggingLevel m_level; std::string m_module; }; #endif <file_sep>/HabitTracker/Core/Src/CommandCallableBase.h /* * CommandCallable.h * * Created on: Apr 17, 2021 * Author: keisu */ #ifndef SRC_COMMANDCALLABLE_H_ #define SRC_COMMANDCALLABLE_H_ #include "IOStreamBase.h" #include <cstddef> #include <cstdint> enum class cmd_status_t { Ok, InvalidCode }; class CommandCallableBase { protected: virtual ~CommandCallableBase() {}; public: virtual cmd_status_t CommandCallback(uint8_t* buffer, size_t size, uint32_t code, IOStreamBase* iostream) {return cmd_status_t::Ok; }; }; #endif /* SRC_COMMANDCALLABLE_H_ */ <file_sep>/HabitTracker/Core/Src/StatusLED.h /* * StatusLED.h * * Created on: Apr 8, 2021 * Author: keisu */ #ifndef SRC_STATUSLED_H_ #define SRC_STATUSLED_H_ class StatusLED { public: static void SetErrorEvent(); static void ClearErrorEvent(); }; #endif /* SRC_STATUSLED_H_ */ <file_sep>/HabitTrackerUnitTests/src/TimeTests.cpp /* * RealTimeClockUtilitiesTest.cpp * * Created on: Apr 4, 2021 * Author: keisu * * Description: Tests for RealTimeClockUtiltis */ #include "Time.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(TimeTests) { }; TEST(TimeTests, default_values) { Time_t time; LONGS_EQUAL(12, time.Hours); LONGS_EQUAL(0, time.Minutes); LONGS_EQUAL(0, time.Seconds); CHECK(TimeFormat_t::Format_12_AM == time.TimeFormat); CHECK(DayLightSaving_t::None == time.DayLightSaving); CHECK(StoreOperation_t::Reset == time.StoreOperation); } TEST(TimeTests, to_string_test_no_colon_toggle) { Time_t time; STRCMP_EQUAL("12:00AM", time.ToString().c_str()); time.Hours = 4; time.Minutes = 32; time.TimeFormat = TimeFormat_t::Format_12_PM; STRCMP_EQUAL("04:32PM", time.ToString().c_str()); } TEST(TimeTests, to_string_test_colon_toggle) { Time_t time; STRCMP_EQUAL("12:00AM", time.ToString(true).c_str()); time.Seconds = 1; STRCMP_EQUAL("12 00AM", time.ToString(true).c_str()); } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Point.h /* * Point_t.h * * Created on: Mar 28, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_POINT_H_ #define EXTERNALPERIPHERALS_POINT_H_ struct Point_t { Point_t(uint32_t x_val = 0, uint32_t y_val = 0) : X(x_val), Y(y_val) {}; uint32_t X{0}; uint32_t Y{0}; }; #endif /* EXTERNALPERIPHERALS_POINT_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/GraphicsUtilities.cpp /* * GraphicsUtilities.cpp * * Created on: Mar 29, 2021 * Author: keisu */ #include "GraphicsUtilities.h" size_t GraphicsUtilities::SplitString(std::string input, std::string output[], size_t output_size, uint32_t font_width, uint32_t screen_width) { std::string current_word = ""; size_t current_word_index = 0; for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) { if (*iter == '\n') { // Add current string of characters as a word if (current_word.length() > 0) { if (current_word_index < output_size) { output[current_word_index++] = current_word; current_word = ""; } } // Add the newline as its own "word" if (current_word_index < output_size) { output[current_word_index++] = "\n"; } }else if (*iter == ' ') { // Add current string of characters as a word if (current_word.length() > 0) { if (current_word_index < output_size) { output[current_word_index++] = current_word; current_word = ""; } }else { // Throw away space character if current word length is empty; } }else { // Check if adding character will make word longer than width of screen if ((current_word.length() + 1) * font_width < screen_width) {// If not add character current_word += *iter; }else {// If yes, cut off word and continue the word onto the next string if (current_word_index < output_size) { output[current_word_index++] = current_word; current_word = *iter; } } } } // Add any remaining characters as a word if (current_word.length() > 0) { if (current_word_index < output_size) { output[current_word_index++] = current_word; current_word = ""; } } return current_word_index; } size_t GraphicsUtilities::WrapText(std::string input, std::string output[], size_t output_size, uint32_t font_width, uint32_t screen_width) { const size_t max_words = 100; std::string words[max_words]; size_t current_line_index = 0; std::string current_line = ""; uint32_t max_characters_per_line = screen_width / font_width; size_t num_words = SplitString(input, words, max_words, font_width, screen_width); if ( num_words > max_words) { return 0; } for (size_t i = 0; i < num_words; i++) { size_t line_length = current_line.length() + words[i].length(); if (words[i] == "\n") {// New line if (current_line.length() > 0) {// End current line as it is and move on to next line output[current_line_index++] = current_line; current_line = ""; }else {// Create empty line output[current_line_index++] = ""; } } else if (line_length == max_characters_per_line && current_line.length() == 0) {// Current line is empty and next word is equal to the maximum number of characters per line output[current_line_index++] = words[i]; } else if ((1 + line_length) > max_characters_per_line) // the + 1 is for the space {// space + next word is too long output[current_line_index++] = current_line; current_line = ""; // Kind of a hack but decrement i so that the word that would have // went out of bounds can be drawn in the next line i--; }else {// Enough room is available for a space + the next word if (current_line.length() > 0) // do not add a space if first word in line { current_line += " "; } current_line += words[i]; } } if (current_line.length() > 0) { output[current_line_index++] = current_line; current_line = ""; } return current_line_index; } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Button.cpp /* * Button.cpp * * Created on: Apr 14, 2021 * Author: keisu */ #include "Button.h" bool Button::IsPressed(bool gpioIsSet) { m_state = (m_state << 1 ) | (gpioIsSet ? 1 : 0) | 0xe000; if(m_state==0xf000) { return true; }else { return false; } } <file_sep>/HabitTracker/Core/Src/StatusLED.cpp /* * StatusLED.cpp * * Created on: Apr 8, 2021 * Author: keisu */ #include "StatusLED.h" #include "main.h" void StatusLED::SetErrorEvent() { HAL_GPIO_WritePin(LD3_GPIO_Port, LD3_Pin, GPIO_PIN_SET); } void StatusLED::ClearErrorEvent() { HAL_GPIO_WritePin(LD3_GPIO_Port, LD3_Pin, GPIO_PIN_RESET); } <file_sep>/HabitTrackerUnitTests/src/ButtonTests.cpp /* * ButtonTests.cpp * * Created on: Apr 14, 2021 * Author: keisu */ #include "Button.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(ButtonTests) { Button *button; const uint32_t consecutive_resets_required = 12; void setup() { button = new Button(); } void teardown() { delete button; } }; TEST(ButtonTests, button_pressed) { for (uint32_t i = 0; i < consecutive_resets_required - 1; i++) { CHECK_FALSE(button->IsPressed(false)); } CHECK(button->IsPressed(false)); } TEST(ButtonTests, button_pressed_twice) { for (uint32_t i = 0; i < consecutive_resets_required - 1; i++) { CHECK_FALSE(button->IsPressed(false)); } CHECK(button->IsPressed(false)); CHECK_FALSE(button->IsPressed(true)); for (uint32_t i = 0; i < consecutive_resets_required - 1; i++) { CHECK_FALSE(button->IsPressed(false)); } CHECK(button->IsPressed(false)); } <file_sep>/HabitTracker/Core/Src/HabitManager.h /* * HabitManager.h * * Created on: Apr 8, 2021 * Author: keisu */ #ifndef SRC_HABITMANAGER_H_ #define SRC_HABITMANAGER_H_ #include "Habit.h" #include "CommandCallableBase.h" #include <array> // Command Codes #define HABIT_MANAGER_CMD_RESET 0 #define HABIT_MANAGER_CMD_ADD_HABIT 1 class HabitManager : public CommandCallableBase { public: bool AddHabit(Habit_t habit); bool GetHabit(size_t index, Habit_t &habit); bool ToggleHabit(size_t index); void Reset(); size_t Count(); size_t MaxCount(); cmd_status_t CommandCallback(uint8_t* buffer, size_t size, uint32_t code, IOStreamBase* iostream); private: std::array<Habit_t, 10> m_habits; size_t m_count{0}; }; #endif <file_sep>/HabitTrackerUnitTests/src/GraphicsUtilitiesTests.cpp /* * GraphicsUtilitiesTests.cpp * * Created on: Mar 29, 2021 * Author: keisu */ #include "GraphicsUtilities.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(GraphicsUtilitiesTests) { // Virtual LCD display and font configuration const uint32_t screen_width = 128; const uint32_t screen_height = 64; const uint32_t font_height = 10; const uint32_t font_width = 7; }; TEST(GraphicsUtilitiesTests, split_string) { std::string test = " this is a sample. "; const size_t max_words = 100; std::string words[max_words]; LONGS_EQUAL(4, GraphicsUtilities::SplitString(test, words, max_words, font_width, screen_width)); STRCMP_EQUAL("this", words[0].c_str()); STRCMP_EQUAL("is", words[1].c_str()); STRCMP_EQUAL("a", words[2].c_str()); STRCMP_EQUAL("sample.", words[3].c_str()); } TEST(GraphicsUtilitiesTests, split_string_overflow_buffer) { std::string test = "this is a sample."; const size_t max_words = 3; std::string words[max_words]; LONGS_EQUAL(max_words, GraphicsUtilities::SplitString(test, words, max_words, font_width, screen_width)); } TEST(GraphicsUtilitiesTests, split_string_long_word) { std::string test = "thisisareallylongword short"; const size_t max_words = 3; std::string words[max_words]; LONGS_EQUAL(3, GraphicsUtilities::SplitString(test, words, max_words, font_width, screen_width)); STRCMP_EQUAL("thisisareallylongw", words[0].c_str()); STRCMP_EQUAL("ord", words[1].c_str()); STRCMP_EQUAL("short", words[2].c_str()); } TEST(GraphicsUtilitiesTests, wrap_text_single_line) { std::string test = "this is a sample"; const uint32_t num_lines = screen_height / font_height; std::string lines[num_lines]; GraphicsUtilities::WrapText(test, lines, num_lines, font_width, screen_width); STRCMP_EQUAL("this is a sample", lines[0].c_str()); } TEST(GraphicsUtilitiesTests, wrap_text_basic) { std::string test = "this is a sampleee text string that will get wrapped."; const uint32_t num_lines = screen_height / font_height; std::string lines[num_lines]; LONGS_EQUAL(3, GraphicsUtilities::WrapText(test, lines, num_lines, font_width, screen_width)); STRCMP_EQUAL("this is a sampleee", lines[0].c_str()); STRCMP_EQUAL("text string that", lines[1].c_str()); STRCMP_EQUAL("will get wrapped.", lines[2].c_str()); } TEST(GraphicsUtilitiesTests, wrap_text_word_longer_than_line) { std::string test = "this is a sampletextstringstring that will get wrapped."; const uint32_t num_lines = screen_height / font_height; std::string lines[num_lines]; LONGS_EQUAL(4, GraphicsUtilities::WrapText(test, lines, num_lines, font_width, screen_width)); STRCMP_EQUAL("this is a", lines[0].c_str()); STRCMP_EQUAL("sampletextstringst", lines[1].c_str()); STRCMP_EQUAL("ring that will get", lines[2].c_str()); STRCMP_EQUAL("wrapped.", lines[3].c_str()); } TEST(GraphicsUtilitiesTests, wrap_text_word_wraps_two_lines) { std::string test = "this is a samplestringsamplestringsamplestring"; const uint32_t num_lines = screen_height / font_height; std::string lines[num_lines]; LONGS_EQUAL(3, GraphicsUtilities::WrapText(test, lines, num_lines, font_width, screen_width)); STRCMP_EQUAL("this is a", lines[0].c_str()); STRCMP_EQUAL("samplestringsample", lines[1].c_str()); STRCMP_EQUAL("stringsamplestring", lines[2].c_str()); } TEST(GraphicsUtilitiesTests, split_text_new_line) { std::string test = "this is\n a\n sample"; const size_t max_words = 6; size_t current_word = 0; std::string words[max_words]; LONGS_EQUAL(6, GraphicsUtilities::SplitString(test, words, max_words, font_width, screen_width)); STRCMP_EQUAL("this", words[current_word++].c_str()); STRCMP_EQUAL("is", words[current_word++].c_str()); STRCMP_EQUAL("\n", words[current_word++].c_str()); STRCMP_EQUAL("a", words[current_word++].c_str()); STRCMP_EQUAL("\n", words[current_word++].c_str()); STRCMP_EQUAL("sample", words[current_word++].c_str()); } TEST(GraphicsUtilitiesTests, wrap_text_new_line) { std::string test = "this is a\n sample \nstring"; const uint32_t num_lines = screen_height / font_height; std::string lines[num_lines]; LONGS_EQUAL(3, GraphicsUtilities::WrapText(test, lines, num_lines, font_width, screen_width)); STRCMP_EQUAL("this is a", lines[0].c_str()); STRCMP_EQUAL("sample", lines[1].c_str()); STRCMP_EQUAL("string", lines[2].c_str()); } TEST(GraphicsUtilitiesTests, wrap_text_two_new_lines_backtoback) { std::string test = "this is a\n\nsample string"; const uint32_t num_lines = screen_height / font_height; std::string lines[num_lines]; LONGS_EQUAL(3, GraphicsUtilities::WrapText(test, lines, num_lines, font_width, screen_width)); STRCMP_EQUAL("this is a", lines[0].c_str()); STRCMP_EQUAL("", lines[1].c_str()); STRCMP_EQUAL("sample string", lines[2].c_str()); } <file_sep>/HabitTracker/Core/Src/LoggerTask.cpp /* * LoggerTask.cpp * * Created on: Apr 1, 2021 * Author: keisu */ #include "LoggerTask.h" #include "stm32f2xx_hal.h" #include "Logger.h" #include "cmsis_os.h" #include <cstring> extern osMessageQueueId_t g_logger_queueHandle; void LoggerTask::Run() { osStatus_t status; uint8_t buffer[Logger::BufferItemSize] = {0}; for (;;) { status = osMessageQueueGet(g_logger_queueHandle, buffer, NULL, 0U); if (status == osOK) { size_t i = 0; char c = buffer[i]; while (c) { ITM_SendChar(c); c = buffer[++i]; } memset(buffer, 0, Logger::BufferItemSize); } } } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/SSD1306.cpp /* * SSD1306.cpp * * Created on: Mar 28, 2021 * Author: keisu */ /* * SSD1306.cpp * * Created on: Aug 29, 2020 * Author: keisu * Data Frame (aka. _buffer array) pixel layout * * <------ 128 Pixel Wide -------> * First 128 Bytes = first 8 rows * Each Byte is one pixel wide * ------------------------------- ^ * B B|B | * Y Y|Y | 8 Pixels high per byte * T Y|T | * E E|E | * 1 <... 1|0 | * 2 #|# | * 7 #|# | * # #|# | * ------------------------------- V * B * Y * T * E * <... 1 * 2 * 8 * # * --------------------------------- */ // #include "SSD1306.h" #include <string> // Module name used for logging static const std::string MODULE_NAME = "SSD1306: "; #define CHECK_HAL_STATUS(status_to_check)({ if (status_to_check != HAL_OK) return Status_t::ERROR; else return Status_t::OK; }) Status_t SSD1306::Initialize() { Status_t status = Status_t::OK; status |= this->WriteCommand(CMD::SET_MEM_ADDR_MODE); status |= this->WriteCommand(CMD::PAGE_START_ADDR); status |= this->WriteCommand(CMD::COM_SCAN_DIR_63_TO_0); status |= this->WriteCommand(CMD::LOW_COLUMN_ADDR_0); status |= this->WriteCommand(CMD::HIGH_COLUMN_ADDR_0); status |= this->WriteCommand(CMD::START_LINE_ADDR_0); status |= this->SetContrast(0xFF); status |= this->WriteCommand(CMD::INVERSE_OFF); status |= this->WriteCommand(CMD::MULTIPLEX_RATIO_1_64); status |= this->WriteCommand(CMD::UNKNOWN); status |= this->WriteCommand(CMD::OUTPUT_FOLLOWS_RAM); status |= this->WriteCommand(CMD::SET_DISPLAY_OFFSET); status |= this->WriteCommandByte(0x00); status |= this->WriteCommand(CMD::SET_DISPLAY_CLOCK_RATIO); status |= this->WriteCommandByte(0xF0); status |= this->WriteCommand(CMD::SET_PRECHARGE_PERIOD); status |= this->WriteCommandByte(0x22); status |= this->WriteCommand(CMD::SET_COM_PIN_HW_CONFIG); status |= this->WriteCommandByte(0x12); status |= this->WriteCommand(CMD::SET_VCOMH); status |= this->WriteCommandByte(0x20); status |= this->WriteCommand(CMD::SET_DCDC_ENABLE); status |= this->WriteCommandByte(0x14); status |= this->SetDisplayEnable(true); return status; } Status_t SSD1306::WriteCommandByte(uint8_t byte) { HAL_StatusTypeDef status = HAL_I2C_Mem_Write(m_i2c_handler, I2C_ADDR, 0x00, 1, &byte, 1, HAL_MAX_DELAY); CHECK_HAL_STATUS(status); } Status_t SSD1306::WriteCommandBytes(uint8_t* buffer, size_t buffer_size) { HAL_StatusTypeDef status = HAL_I2C_Mem_Write(m_i2c_handler, I2C_ADDR, 0x40, 1, buffer, buffer_size, HAL_MAX_DELAY); CHECK_HAL_STATUS(status); } Status_t SSD1306::WriteCommand(CMD cmd) { return WriteCommandByte((uint8_t)cmd); } Status_t SSD1306::SetDisplayEnable(bool enable) { CMD value; Status_t status = Status_t::OK; if (enable) { value = CMD::DISPLAY_ON; } else { value = CMD::DISPLAY_OFF; } status = this->WriteCommand(value); m_is_enabled = enable; return status; } Status_t SSD1306::SetContrast(const uint8_t value) { Status_t status = Status_t::OK; status |= WriteCommand(CMD::SET_CONTRAST); status |= WriteCommandByte(value); return status; } Status_t SSD1306::Update() { Status_t status = Status_t::OK; for(uint8_t i = 0; i < HEIGHT/8; i++) { status |= this->WriteCommandByte(0xB0 + i); // Set the current RAM page address. status |= this->WriteCommandByte(0x00); status |= this->WriteCommandByte(0x10); status |= this->WriteCommandBytes(&m_buffer[WIDTH*i], WIDTH); } return status; } Status_t SSD1306::DrawPixel(Point_t point, Color_t color) { if(point.X >= WIDTH || point.Y >= HEIGHT) { // Don't write outside the buffer return Status_t::OK; } if(color == BasicColors::Black) { m_buffer[point.X + (point.Y / 8) * WIDTH] &= ~(1 << (point.Y % 8)); } else { m_buffer[point.X + (point.Y / 8) * WIDTH] |= 1 << (point.Y % 8); } return Status_t::OK; } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/RealTimeClock.cpp /* * RealTimeClock.cpp * * Created on: Apr 4, 2021 * Author: keisu * * Note: Cannot call logger since the logger depends on this */ #include "RealTimeClock.h" static const std::string MODULE_NAME = "RealTimeClock"; void RealTimeClock::Initialize() { if (m_handle == nullptr) { return; } RTC_DateTypeDef date_structure; RTC_TimeTypeDef time_structure; // Configure Date date_structure.Year = 0; date_structure.Month = RTC_MONTH_FEBRUARY; date_structure.Date = 1; date_structure.WeekDay = RTC_WEEKDAY_TUESDAY; HAL_RTC_SetDate(m_handle ,&date_structure , RTC_FORMAT_BIN); // Configure Time time_structure.Hours = 11; time_structure.Minutes = 59; time_structure.Seconds = 55; time_structure.TimeFormat = RTC_HOURFORMAT12_PM; time_structure.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; time_structure.StoreOperation = RTC_STOREOPERATION_RESET; HAL_RTC_SetTime(m_handle, &time_structure, RTC_FORMAT_BIN); } Time_t RealTimeClock::GetTime() { RTC_TimeTypeDef time; RTC_DateTypeDef date; HAL_RTC_GetTime(m_handle, &time, RTC_FORMAT_BIN); HAL_RTC_GetDate(m_handle, &date, RTC_FORMAT_BIN); // Must be called after getting time to unlock higher order calander shadow registers Time_t ret_time; ret_time.Hours = time.Hours; ret_time.Minutes = time.Minutes; ret_time.Seconds = time.Seconds; switch(time.TimeFormat) { case RTC_HOURFORMAT12_AM: ret_time.TimeFormat = TimeFormat_t::Format_12_AM; break; case RTC_HOURFORMAT12_PM: ret_time.TimeFormat = TimeFormat_t::Format_12_PM; break; } switch(time.DayLightSaving) { case RTC_DAYLIGHTSAVING_SUB1H: ret_time.DayLightSaving = DayLightSaving_t::Sub_1H; break; case RTC_DAYLIGHTSAVING_ADD1H: ret_time.DayLightSaving = DayLightSaving_t::Add_1H; break; case RTC_DAYLIGHTSAVING_NONE: ret_time.DayLightSaving = DayLightSaving_t::None; break; } switch(time.StoreOperation) { case RTC_STOREOPERATION_RESET: ret_time.StoreOperation = StoreOperation_t::Reset; break; case RTC_STOREOPERATION_SET: ret_time.StoreOperation = StoreOperation_t::Set; break; } return ret_time; } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Time.cpp /* * Time.cpp * * Created on: Apr 7, 2021 * Author: keisu */ #include "Time.h" std::string Time_t::ToString(bool toggle_colon) { std::string ret_str = ""; if (Hours < 10) { ret_str += "0"; } ret_str += std::to_string(Hours); if (toggle_colon && Seconds % 2 == 1) { ret_str += " "; } else { ret_str += ":"; } if (Minutes < 10) { ret_str += "0"; } ret_str += std::to_string(Minutes); if (TimeFormat == TimeFormat_t::Format_12_AM) { ret_str += "AM"; } else { ret_str += "PM"; } return ret_str; } <file_sep>/HabitTracker/Core/Src/BasicTimer.cpp /* * BasicTimer.cpp * * Created on: Apr 25, 2021 * Author: keisu */ #include "BasicTimer.h" void BasicTimer::Start(uint32_t initial_tick, uint32_t interval) { m_initial_tick = initial_tick; m_interval = interval; } bool BasicTimer::HasExpired(uint32_t tick) { return tick - m_initial_tick >= m_interval; } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Date.h /* * Date.h * * Created on: Apr 4, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_DATE_H_ #define EXTERNALPERIPHERALS_DATE_H_ enum class WeekDay_t { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; enum class Month_t { Janurary, February, March, April, May, June, July, August, September, October, November, December }; struct Date_t { uint32_t Year; uint8_t Day; WeekDay_t Weekday; Month_t Month; }; #endif /* EXTERNALPERIPHERALS_DATE_H_ */ <file_sep>/HabitTracker/Core/Src/Habit.cpp /* * Habit.cpp * * Created on: Apr 8, 2021 * Author: keisu */ <file_sep>/HabitTracker/Core/Src/CommandParser.cpp /* * CommandParser.cpp * * Created on: Apr 17, 2021 * Author: keisu */ #include "CommandParser.h" #include <cstring> #include <algorithm> CommandParser::CommandParser() { m_module_callbacks.fill(nullptr); } bool CommandParser::RegisterModule(Module_t module, CommandCallableBase* callable) { size_t module_index = static_cast<size_t>(module); m_module_callbacks[module_index] = callable; return true; } bool CommandParser::RegisterCommand(Command_t command) { // Verify that callback is registered if (m_module_callbacks[static_cast<size_t>(command.Module)] == nullptr || m_num_commands >= m_commands.size()) { return false; } m_commands[m_num_commands++] = command; return true; } bool CommandParser::Execute(IOStreamBase* iostream) { const size_t buffer_size = 128; uint8_t read_buffer[buffer_size] = {0}; size_t byte_read = iostream->Read(read_buffer, buffer_size); std::string cmd_str = ""; size_t cmd_index = 0; // Extract command from buffer while (cmd_index < byte_read && read_buffer[cmd_index] != static_cast<uint8_t>(' ') && read_buffer[cmd_index] != 0 && read_buffer[cmd_index] != '\r') { cmd_str += read_buffer[cmd_index++]; } if (cmd_str == "help") { PrintHelp(iostream); return true; }else { // Find start of command values while (cmd_index < byte_read && (read_buffer[cmd_index] == static_cast<uint8_t>(' ') || read_buffer[cmd_index] == static_cast<uint8_t>('\r'))) { cmd_index++; } // Search command list for given command for (size_t i = 0; i < m_num_commands;i++) { Command_t cmd = m_commands[i]; if (cmd_str == cmd.Name) { size_t module_index = static_cast<size_t>(cmd.Module); m_module_callbacks[module_index]->CommandCallback(read_buffer + cmd_index, byte_read - cmd_index, cmd.Code, iostream); return true; } } return false; } } void CommandParser::PrintHelp(IOStreamBase* iostream) { const size_t write_buffer_size = 128; uint8_t write_buffer[write_buffer_size] = {0}; for (size_t i = 0; i < m_num_commands;i++) { Command_t cmd = m_commands[i]; size_t j = 0; for (; j < cmd.Name.size() && j < write_buffer_size - 5; j++) { write_buffer[j] = cmd.Name[j]; } write_buffer[j++] = ' '; write_buffer[j++] = '-'; write_buffer[j++] = ' '; for (size_t k = 0; k < cmd.Help.size() && j < write_buffer_size - 2; j++) { write_buffer[j] = cmd.Help[k++]; } write_buffer[j++] = '\r'; write_buffer[j++] = '\n'; iostream->Write(write_buffer, j); std::fill(write_buffer, write_buffer + write_buffer_size, 0); } } size_t CommandParser::MaxCommands() { return m_commands.size(); } <file_sep>/HabitTracker/Core/Src/GUIStateClock.h /* * GUIStateClock.h * * Created on: Mar 30, 2021 * Author: keisu */ #ifndef SRC_GUISTATECLOCK_H_ #define SRC_GUISTATECLOCK_H_ #include "GUIStateBase.h" class GUIStateClock : public GUIStateBase { public: GUIStateClock(GraphicsEngine* gfx_engine, GUIControllerTask* controller) : GUIStateBase(gfx_engine, controller) {}; void UIDraw() override; void OnLoaded() override; private: void DrawTime(); }; #endif /* SRC_GUISTATECLOCK_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/BasicFonts.h /* * BasicFont.h * * Created on: Mar 28, 2021 * Author: keisu */ #ifndef EXTERNALPERIPHERALS_BASICFONTS_H_ #define EXTERNALPERIPHERALS_BASICFONTS_H_ #include <cstdint> struct BasicFont{ const uint8_t FontWidth; /*!< Font width in pixels */ uint8_t FontHeight; /*!< Font height in pixels */ const uint16_t *data; /*!< Pointer to data font data array */ }; #define SSD1306_INCLUDE_FONT_11x18 #define SSD1306_INCLUDE_FONT_7x10 #define SSD1306_INCLUDE_FONT_16x26 #ifdef SSD1306_INCLUDE_FONT_6x8 extern BasicFont Font_6x8; #endif #ifdef SSD1306_INCLUDE_FONT_7x10 extern BasicFont Font_7x10; #endif #ifdef SSD1306_INCLUDE_FONT_11x18 extern BasicFont Font_11x18; #endif #ifdef SSD1306_INCLUDE_FONT_16x26 extern BasicFont Font_16x26; #endif #endif /* EXTERNALPERIPHERALS_BASICFONTS_H_ */ <file_sep>/HabitTrackerUnitTests/src/HabitManagerTests.cpp /* * HabitManagerTests.cpp * * Created on: Apr 8, 2021 * Author: keisu */ #include "HabitManager.h" // Includes CppUtest headers last since they can potentially override functions/keywords used before ('new' for example) #include "CppUTest/TestHarness.h" #include "CppUTestExt/MockSupport.h" TEST_GROUP(HabitManagerTests) { HabitManager* manager; void setup() { manager = new HabitManager(); } void teardown() { delete manager; } }; TEST(HabitManagerTests, count_added_habit) { Habit_t test_habit; LONGS_EQUAL(0,manager->Count()); manager->AddHabit(test_habit); LONGS_EQUAL(1,manager->Count()); manager->AddHabit(test_habit); LONGS_EQUAL(2,manager->Count()); } TEST(HabitManagerTests, added_too_many) { Habit_t test_habit; for (size_t i = 0; i < manager->MaxCount(); i++) { CHECK(manager->AddHabit(test_habit)); } CHECK_FALSE(manager->AddHabit(test_habit)); } TEST(HabitManagerTests, get_habit) { Habit_t test_habit; test_habit.Name = "test name"; test_habit.IsComplete = true; test_habit.Streak = 123; Habit_t habit; manager->AddHabit(test_habit); CHECK(manager->GetHabit(0, habit)); STRCMP_EQUAL("test name", habit.Name.c_str()); CHECK(habit.IsComplete); LONGS_EQUAL(123, habit.Streak); test_habit.Name = "test name2"; test_habit.IsComplete = false; test_habit.Streak = 321; manager->AddHabit(test_habit); CHECK(manager->GetHabit(1, habit)); STRCMP_EQUAL("test name2", habit.Name.c_str()); CHECK_FALSE(habit.IsComplete); LONGS_EQUAL(321, habit.Streak); } TEST(HabitManagerTests, get_habit_out_of_range) { Habit_t habit; CHECK_FALSE(manager->GetHabit(0, habit)); } TEST(HabitManagerTests, toggle_habit_completion) { Habit_t test_habit; test_habit.Name = "test name"; test_habit.IsComplete = true; test_habit.Streak = 123; manager->AddHabit(test_habit); manager->ToggleHabit(0); manager->GetHabit(0, test_habit); CHECK_FALSE(test_habit.IsComplete); LONGS_EQUAL(122, test_habit.Streak); manager->ToggleHabit(0); manager->GetHabit(0, test_habit); CHECK(test_habit.IsComplete); LONGS_EQUAL(123, test_habit.Streak); } TEST(HabitManagerTests, set_all_incomplete) { Habit_t test_habit; test_habit.Name = "test name"; test_habit.IsComplete = true; test_habit.Streak = 123; manager->AddHabit(test_habit); test_habit.IsComplete = false; test_habit.Streak = 23; manager->AddHabit(test_habit); test_habit.IsComplete = true; test_habit.Streak = 321; manager->AddHabit(test_habit); manager->Reset(); for (size_t i = 0; i < manager->Count(); i++) { Habit_t habit; manager->GetHabit(i, habit); CHECK_FALSE(habit.IsComplete); } manager->GetHabit(0, test_habit); LONGS_EQUAL(123, test_habit.Streak); manager->GetHabit(1, test_habit); LONGS_EQUAL(0, test_habit.Streak); manager->GetHabit(2, test_habit); LONGS_EQUAL(321, test_habit.Streak); } <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Button.h /* * Button.h * * Created on: Apr 14, 2021 * Author: keisu * * For button that is normally HIGH and goes LOW when pressed */ #ifndef EXTERNALPERIPHERALS_BUTTON_H_ #define EXTERNALPERIPHERALS_BUTTON_H #include <cstdint> class Button { public: bool IsPressed(bool gpioIsSet); private: uint16_t m_state{UINT16_MAX}; }; #endif /* EXTERNALPERIPHERALS_BUTTON_H_ */ <file_sep>/HabitTracker/Core/Src/CommandParser.h /* * CommandParser.h * * Created on: Apr 17, 2021 * Author: keisu */ #ifndef SRC_COMMANDPARSER_H_ #define SRC_COMMANDPARSER_H_ #include "IOStreamBase.h" #include "CommandCallableBase.h" #include <functional> #include <string> #include <array> enum class Module_t { HabitManager }; struct Command_t { std::string Name; std::string Help; uint32_t Code; Module_t Module; }; class CommandParser { public: CommandParser(); /* * Reads streams and executes command if a registered command matches the stream input * * @param iostream IOStream to read from and write to * * @return True on success, false otherwise */ bool Execute(IOStreamBase* iostream); // commant parser sends down io stream to executing function which an write to io stream /* * Registers a module * * @param module Module to register * @param callback Callback associated with module * * @return true on success, false otherwise */ bool RegisterModule(Module_t module, CommandCallableBase* callable); /* * Registers a command. Module needs to be registered before registering command assocated with module. * * @param command Command to register * * @return true on success, false otherwise */ bool RegisterCommand(Command_t command); size_t MaxCommands(); private: std::array<CommandCallableBase*, 10> m_module_callbacks; std::array<Command_t, 32> m_commands; size_t m_num_commands{0}; /* * Prints out help text to the io stream */ void PrintHelp(IOStreamBase* iostream); }; #endif /* SRC_COMMANDPARSER_H_ */ <file_sep>/HabitTracker/Drivers/ExternalPeripherals/Color.cpp #include "Color.h" const Color_t BasicColors::Black{0, 0, 0}; const Color_t BasicColors::White{255, 255, 255};
acbafce826387e794f2125d7d0f198ee16de1945
[ "C", "C++" ]
58
C++
ksk-t/HabitTracker
f73dc9cadab897362d0db11a189e07758d1ead35
39cc351d1b01281ec647fd7ea7d071d3264d6557
refs/heads/master
<repo_name>meta-boy/Yedivision<file_sep>/ye.py from flask import Flask,render_template,request from firebase import firebase import os import requests from bs4 import BeautifulSoup app=Flask(__name__,static_url_path='/static') @app.route ("/") def index(): #full_filename=os.path.join(app.config['yefinal.png'],'static/') return render_template("ye.html") @app.route("/assignment",methods=["POST"]) def assignment(): firebase1=firebase.FirebaseApplication('https://assignments-c2657.firebaseio.com/') result=firebase1.get('feature',None) posts=[] for i in result: posts.append([result[i]]) return render_template("assignment.html",posts=posts) @app.route("/question_bank",methods=["POST"]) def question_bank(): firebase1=firebase.FirebaseApplication('https://assignments-c2657.firebaseio.com/') result=firebase1.get('paper',None) posts=[] for i in result: posts.append([result[i]]) return render_template("question_bank.html",posts=posts) @app.route("/study_material",methods=["POST"]) def study_material(): firebase1=firebase.FirebaseApplication('https://assignments-c2657.firebaseio.com/') result=firebase1.get('studymaterial',None) posts=[] for i in result: posts.append([result[i]]) return render_template("study_material.html",posts=posts) @app.route ("/news_ann",methods=["POST"]) def news_ann(): posts=[] d={} for i in range(1,4): r=requests.get("http://www.rait.ac.in/page/"+str(i)+"/") c=r.content soup=BeautifulSoup(c,"html.parser") alls=soup.find_all("div",{"class":"portfolio-thumbnail-context"}) for ii in range(len(alls)): d["text"]=alls[ii].find("a").text d["links"]=alls[ii].find("a").get('href') posts.append(d) d={} return render_template("news_ann.html",posts=posts) if __name__=="__main__": app.debug=True app.run()
937a2bc185760aec7f4aba2619499310a7c8bb58
[ "Python" ]
1
Python
meta-boy/Yedivision
39ae425c6f550be08326c2fccee4c633c70961e0
2fc3aee5a2996d693b9fa43162d757775b02c2c8
refs/heads/master
<repo_name>owpk/select-and-translate<file_sep>/install.sh #!/usr/bin/bash sudo cp ./tools/* /usr/local/bin/<file_sep>/tools/gclip #!/usr/bin/bash /mnt/c/Windows/system32/WindowsPowerShell/v1.0/powershell.exe Get-Clipboard <file_sep>/tools/translator #!/usr/bin/bash data=$(wget -U "Mozilla/5.0" -qO - "http://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=$1&dt=t&q=$(gclip | tr -d '.' | sed "s/[\"'<>]//g")") echo $data | sed 's/\[\[\[\"//' | cut -d \" -f 1 <file_sep>/tools/notif #!/usr/bin/bash data=$(translator $1) /mnt/c/Windows/system32/WindowsPowerShell/v1.0/powershell.exe New-BurntToastNotification -Text "Translator", '"'"$data"'"' echo $data | pclip <file_sep>/tools/pclip #!/usr/bin/bash /mnt/c/Windows/system32/clip.exe <file_sep>/README.md ### Translate selected text and send it to windows notification center <img src="https://github.com/vzvz4/dotfiles/blob/master/transl.gif"/> ### Installation Guide 1. Make sure you have PowerShell installed - You can check it, go to C:/Windows/System32/WindowsPowerShell/v1.0 and search for powershell.exe 2. Make sure you have windows sub system linux (wsl) installed - You can check it, go to C:/Windows/System32/ and search for wsl.exe, see [installation guide](https://docs.microsoft.com/en-en/windows/wsl/install-win10) if needed. 3. To send translated text to notify you have to install [BurntToast](https://github.com/Windos/BurntToast), should work fine just follow instructions. If some issues occures try to do this: - Dont forget "unblock" the zip file before extracting the contents. - Open powershell and run this command "Import-Module BurntToast" 4. Download and unzip https://github.com/vzvz4/select-and-translate/releases/tag/0.0.2 or ``` $ git clone https://github.com/vzvz4/select-and-translate ``` - run wsl.exe, go to the folder you just downloaded and copy "gclip", "pclip", "translator" and "notif" to /usr/local/bin/ directory - Step by step: ```bash $ cd /mnt/c/'YOUR_PATH_TO_DOWNLOADS'/select-and-translate/tools/ $ cp * /usr/local/bin/ ``` ### Usage Guide Copy any text you want to translate and double click to run-en.vbs, notification with translated text should pop up. ### Additions - Copy "run-\*.vbs" file (for example run-en.vbs), instead of "en" in "lang = en" paste any language you want to translate the selected text. - Also you can bind execution of the tranlsation script to specific keys, i found this solution https://www.youtube.com/watch?v=tPcw-gDDVwo but it works a bit slow <img src="https://github.com/vzvz4/dotfiles/blob/master/transl-hotkey.gif"/> - Note that translated text copy to system clipboard so you can paste translation to where ever you want
9585951e2383a63c67b5a508bdc6f55e896bac80
[ "Markdown", "Shell" ]
6
Shell
owpk/select-and-translate
27164a2fd07eaae26da8e16ba63b8824f2184000
ddfe1f042614affda69631af189c46238eb42f7e
refs/heads/master
<file_sep>package com.oncology.service; import java.util.Collection; import com.oncology.model.UserProtocol; public interface UserProtocolService { Collection<UserProtocol> findAll(); UserProtocol findOne(Long id); UserProtocol create(UserProtocol userProtocol); UserProtocol update(UserProtocol userProtocol); void delete(Long id); } <file_sep>package com.oncology.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.oncology.model.UserProtocol; @Repository public interface UserProtocolRepository extends JpaRepository<UserProtocol, Long> { }
8012a96da065b0f13bf5564092bff19675b86050
[ "Java" ]
2
Java
vinchauhan/LeukemiaHelperApp
786c860c50ac73f7d82611b37cd692c9aa643ec3
c8418c00268cc6282e2ef0ebb7b3f65b50e9741b
refs/heads/master
<repo_name>shuye00123/ConcurrentStudy<file_sep>/src/com/concurrent/study/java/SCMSW/PhilosopherCondition.java package com.concurrent.study.java.SCMSW; import java.util.Random; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * Created by shuye on 2016/12/20. * * week1 2 1 * * 公平锁是FIFO队列,适合严格控制执行顺序的情况,非公平锁是抢占式的,吞吐量更大,有可能有的进程一直获取不到锁 * ReentrantReadWriteLock是读写锁,其中的WriteLock是与ReentrantLock相似的独占锁,而ReadLock是共享锁,他们共用一个队列,一个状态码 其中高16位是共享锁,低16位是独占锁,适用于读多于写而且读不改变值的情况 * 虚假唤醒是await的线程非条件下被唤醒,判断条件用while不用if可以避免虚假唤醒 * AtomicIntegerFielfUpdater可以用一个Object和一个Integer属性名初始化,为对象的那个属性进行原子操作 * * * * 读取多的情况用交替锁,少不用 */ public class PhilosopherCondition extends Thread { private boolean eating; private PhilosopherCondition left; private PhilosopherCondition right; private ReentrantLock table; private Condition condition; private Random random; public PhilosopherCondition(ReentrantLock table, String name) { setName(name); eating = false; this.table = table; condition = table.newCondition(); random = new Random(); } public void setLeft(PhilosopherCondition left){ this.left = left; } public void setRight(PhilosopherCondition right) { this.right = right; } public void run() { try { while (true){ think(); eat(); } }catch (InterruptedException e){ } } private void think() throws InterruptedException { table.lock(); try { System.out.println("Philosopher"+Thread.currentThread().getName()+" is thinking"); eating = false; left.condition.signal(); right.condition.signal(); }finally { table.unlock(); } Thread.sleep(random.nextInt(1000)); } private void eat() throws InterruptedException { table.lock(); try { while (left.eating||right.eating){ condition.await(); } System.out.println("Philosopher"+Thread.currentThread().getName()+" is eating"); eating = true; }finally { table.unlock(); } Thread.sleep(random.nextInt(1000)); } public static void main(String[] args) { ReentrantLock table = new ReentrantLock(); PhilosopherCondition p1 = new PhilosopherCondition(table,"1"); PhilosopherCondition p2 = new PhilosopherCondition(table,"2"); PhilosopherCondition p3 = new PhilosopherCondition(table,"3"); PhilosopherCondition p4 = new PhilosopherCondition(table,"4"); PhilosopherCondition p5 = new PhilosopherCondition(table,"5"); p1.setLeft(p5); p1.setRight(p2); p2.setLeft(p1); p2.setRight(p3); p3.setLeft(p2); p3.setRight(p4); p4.setLeft(p3); p4.setRight(p5); p5.setLeft(p4); p5.setRight(p1); p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); } } <file_sep>/src/com/concurrent/study/java/Lock/LockVSSynchronization.java package com.concurrent.study.java.Lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by shuye on 2017/3/30. */ public class LockVSSynchronization { private Lock lock = new ReentrantLock(false); private Integer i = 0; /** java 1.8 * now i is 20000, spend 4992756 ns t8 * now i is 20000, spend 5043442 ns t10 * now i is 200000, spend 30899516 ns t10 * now i is 2000000, spend 113391942 ns t10 * now i is 2400000, spend 119293765 ns t12 * java 1.7 * now i is 20000, spend 3795982 ns t8 */ private synchronized void doIncBySyn() { i++; } /** java 1.8 * now i is 20000, spend 9220482 ns t8 * now i is 20000, spend 9122756 ns t10 * now i is 200000, spend 13841298 ns t10 * now i is 2000000, spend 70595429 ns t10 * now i is 2400000, spend 82051202 ns t12 * java 1.7 * now i is 20000, spend 4151879 ns t8 */ private void doIncByLock() { lock.lock(); try { i++; } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public class lockAndIncrement implements Runnable { @Override public void run() { for (int n = 0; n < 200000; n++) { doIncBySyn(); //doIncByLock(); } } } public void doLockIncrement() throws InterruptedException { Thread thread1 = new Thread(new lockAndIncrement()); Thread thread2 = new Thread(new lockAndIncrement()); Thread thread3 = new Thread(new lockAndIncrement()); Thread thread4 = new Thread(new lockAndIncrement()); Thread thread5 = new Thread(new lockAndIncrement()); Thread thread6 = new Thread(new lockAndIncrement()); Thread thread7 = new Thread(new lockAndIncrement()); Thread thread8 = new Thread(new lockAndIncrement()); Thread thread9 = new Thread(new lockAndIncrement()); Thread thread10 = new Thread(new lockAndIncrement()); Thread thread11 = new Thread(new lockAndIncrement()); Thread thread12 = new Thread(new lockAndIncrement()); long starttime = System.nanoTime(); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); thread6.start(); thread7.start(); thread8.start(); thread9.start(); thread10.start(); thread11.start(); thread12.start(); thread1.join(); thread2.join(); thread3.join(); thread4.join(); thread5.join(); thread6.join(); thread7.join(); thread8.join(); thread9.join(); thread10.join(); thread11.join(); thread12.join(); long endtime = System.nanoTime(); System.out.printf("now i is %d, spend %d ns", i, endtime - starttime); } public static void main(String[] args) throws InterruptedException { LockVSSynchronization lockVSSynchronization = new LockVSSynchronization(); lockVSSynchronization.doLockIncrement(); } } <file_sep>/src/com/concurrent/study/java/SCMSW/disorder.java package com.concurrent.study.java.SCMSW; import java.util.concurrent.TimeUnit; /** * Created by shuye on 2016/12/19. * week1 1 * * 突然发现CSDN博客被封了我去他吗找时间自己弄个博客 * * 七周七并发模型第一天 * 本节介绍了如何创建线程,并用java对象的内置锁实现互斥。还介绍了线程与锁模型带来的三个主要危害--竞态条件、死锁和内存可见性,并讨论了一些帮助我们避免危害的准则: * 对共享变量的所有访问都需要同步化; * 读线程和写线程都需要同步化; * 按照约定的全局顺序来获取多把锁; * 持有锁的时间应尽可能短 * * java线程之间通信是通过共享内存,静态域实例域和数组元素存储在堆内存中,堆内存线程间共享 * 一致性内存模型 > JMM > CPU内存模型 * * 线程安全的单例模式? 不一定,volatile? * * 反模式, 是指用来解决问题的带有共同性的不良方法。它们已经经过研究并分类,以防止日后重蹈覆辙,并能在研发尚未投产时辨认出来。 */ public class disorder { static class Work1 implements Runnable{ @Override public void run() { i = 1; j = 2; System.out.println(j); System.out.println(i); } } static class Work2 implements Runnable{ @Override public void run() { i = 2; j = 1; System.out.println(j); System.out.println(i); } } static int i = 0; static int j = 0; public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Work1()); Thread thread2 = new Thread(new Work1()); thread1.start(); thread2.start(); } } <file_sep>/src/com/concurrent/study/java/Lock/MyLock.java package com.concurrent.study.java.Lock; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.Condition; /** * Created by shuye on 2016/12/18. */ public class MyLock { private static class Sync extends AbstractQueuedSynchronizer{ protected boolean isHeldExclusively() { return getState() == 1; } public boolean tryAcquire(int acquire) { assert acquire == 1; if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } public boolean tryRelease(int releases) { assert releases == 1; if (getState() == 0) { throw new IllegalMonitorStateException(); } setExclusiveOwnerThread(null); setState(0); return true; } Condition newCondition() { return new ConditionObject(); } } private final Sync sync = new Sync(); public void lock() { sync.acquire(1); } public boolean tryLock() { return sync.tryAcquire(1); } public void unlock() { sync.release(1); } public boolean tryUnlock() { return sync.tryRelease(1); } public boolean isLocked() { return sync.isHeldExclusively(); } } <file_sep>/src/com/concurrent/study/java/SCMSW/PhilosopherSyn.java package com.concurrent.study.java.SCMSW; import java.util.Random; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * Created by shuye on 2016/12/20. * * week1 2 2 */ public class PhilosopherSyn extends Thread { private boolean eating; private PhilosopherSyn left; private PhilosopherSyn right; private Object table; private Random random; public PhilosopherSyn(Object table, String name){ setName(name); eating = false; this.table = table; random = new Random(); } public void setLeft(PhilosopherSyn left) { this.left = left; } public void setRight(PhilosopherSyn right) { this.right = right; } public void run() { try { while (true){ think(); eat(); } }catch (InterruptedException e){ } } private void think() throws InterruptedException { synchronized (table){ System.out.println("Philosopher"+Thread.currentThread().getName()+" is thinking"); eating = false; table.notify(); } Thread.sleep(1000); } private void eat() throws InterruptedException { synchronized (table){ while (left.eating||right.eating){ table.wait(); } System.out.println("Philosopher"+Thread.currentThread().getName()+" is eating"); eating = true; } Thread.sleep(1000); } public static void main(String[] args) { ReentrantLock table = new ReentrantLock(); PhilosopherSyn p1 = new PhilosopherSyn(table,"1"); PhilosopherSyn p2 = new PhilosopherSyn(table,"2"); PhilosopherSyn p3 = new PhilosopherSyn(table,"3"); PhilosopherSyn p4 = new PhilosopherSyn(table,"4"); PhilosopherSyn p5 = new PhilosopherSyn(table,"5"); p1.setLeft(p5); p1.setRight(p2); p2.setLeft(p1); p2.setRight(p3); p3.setLeft(p2); p3.setRight(p4); p4.setLeft(p3); p4.setRight(p5); p5.setLeft(p4); p5.setRight(p1); p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); } } <file_sep>/src/com/concurrent/study/java/Lock/RWLock.java package com.concurrent.study.java.Lock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Created by Administrator on 2016/12/8. */ public class RWLock { private static Map param; private volatile static int p = 0; private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(false); static class ReadTask implements Runnable{ @Override public void run() { while (true) { lock.readLock().lock(); try { String get = String.valueOf(param.get(p)); if (get==null||get.equals("null"))break; System.out.println("time "+p++); System.out.println(Thread.currentThread().getName()+" get "+get); TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.readLock().unlock(); } } } } static class WriteTask implements Runnable{ @Override public void run() { int i = 0; while (true) { lock.writeLock().lock(); try { param.put(i++,System.currentTimeMillis()); System.out.println(Thread.currentThread().getName()+" put "+i); TimeUnit.MILLISECONDS.sleep(10); if (i == 100)break; } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.writeLock().unlock(); } } } } public static void main(String[] args) { param = new HashMap<String, String>(); Thread wt = new Thread(new WriteTask()); wt.start(); Thread rt1 = new Thread(new ReadTask()); rt1.start(); Thread rt2 = new Thread(new ReadTask()); rt2.start(); } } <file_sep>/src/com/concurrent/study/java/HashtableAndCHM.java package com.concurrent.study.java; import java.util.Hashtable; import java.util.concurrent.ConcurrentHashMap; /** * Created by shuye on 2016/12/10. */ public class HashtableAndCHM { private static Hashtable<String, String> ht; private static ConcurrentHashMap<String, String> chm; static class htRunner implements Runnable{ @Override public void run() { for (int i = 0; i <1000000; i++) { ht.get("key" + i); } } } static class chmRunner implements Runnable{ @Override public void run() { for (int i = 0; i <1000000; i++) { chm.get("key"+i); } } } public static void main(String[] args) { ht = new Hashtable<String, String>(); chm = new ConcurrentHashMap<String, String>(); long t1 = System.nanoTime(); for (int i = 0; i <1000000; i++) { ht.put("key"+i,"value"+i); } long t2 = System.nanoTime(); for (int i = 0; i <1000000; i++) { chm.put("key"+i,"value"+i); } long t3 = System.nanoTime(); for (int i = 0;i<1000000; i++){ ht.get("key"+i); } long t4 = System.nanoTime(); for (int i = 0;i<1000000; i++){ chm.get("key" + i); } long t5 = System.nanoTime(); System.out.println("hashtable put value spend "+ (t2 - t1)); System.out.println("concurrrentHashMap put value spend "+ (t3 - t2)); System.out.println("hashtable get value spend "+ (t4 - t3)); System.out.println("concurrrentHashMap get value spend "+ (t5 - t4)); long t6 = System.nanoTime(); for (int i = 0; i<20;i++){ Thread ht = new Thread(new htRunner()); ht.start(); } long t7 = System.nanoTime(); for (int i = 0; i<20;i++){ Thread chm = new Thread(new chmRunner()); chm.start(); } long t8 = System.nanoTime(); System.out.println("20 thread get hashtable value spend "+ (t7 - t6)); System.out.println("20 thread get concurrrentHashMap value spend "+ (t8 - t7)); long t9 = System.nanoTime(); for (int i = 0; i<200;i++){ Thread ht = new Thread(new htRunner()); ht.start(); } long t10 = System.nanoTime(); for (int i = 0; i<200;i++){ Thread chm = new Thread(new chmRunner()); chm.start(); } long t11 = System.nanoTime(); System.out.println("200 thread get hashtable value spend "+ (t10 - t9)); System.out.println("200 thread get concurrrentHashMap value spend "+ (t11 - t10)); } } <file_sep>/src/com/concurrent/study/java/ThreadPool/CachedThreadPoolTest.java package com.concurrent.study.java.ThreadPool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Created by shuye on 2016/12/18. * CachedThreadPool corePoolSoze为0,maximumPoolSize为Integer.MAX_VALUE * 线程池中线程等待生存时间为60s * * 线程池的好处 * 1.降低线程创建销毁造成的损耗 * 2.提高响应速度,不需要创建线程 * 3.提高线程的可管理性 * 4.防止服务器过载 */ public class CachedThreadPoolTest { static class Worker implements Runnable{ @Override public void run() { try { TimeUnit.MILLISECONDS.sleep(10); System.out.println(Thread.currentThread().getName()+" is running"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i<10; i++){ executorService.execute(new Worker()); } TimeUnit.SECONDS.sleep(10); for (int i = 0; i<10; i++){ executorService.execute(new Worker()); } TimeUnit.SECONDS.sleep(60); for (int i = 0; i<10; i++){ executorService.execute(new Worker()); } executorService.shutdown(); } } <file_sep>/src/com/concurrent/study/java/Queue/ArrayBlockingQueue.java package com.concurrent.study.java.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * Created by shuye on 2016/12/11. */ public class ArrayBlockingQueue { enum WorkUnit{ RUN, STOP } static class Worker implements Runnable{ BlockingQueue<WorkUnit> in; BlockingQueue<WorkUnit> out; public Worker(BlockingQueue<WorkUnit> in, BlockingQueue<WorkUnit> out) { this.in = in; this.out = out; } @Override public void run() { while (true) { try { WorkUnit w = in.take(); if (w == WorkUnit.RUN) { for (int i = 0; i<10; i++) { System.out.println("sub thread run"+i); TimeUnit.MICROSECONDS.sleep(1); } } out.put(w); if (w == WorkUnit.STOP)break; } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { BlockingQueue<WorkUnit> in = new java.util.concurrent.ArrayBlockingQueue<>(1); BlockingQueue<WorkUnit> out = new java.util.concurrent.ArrayBlockingQueue<>(1); Thread thread = new Thread(new Worker(in ,out)); thread.start(); try { for (int i = 0; i<5;i++) { System.out.println(i); in.put(WorkUnit.RUN); out.take(); for (int j = 0; j< 10; j++) { System.out.println("main thread" + j); TimeUnit.MICROSECONDS.sleep(1); } } in.put(WorkUnit.STOP); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>/src/com/concurrent/study/java/ForkJoin/FutureTest.java package com.concurrent.study.java.ForkJoin; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; /** * Created by shuye on 2016/12/25. */ public class FutureTest { public static void main(String[] args) throws ExecutionException, InterruptedException { for (int i = 0; i<10; i++) { subTask task = new subTask(); FutureTask<String> futureTask1 = new FutureTask<String>(task); new Thread(futureTask1).start(); System.out.println(futureTask1.get()); mainRunner runner = new mainRunner(); FutureTask<String> futureTask2 = new FutureTask<String>(runner, "main thread is finished"); new Thread(futureTask2).start(); System.out.println(futureTask2.get()); } } static class subTask implements Callable<String> { @Override public String call() throws Exception { for (int i = 0; i<10; i++) { System.out.println("sub thread:" + i); } return "sub thread is finished"; } } static class mainRunner implements Runnable{ @Override public void run() { for (int i = 0; i<10; i++) { System.out.println("main thread:" + i); } } } } <file_sep>/src/com/concurrent/study/java/ForkJoin/ForkJoinTaskTest.java package com.concurrent.study.java.ForkJoin; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.RecursiveTask; /** * Created by shuye on 2016/12/25. */ public class ForkJoinTaskTest { public static void main(String[] args) throws ExecutionException, InterruptedException { ForkJoinPool pool = new ForkJoinPool(); CountTask task = new CountTask(1,10); Future<Integer> result = pool.submit(task); System.out.println("sum result is "+result.get()); } static class CountTask extends RecursiveTask<Integer> { private static int splitesize = 2; private int start, end; public CountTask(int start, int end) { this.start = start; this.end = end; } @Override protected Integer compute() { int sum = 0; boolean canCompute = (end - start)<=splitesize; if (canCompute){ for(int i = start; i<=end; i++){ sum+=i; } }else { int middle = (start+end)/2; CountTask first = new CountTask(start, middle); CountTask second = new CountTask(middle+1, end); first.fork(); second.fork(); int firstResult = first.join(); int secondResult = second.join(); sum = firstResult+secondResult; } return sum; } } } <file_sep>/src/com/concurrent/study/java/CountDownLatchTest.java package com.concurrent.study.java; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Created by Administrator on 2016/12/16. */ public class CountDownLatchTest { static class Worker implements Runnable{ private CountDownLatch countDownLatch; public Worker(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { try { System.out.println(Thread.currentThread().getName()+" is running!"); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }finally { countDownLatch.countDown(); } } } public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(4); for (int i = 0; i<4; i++) { Thread thread = new Thread(new Worker(countDownLatch)); thread.start(); } countDownLatch.await(); System.out.println("is all done!"); } }
7125f3cdcdf0dac40d46925f5f887a60ff63b07b
[ "Java" ]
12
Java
shuye00123/ConcurrentStudy
2b35c6d92e923b0d8c7305be7147f76a6ed7b85b
ecdb12389ad655d1d84a68dc2106902f7703a18d
refs/heads/master
<repo_name>agungatd/h8-p0-w4<file_sep>/excerxise-17-week-4.js function totalDigitRekursif(angka) { // you can only write your code here! var numStr = ''+angka // for (var i =0; i < num.length; i++) {} if (numStr.length === 0) { return 0 } return parseInt(numStr[0]) + totalDigitRekursif(numStr.slice(1)) // console.log(typeof num) } // TEST CASES console.log(totalDigitRekursif(512)); // 8 console.log(totalDigitRekursif(1542)); // 12 console.log(totalDigitRekursif(5)); // 5 console.log(totalDigitRekursif(21)); // 3 console.log(totalDigitRekursif(11111)); // 5 /** * buat jadi string agar mudah dipisahkan tiap elemen * pisahkan elemen menggunakan loop/recursive * tiap element diubah menjadi number again * recursive the calculation */<file_sep>/excerxise-12-week-4.js function shoppingTime(memberId, money) { var res='' var barang=[['Sepatu Stacattu',1500000],['Baju Zoro',500000],['Baju H&N',250000],['Sweater Uniklooh',175000],['Casing Handphone',50000]] var listPurchased=[] var uangSisa=0 var barangBeli='' var obj = {} // you can only write your code here! if (memberId === '' || memberId === undefined ) { res = 'Mohon maaf, toko X hanya berlaku untuk member saja' } else if (money < 50000) { res = 'Mohon maaf, uang tidak cukup' } else { obj.memberId = memberId obj.money = money //for list purchased obj.listPurchased = [] //money change if ( money >= barang[0][1]) { money -= barang[0][1] obj.listPurchased.push(barang[0][0]) } if (money >= barang[1][1]) { money -= barang[1][1] obj.listPurchased.push(barang[1][0]) } if (money >= barang[2][1]) { money -= barang[2][1] obj.listPurchased.push(barang[2][0]) } if (money >= barang[3][1]) { money -= barang[3][1] obj.listPurchased.push(barang[3][0]) } if (money >= barang[4][1]) { money -= barang[4][1] obj.listPurchased.push(barang[4][0]) } obj.changeMoney = money res = obj } return res } // TEST CASES console.log(shoppingTime('1820RzKrnWn08', 2475000)); //{ memberId: '1820RzKrnWn08', // money: 2475000, // listPurchased: // [ '<NAME>', // '<NAME>', // '<NAME>', // '<NAME>', // 'Casing Handphone' ], // changeMoney: 0 } console.log(shoppingTime('82Ku8Ma742', 170000)); //{ memberId: '82Ku8Ma742', // money: 170000, // listPurchased: // [ 'Casing Handphone' ], // changeMoney: 120000 } console.log(shoppingTime('', 2475000)); //Mohon maaf, toko X hanya berlaku untuk member saja console.log(shoppingTime('234JdhweRxa53', 15000)); //Mohon maaf, uang tidak cukup console.log(shoppingTime()); ////Mohon maaf, toko X hanya berlaku untuk member saja<file_sep>/excerxise-15-week-4.js //<NAME> function changeVocals (str) { //code di sini -- Sfrgfj Drb var res='' var obj = { a:'b', i:'j', u:'v', e:'f', o:'p', A:'B', I:'J', U:'V', E:'F', O:'P' } // var consonantGroup='bjvfpBJVFP' // console.log(str.length) for (var i =0; i < str.length; i++) { // console.log(str[i]+'==='+obj[str[i]]) if (typeof obj[str[i]] !== 'undefined') { res += obj[str[i]] } else { res += str[i] } // console.log(str[i]) } // console.log(res,'---vocal') // console.log(res) return res } function reverseWord (str) { //code di sini if (str.length-1 === 0) { return str[0] } return str[str.length-1]+reverseWord(str.slice(0,str.length-1)) } function setLowerUpperCase (str) { //code di sini var abjad = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz -1234567890' var caseAbjad = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -1234567890' var res = '' for (var i = 0; i < str.length; i++ ){ for (var j = 0; j < abjad.length; j++ ) { if (abjad[j] === str[i]) { res += caseAbjad[j] } } } // console.log(res,'--ini yg up low case') return res } function removeSpaces (str) { //code di sini var res='' var arr=[] arr = str.split(' ') // console.log(arr,'--removeSpaces') for (var i = 0; i < arr.length; i++) { res += arr[i] } return res } function passwordGenerator (name) { //code di sini if (name.length < 5) { return 'Minimal karakter yang diinputkan adalah 5 karakter' } else { var noVocal = changeVocals(name) var reversed = reverseWord(noVocal) var changeCase = setLowerUpperCase(reversed) var password = removeSpaces(changeCase) return password } } console.log(passwordGenerator('<NAME>')); // 'VP<PASSWORD>' console.log(passwordGenerator('<PASSWORD>')); // '<PASSWORD>' console.log(passwordGenerator('<PASSWORD>')); // '<PASSWORD>' console.log(passwordGenerator('<PASSWORD>')); // 'Minimal karakter yang diinputkan adalah 5 karakter'<file_sep>/excerxise-18-week-4.js function kaliTerusRekursif(angka) { // you can only write your code here! var numStr = ''+angka var isOneDigit=0 if (numStr.length === 1) { return parseInt(numStr) } isOneDigit = parseInt(numStr[0]) * kaliTerusRekursif(numStr.slice(1)) // return isOneDigit return kaliTerusRekursif(isOneDigit) } // TEST CASES console.log(kaliTerusRekursif(66)); // 8 console.log(kaliTerusRekursif(3)); // 3 console.log(kaliTerusRekursif(24)); // 8 console.log(kaliTerusRekursif(654)); // 0 console.log(kaliTerusRekursif(1231)); // 6<file_sep>/excerxise-14-week-4.js function sorting(arrNumber) { // penampung function var res=[] //code if (arrNumber == "") { res = "''" } else { arrNumber.sort() var maxNum = arrNumber[arrNumber.length-1] // console.log(arrNumber,'---> punya sorting',arrNumber.length-2 ) // cari angka max for (var i =arrNumber.length-2; i >= 0 ; i--) { if ( maxNum === arrNumber[i]) { res.push(arrNumber[i]) } } res.push(maxNum) // } console.log(maxNum,'----->max number') // console.log(res,'------> result array max') } return res } function getTotal(arrNumber) { // code di sini var res='' var total=0 if (arrNumber == "''") { res = "''" } else { for ( var i = 0; i < arrNumber.length; i++) { total++ } res = 'angka paling besar adalah '+ arrNumber[0] +' dan jumlah kemunculan sebanyak '+ total +' kali' } return res } function mostFrequentLargestNumbers(arrNumber) { var listSort = sorting(arrNumber); var countHighest = getTotal(listSort); return countHighest; } console.log(mostFrequentLargestNumbers([2, 8, 4, 6, 8, 5, 8, 4])); //'angka paling besar adalah 8 dan jumlah kemunculan sebanyak 3 kali' console.log(mostFrequentLargestNumbers([122, 122, 130, 100, 135, 100, 135, 150])); //'angka paling besar adalah 150 dan jumlah kemunculan sebanyak 1 kali' console.log(mostFrequentLargestNumbers([1, 1, 1, 1])); //'angka paling besar adalah 1 dan jumlah kemunculan sebanyak 4 kali' console.log(mostFrequentLargestNumbers([])); //''
3324a71a77eacd7adb9c0343e3e62cf9f9514678
[ "JavaScript" ]
5
JavaScript
agungatd/h8-p0-w4
317ecbf83ada0857d02eaf721d10d5baabfede2c
ef9353ef071089a8d92c4051c6967d85e65851b6
refs/heads/master
<repo_name>kadamgreene/PostSharp.FastTrack<file_sep>/PostSharp.UndoRedo/ViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PostSharp.Patterns.Model; using PostSharp.Patterns.Recording; using System.ComponentModel; namespace PostSharp.UndoRedo { [Recordable] [NotifyPropertyChanged] public class ViewModel { public string FirstName { get; set; } public string LastName { get; set; } public ViewModel() { FirstName = "Original"; LastName = "Name"; Address = new Address { Street = "100 Main St" }; } [Child] public Address Address { get; set; } } [Recordable] [NotifyPropertyChanged] public class Address { public string Street { get; set; } } } <file_sep>/PostSharp.Custom/TimedAttribute.cs using System; using System.Reflection; using PostSharp.Aspects; using PostSharp.Extensibility; using System.Diagnostics; namespace PostSharp.Custom { [Serializable] public sealed class TimedAttribute : OnMethodBoundaryAspect { #region Build-Time Logic public override bool CompileTimeValidate(MethodBase method) { return method.Name.Equals("SayHello"); } public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) { this.CompileTime = DateTime.Now; } #endregion #region Run-Time Logic public override void RuntimeInitialize(MethodBase method) { this.RuntimeTime = DateTime.Now; } #endregion public override void OnEntry(MethodExecutionArgs args) { // It is equiavlent to the start of the "try" Stopwatch sw = new Stopwatch(); args.MethodExecutionTag = sw; sw.Start(); } public override void OnExit(MethodExecutionArgs args) { // It is equivalent to the 'finally' block. var sw = args.MethodExecutionTag as Stopwatch; sw.Stop(); Console.WriteLine("{0} took {1}ms [run started at {2}, compiled at {3}]", args.Method.Name, sw.ElapsedMilliseconds, RuntimeTime.ToLongTimeString(), CompileTime.ToLongTimeString()); } public override void OnSuccess(MethodExecutionArgs args) { // This method is invoked after successful execution of the method to which the current aspect is applied. } public override void OnException(MethodExecutionArgs args) { // This method is invoked upon exception in the method to which the current aspect is applied. // It is equivelent to the 'catch' block. } public DateTime CompileTime { get; private set; } public DateTime RuntimeTime { get; private set; } } } <file_sep>/PostSharp.ReaderWriterLock/ReadWriterProgram.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PostSharp.ReaderWriterLock { class ReadWriterProgram { static void Main(string[] args) { Calc c = new Calc(); Console.Write("Enter First Number: "); var num1 = Console.ReadLine(); c.FirstNumber = Double.Parse(num1); Console.Write("Enter Second Number: "); var num2 = Console.ReadLine(); c.SecondNumber = Double.Parse(num2); var t1 = Task.Factory.StartNew(() => c.Add()); var t2 = Task.Factory.StartNew(() => c.SecondNumber /= 2); Task.WaitAll(t1, t2); Console.ReadLine(); } } } <file_sep>/PostSharp.Aggregatable/Objects - Disposable.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PostSharp.Patterns.Model; using PostSharp.Patterns.Collections; namespace PostSharp.Aggregatable { [Disposable] public class Person { public Person() { Addresses = new AdvisableCollection<Address>(); } public string Name { get; set; } [Child] public AdvisableCollection<Address> Addresses { get; set; } [Reference] public Address MainAddress { get; set; } } [Aggregatable] public class Address : Disposable { private Guid id; public Address() { this.id = Guid.NewGuid(); } public string Street { get; set; } public string City { get; set; } public string Province { get; set; } public string Postal { get; set; } [Parent] public Person Parent { get; set; } private bool disposed = false; protected override void Dispose(bool dispose) { Console.WriteLine("Address disposed: {0}", id); } } } <file_sep>/PostSharp.Custom/Services/GreetingsService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace PostSharp.Custom.Services { public class GreetingsService { public void SayHello(string name) { Console.WriteLine("Hello, " + name); Thread.Sleep(1000); } public void SayGoodbye(string name) { Console.WriteLine("Goodbye, " + name); Thread.Sleep(1000); } } } <file_sep>/PostSharp.NotifyPropertyChange/Person.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using PostSharp.Patterns.Model; namespace PostSharp.NotifyPropertyChange { public class Person { public Person() { } public string LastName { get; set; } public string FirstName { get; set; } public string FullName { get { return this.FirstName + " " + this.LastName; } } } } <file_sep>/PostSharp.Custom/CustomProgram.cs using PostSharp.Custom.Services; namespace PostSharp.Custom { class CustomProgram { static void Main(string[] args) { GreetingsService service = new GreetingsService(); service.SayHello("Adam"); service.SayGoodbye("Adam"); } } } <file_sep>/PostSharp.ReaderWriterLock/Calc.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using PostSharp.Patterns.Threading; namespace PostSharp.ReaderWriterLock { public class Calc { public double FirstNumber { get; set; } public double SecondNumber { get; set; } public void Add() { Console.Write("{0}", FirstNumber); Console.Write(" + "); Console.Write("{0}", SecondNumber); Thread.Sleep(50); Console.WriteLine(" = {0}", FirstNumber + SecondNumber); } } }<file_sep>/PostSharp.Aggregatable/Program.cs using PostSharp.Patterns.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PostSharp.Aggregatable { class Program { static void Main(string[] args) { Person p = new Person() { Name = "<NAME>" }; var addr1 = new Address() { Street = "100 Main St" }; var addr2 = new Address() { Street = "200 Left St" }; var addr3 = new Address() { Street = "300 Right St" }; p.Addresses.Add(addr1); p.Addresses.Add(addr2); p.MainAddress = addr3; // Show that parent is automatically set Console.WriteLine("Parent Name: {0}", addr1.Parent.Name); //VisitChildren(p); ((IDisposable)p).Dispose(); } private static void VisitChildren(Person p) { // Visit all Children IAggregatable agg = p as IAggregatable; agg.VisitChildren((child, childinfo, state) => { if (child is Address) { Console.WriteLine("Address is: {0}", ((Address)child).Street); } return true; }); } } } <file_sep>/PostSharp.Aggregatable/Objects - Normal.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PostSharp.Patterns.Model; using PostSharp.Patterns.Collections; using System.Collections.ObjectModel; namespace PostSharp.Aggregatable { public class Person : IDisposable { private List<Address> addresses; public Person() { this.addresses = new List<Address>(); } public string Name { get; set; } public ReadOnlyCollection<Address> Addresses { get { return new ReadOnlyCollection<Address>(addresses); } } public Address MainAddress { get; set; } public void AddAddress(Address address) { address.Parent = this; addresses.Add(address); } public void Dispose() { addresses.ForEach(x => { ((IDisposable)x).Dispose(); }); MainAddress.Dispose(); } } public class Address : Disposable { private Guid id; public Address() { this.id = Guid.NewGuid(); } public string Street { get; set; } public string City { get; set; } public string Province { get; set; } public string Postal { get; set; } public Person Parent { get; set; } protected override void Dispose(bool dispose) { Console.WriteLine("Address disposed: {0}", id); } } } <file_sep>/PostSharp.Immutable/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PostSharp.Immutable { class Program { static void Main(string[] args) { Person p = new Person(); p.address.Street = "new st"; } } } <file_sep>/PostSharp.UndoRedo/MainWindow.xaml.cs using PostSharp.Patterns.Recording; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PostSharp.UndoRedo { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { readonly ViewModel viewModel = new ViewModel(); public ViewModel ViewModel { get { return viewModel; } } public MainWindow() { InitializeComponent(); RecordingServices.DefaultRecorder.Clear(); } private void Button_Click(object sender, RoutedEventArgs e) { using (var scope = RecordingServices.DefaultRecorder.OpenScope("Info Changed")) { ViewModel.FirstName = "Atomic"; ViewModel.LastName = "Change"; ViewModel.Address.Street = "200 New St"; scope.Complete(); } } } } <file_sep>/PostSharp.Immutable/PersonNormal.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PostSharp.Immutable { public class Person { public readonly string name; public readonly int age; public readonly Address address; public Person() { name = "Adam"; age = 39; address = new Address { Street = "100 Main St" }; } } public class Address { public string Street { get; set; } } } <file_sep>/PostSharp.Immutable/PersonImmutable.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PostSharp.Patterns.Threading; using PostSharp.Patterns.Model; namespace PostSharp.Immutable { [Immutable] public class Person { public string name; public int age; [Child] public Address address; public Person() { SetInformation(); } private void SetInformation() { name = "Adam"; age = 39; address = new Address { Street = "100 Main St" }; } } [Freezable] public class Address { public string Street { get; set; } } } <file_sep>/README.md # PostSharp.FastTrack
6ec8ab852738e03a34d1a94ad081c401c22d855a
[ "Markdown", "C#" ]
15
C#
kadamgreene/PostSharp.FastTrack
db31f41ca5ff9758b31a01218a7eeb79a5473c4d
4998c540782e6d69b3dae40dfddcf435df3630d1
refs/heads/main
<file_sep>#Thu Mar 11 09:28:18 IST 2021 org.eclipse.core.runtime=2 org.eclipse.platform=4.18.0.v20201202-1800 <file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.SQLException; import java.util.Properties; public class WorkerThread extends Thread{ private String filePath; private Properties criteriaProps; private String fileName; FileWriter validFile; FileWriter invalidFile; WorkerThread(String filePath){ this.filePath = filePath; this.fileName=Paths.get(filePath).getFileName().toString(); try { this.invalidFile=new FileWriter(MyConstants.OUTPUT_DIR+"/"+fileName+"invalidFile.csv") ; this.validFile=new FileWriter(MyConstants.OUTPUT_DIR+"/"+fileName+"validFile.csv") ; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } { criteriaProps=new Properties(); try { criteriaProps.load(new FileReader("csvCriterion.props")); } catch (IOException e) { e.printStackTrace(); } } public void run() { System.out.println("Worker Thread started for file "+filePath); try { csvReader(filePath); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void csvReader(String filePath) throws SQLException { String line=""; String splitBy=","; try { BufferedReader br=new BufferedReader(new FileReader(filePath)); while((line=br.readLine())!=null) { mainlogic(line,splitBy); } validFile.close(); invalidFile.close(); DataBaseLayer.closeConn(); System.out.println("connection closed"); } catch (IOException e) { e.printStackTrace(); } } private void mainlogic(String line,String splitBy) throws IOException, SQLException { String[] account=line.split(splitBy); DataBaseLayer db=new DataBaseLayer(); boolean validator=true; for(int i=0;i<account.length;i++) { if (checkField(account[i],Integer.toString(i))){ validator=true; } else { validator=false; break; } } if(validator) { writetoValidFile(line); db.writetoValidDB(line, fileName); } else { writetoInvalidFile(line); } } private void writetoInvalidFile(String line) throws IOException { this.invalidFile.write(line); } private void writetoValidFile(String line) throws IOException{ this.validFile.write(line); } private boolean checkField(String fieldValue, String field) { if(this.criteriaProps.containsKey(field)){ int lengthofField=fieldValue.length(); String fieldCritera=criteriaProps.getProperty(field); if(lengthofField<=Integer.parseInt(fieldCritera)) { return true; } return false; } return false; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-reactiveform', templateUrl: './reactiveform.component.html', styleUrls: ['./reactiveform.component.css'] }) export class ReactiveformComponent implements OnInit { title="Reactive Model Form"; constructor() { } ngOnInit(): void { } registrationform = new FormGroup({ //username : new FormControl('Amit'), //default value username : new FormControl('Amit', [Validators.required, Validators.minLength(4)]), password : new FormControl(''), confirmPassword : new FormControl(''), address : new FormGroup({ city : new FormControl('Pune'), //city, state and postalcode combined in address state : new FormControl(''), postalcode : new FormControl('') }) }); onSubmit(){ console.log(this.registrationform.value); alert(JSON.stringify(this.registrationform.value)); } } <file_sep>import { Component } from "@angular/core"; @Component({ selector : 'equitycomp', template : `<h5>This is the area for Finance News - Equity <h5>` }) export class EquityNewsComponent { }<file_sep>package com.training.MyApp.business; import br.gov.frameworkdemoiselle.stereotype.BusinessController; import br.gov.frameworkdemoiselle.template.DelegateCrud; import com.training.MyApp.domain.Category; import com.training.MyApp.persistence.CategoryDAO; @BusinessController public class CategoryBC extends DelegateCrud<Category, Long, CategoryDAO> { private static final long serialVersionUID = 1L; } <file_sep> import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Date; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class FileServer { static HashMap<String,String> fileMap = new HashMap<String,String>(); static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); static { //Getting all the folders to map File folder = new File(FileDriver.folderPath); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { if (file.isFile()) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); FileServer.fileMap.put(file.getName(), sdf.format(file.lastModified())); } } } public static void createFile(String folderPath, String newFileName) throws IOException { if(!fileMap.containsKey(newFileName)){ File newFile= new File(folderPath+"\\" + newFileName); if(newFile.createNewFile()) { BasicFileAttributes attr = Files.readAttributes(newFile.toPath(), BasicFileAttributes.class); fileMap.put(newFile.getName(), sdf.format(attr.creationTime())); } serializing(); } else { String oldFileDate=fileMap.get(newFileName); String todaysDate= LocalDate.now().format(DateTimeFormatter.ofPattern("MM/dd/yyyy")); if(!oldFileDate.equals(todaysDate) ) { File newFile= new File(folderPath+"\\" + newFileName+ "-Copy"); if(newFile.createNewFile()) { fileMap.put(newFile.getName(), sdf.format(newFile.lastModified())); } serializing(); } } } public static void serializing() { try{ FileOutputStream fos= new FileOutputStream("myfile"); ObjectOutputStream oos= new ObjectOutputStream(fos); oos.writeObject(fileMap); oos.close(); fos.close(); }catch(IOException ioe){ ioe.printStackTrace(); } } public static HashMap<String,String> deserializing(){ HashMap<String, String> retfileMap = null; try { FileInputStream fis = new FileInputStream("myfile"); ObjectInputStream ois = new ObjectInputStream(fis); retfileMap = (HashMap<String, String>) ois.readObject(); ois.close(); fis.close(); }catch(IOException ioe){ ioe.printStackTrace(); }catch(ClassNotFoundException c){ c.printStackTrace(); } return retfileMap; } }<file_sep>package com.training.studentproject; public class Subject { String subjectName; int subjectMarks; public Subject(String subjectName, int subjectMarks) { this.subjectName = subjectName; this.subjectMarks = subjectMarks; } public String getSubjectName() { return subjectName; } public int getSubjectMarks() { return subjectMarks; } } <file_sep> public class Address implements Comparable<Address>{ String city; int pin; public Address(String city,int pin) { this.city=city; this.pin=pin; } public boolean equals(Object obj) { Address a=(Address)obj; return this.city.equals(a.city) && this.pin==(a.pin); } @Override public int compareTo(Address o) { // TODO Auto-generated method stub return this.city.compareTo(o.city); } } <file_sep>import java.util.Collection; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import bank.iserver.internal.service.AccountRepository; import bank.iserver.internal.service.AccountService; import bank.server.Bank; import bank.server.internal.Account; import bank.server.internal.AccountRepositoryImpl; import bank.server.internal.BankImpl; public class TestBank { /** * @param args */ public static void main(String[] args) { // AnnotationConfigApplicationContext ctx =new AnnotationConfigApplicationContext(BankConfig.class); ApplicationContext ctx = new ClassPathXmlApplicationContext("application-list.config.xml"); Bank bank1 = (Bank) ctx.getBean("bankService"); Bank bank2 = (Bank) ctx.getBean("bankService"); System.out.println("Is it a singleton "+(bank1==bank2)); // System.out.println(ctx.getClass().getName()); System.out.println("New Balance after withdrawal= "+bank1.withdraw(50, 1234)); Collection<AccountService> accountTypes = bank1.showAccountServices(); for(AccountService acctType : accountTypes){ System.out.println("Account Service "+acctType); } } } <file_sep> import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.rits.Magician; public class TestMagician { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); //Since this is a non-managed bean dependencies will not normally be injected. //But since class Magician has been annotated @Configurable, Spring is injecting dependencies Magician magician = new Magician(); magician.perform(); } } <file_sep>public void getLocks(Object a, Object b) { synchronized(a) { synchronized(b) { //do something } } } and the following instantiations: Object obj1 = new Object(); Object obj2 = new Object(); <file_sep> public class TwoWheeler extends Vehicle { private String twoWheelerModel; public String getTwoWheelerModel() { return twoWheelerModel; } public void setTwoWheelerModel(String twoWheelerModel) { this.twoWheelerModel = twoWheelerModel; } } <file_sep>oracleDriver=oracle.jdbc.driver.OracleDriver oracleURL=jdbc:oracle:thin:@localhost:1521:XE oracleUser=system oraclePassword=<PASSWORD> <file_sep>package bank.server.internal; import java.util.ArrayList; import java.util.Collection; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ImportResource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean; import bank.iserver.internal.service.AccountRepository; import bank.iserver.internal.service.AccountService; import bank.server.Bank; @Configuration("configBank") @ImportResource("test-infrastructure-Java_Based_config.xml") public class BankConfig { private @Value("#{jdbcProperties.oracleURL}") String url; private @Value("#{jdbcProperties.oracleUser}") String username; private @Value("#{jdbcProperties.oraclePassword}") String password; private @Value("#{jdbcProperties.oracleDriver}") String driverClassName; // if name is not specified then name of the Bean is same Collection<E> the method @Bean(name="bankService") @Scope("prototype") Bank bankService(){ Collection<AccountService> accts = new ArrayList<AccountService>(); accts.add(currentAccount()); accts.add(loan()); accts.add(saving()); return new BankImpl(accountRepository(),accts); } @Bean(name="acctRepo") AccountRepository accountRepository(){ return new AccountRepositoryImpl(dataSource()); } @Bean(name="current") AccountService currentAccount(){ CurentAccount acct= new CurentAccount("Ramkrishna IT",1000000); acct.setAcctNo(123456789); return acct; } @Bean(name="saving") AccountService saving(){ SavingsType saving = new SavingsType("<NAME>"); saving.setInterestRate(10.5f); return saving; } @Bean(name="loan") AccountService loan(){ LoanAccount loan = new LoanAccount("HousingLoan", 15); loan.setRateOfInterest(11.5f); return loan; } public @Bean DriverManagerDataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(url, username, password); dataSource.setDriverClassName(driverClassName); return dataSource; } } <file_sep>package bank.server.internal; import bank.iserver.internal.service.AccountService; public class LoanAccount implements AccountService { String loanType; int loanTerm; float rateOfInterest; int loanAmount; LoanAccount(){super();} public String getLoanType() { return loanType; } public void setLoanType(String loanType) { this.loanType = loanType; } public int getLoanAmount() { return loanAmount; } public void setLoanAmount(int loanAmount) { this.loanAmount = loanAmount; } public String getLonanType() { return loanType; } public void setLonanType(String lonanType) { this.loanType = lonanType; } public int getLoanTerm() { return loanTerm; } public void setLoanTerm(int loanTerm) { this.loanTerm = loanTerm; } public LoanAccount(String loanType, int loanTerm) { super(); this.loanType = loanType; this.loanTerm = loanTerm; } public float getRateOfInterest() { return rateOfInterest; } public void setRateOfInterest(float rateOfInterest) { this.rateOfInterest = rateOfInterest; } @Override public String toString() { return "LoanAccount [loanTerm=" + loanTerm + ", lonanType=" + loanType + ", rateOfInterest=" + rateOfInterest + "]"; } @Override public int updateBalance(int amount) { setLoanAmount(amount); return getLoanAmount(); } } <file_sep> public interface Bank { int MIN_BALANCE = 1000; String openAccount(String name,String address,int amount) throws InsufficientBalanceException; int withdraw(int accno, int amount) throws InsufficientBalanceException, InvalidAccountException; int deposit(int accno, int amount) throws InvalidAccountException; int transfer(int accfrom, int accto, int amount) throws InvalidAccountException, InsufficientBalanceException; int closeAccount(int accno) throws InvalidAccountException; String printRecentTransaction(int accno, int notxns) throws InvalidAccountException; } <file_sep>package com.rits; public abstract class MagicBoxImpl implements MagicBox { public MagicBoxImpl() { super(); } @Override public abstract String showContents(String val); /*{ return "A beautiful Assitant"; }*/ } <file_sep>import java.io.IOException; import java.util.Map; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; class LogAction implements Action{ @Override public void takeAction(Map<String, String> map) { Logger logger = Logger.getLogger("MyLog"); FileHandler fh; try { String fp=map.get("logFilePath"); fh = new FileHandler(fp); logger.addHandler(fh); logger.log(Level.INFO,map.get("exception"));; } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }<file_sep>hdfc.txt=13:00:15 icici.txt=11:00:15 sbi.txt=14:00:15<file_sep>import java.lang.reflect.Proxy; public class ProductFactory { static Product newProduct(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ Product product = (Product) Class.forName(className).newInstance(); Product proxy = (Product) Proxy.newProxyInstance(Product.class.getClassLoader(), new Class[]{Product.class}, new DiscountAspect(new LoggerAspect(product),product)); return proxy; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { User } from './user'; @Component({ selector: 'app-templatedrivenform', templateUrl: './templatedrivenform.component.html', styleUrls: ['./templatedrivenform.component.css'] }) export class TemplatedrivenformComponent implements OnInit { title="Template Driven Form"; constructor() { } topics = ['Angular','React','Vue']; userModel=new User("as","asd","asds","asds","asds"); ngOnInit(): void { } } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { NewsComponent } from './news/news.component'; import { ProductDetails } from './productdetails'; import { Product } from './product'; import { SportsNewsComponent } from './news/sportsnews'; import { FinanceNewsComponent } from './news/financenews'; import { EquityNewsComponent } from './news/equityNews'; @NgModule({ declarations: [ AppComponent, AboutComponent, NewsComponent, SportsNewsComponent, FinanceNewsComponent, EquityNewsComponent, Product, ProductDetails ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component } from "@angular/core"; import { Router } from "@angular/router"; @Component({ selector: 'prod-comp', template: `<h2>Product Details</h2> <table border="3" *ngFor="let p of products" (click)="onSelectName(p)"> <tr> <td>{{p.id}}</td> <td>{{p.name}}</td> <td>{{p.price}}</td> </tr> </table> ` }) export class Product{ constructor(private router: Router){ } products=[ {"id":101,"name":"laptop","price":3200}, {"id":102,"name":"phone","price":3200}, {"id":103,"name":"TV","price":3200} ]; onSelectName(p: any){ this.router.navigate(['/selectedprod',p.name]); } }<file_sep>import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.rits.MagicBox; import com.rits.Magician; public class TestMagician { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); Magician magician = ctx.getBean(Magician.class); magician.perform(); // magician.perform(ctx.getBean(MagicBox.class),"hello"); } } <file_sep>import { Observable, of } from 'rxjs'; import {map} from 'rxjs/operators'; const nums=of(1,2,3); const squareValues=map(((val: number) => val * val)); const squaredNums=squareValues(nums); squaredNums.subscribe( ); x =>console.log(x) console.log("HEY"); let observable = new Observable((observer: { next: (arg0: number) => void; }) => { for (let i = 0; i < 3; i++) { observer.next(i); } });<file_sep>import { Component, OnInit } from "@angular/core"; import { ActivatedRoute } from "@angular/router"; @Component({ template: `<h2> You have selected the Product := {{prod_nam}}</h2> <button routerLink="/prod">Go Back<button> ` }) export class ProductDetails implements OnInit{ prod_nam=""; constructor(private ar : ActivatedRoute){ let name=this.ar.snapshot.params['nam']; this.prod_nam = name; } ngOnInit(){ } }<file_sep>import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AboutComponent } from './about/about.component'; import { EquityNewsComponent } from './news/equityNews'; import { FinanceNewsComponent } from './news/financenews'; import { NewsComponent } from './news/news.component'; import { SportsNewsComponent } from './news/sportsnews'; import { Product } from './product'; import { ProductDetails } from './productdetails'; const routes: Routes = []; const routes1= [ {path:'about',component:AboutComponent}, {path:'news',component:NewsComponent} ] const routes2= [ {path:'about',component:AboutComponent}, {path:'news',component:NewsComponent, children: [ {path: 'news/sports',component:SportsNewsComponent}, {path: 'news/finance',component:FinanceNewsComponent}, {path: 'news/finance/equity',component:EquityNewsComponent} ] } ] const routes3= [ {path:'about',component:AboutComponent}, {path:'news',component:NewsComponent, children: [ {path: 'news/sports',component:SportsNewsComponent}, {path: 'news/finance',component:FinanceNewsComponent}, {path: 'news/finance/equity',component:EquityNewsComponent} ] }, { path:'prod',component:Product}, { path:'selectedprod/:nam',component:ProductDetails} ] @NgModule({ imports: [RouterModule.forRoot(routes3)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>"use strict"; exports.__esModule = true; var rxjs_1 = require("rxjs"); var operators_1 = require("rxjs/operators"); var nums = rxjs_1.of(1, 2, 3); var squareValues = operators_1.map((function (val) { return val * val; })); var squaredNums = squareValues(nums); squaredNums.subscribe(); (function (x) { return console.log(x); }); console.log("HEY"); var observable = new rxjs_1.Observable(function (observer) { for (var i = 0; i < 3; i++) { observer.next(i); } }); <file_sep>package com.rits; public class BeautifulAssistantBox implements MagicBox { public BeautifulAssistantBox() { super(); } @Override public String getContents() { return "A beautiful Assitant"; } } <file_sep>import { Component } from "@angular/core"; @Component({ selector : 'sportscomp', template : `<h5>This is the area for Sports News <h5>` }) export class SportsNewsComponent { }<file_sep>package bank.server; import java.util.Collection; import java.util.Map; import bank.iserver.internal.service.AccountService; public interface Bank { int withdraw(int amount , int acctNo); Collection<AccountService> showAccountServices(); Map<String,AccountService> showAccountServicesByName(); } <file_sep>package bank.iserver.internal.service; abstract public class AccountServiceClass { abstract public int updateBalance(int amount); } <file_sep>import java.io.IOException; import java.util.Scanner; import java.util.Set; public class FileDriver { static String folderPath; static Scanner sc= new Scanner(System.in); private static void listFiles() throws IOException { Set<String> setKeys = FileServer.deserializing().keySet(); for(String key : setKeys){ System.out.println( key+": "+ FileServer.deserializing().get(key) ); } showMenu(); } private static void newFile() throws IOException { System.out.println("Enter File Name"); String newFileName=sc.next(); FileServer.createFile(folderPath, newFileName); System.out.println("File Created Successfully"); showMenu(); } private static void showMenu() throws IOException { System.out.println("1. Create File \n2. List Files\n3. Exit"); int menuInput; while(true) { menuInput = sc.nextInt(); switch(menuInput) { case 1: newFile();break; case 2: listFiles();break; case 3: System.out.println("Bye");System.exit(0);break; } } } private static void serverSetup() { System.out.println("Enter Folder Path"); folderPath =sc.next(); } public static void main(String[] args) throws IOException { serverSetup(); showMenu(); } } <file_sep> public class Account { int balance; String name; int acctNo; public Account(int balance, String name, int acctNo) { super(); this.balance = balance; this.name = name; this.acctNo = acctNo; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAcctNo() { return acctNo; } public void setAcctNo(int acctNo) { this.acctNo = acctNo; } } <file_sep> import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.rits.Magician; public class TestMagician { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); Magician magician1 = ctx.getBean("magician",Magician.class); magician1.perform(); System.out.println("Magician 2 Will perform Now !!"); Magician magician2 = ctx.getBean("magician2",Magician.class); magician2.perform(); } } <file_sep> public class HRThread extends Thread{ private LeaveApplication application; HRThread(LeaveApplication application){ this.application=application; } public void run() { System.out.println("HR Recieves Application"); try { Thread.sleep(5000); } catch(InterruptedException e) {} this.application.setHrApprovalStatus(false); System.out.println("HR DONE"); } } <file_sep>package com.perennial.training.rkit; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class AnnotationHandler implements InvocationHandler{ Object obj; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getAnnotation(EntryLog.class)!=null) { System.out.println("Entering : Entry Log"+method.getName()); } return method.invoke(obj, args); } public static void setObj(Object obj) { } } <file_sep>package bank.server.internal; import org.springframework.beans.factory.annotation.Autowired; public class Account { int balance; String name; int acctNo; Account(){super();} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + acctNo; result = prime * result + balance; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Account other = (Account) obj; if (acctNo != other.acctNo) return false; if (balance != other.balance) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Account [acctNo=" + acctNo + ", balance=" + balance + ", name=" + name + "]"; } @Autowired public Account(AccountInfo info) { super(); this.balance = info.balance; this.name = info.name; this.acctNo = info.acctNo; } public int getAcctNo() { return acctNo; } public void setAcctNo(int acctNo) { this.acctNo = acctNo; } public Account(int balance, String name) { super(); this.balance = balance; this.name = name; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int updateBalance(int amount){ setBalance(amount); return getBalance(); } } <file_sep>balance=1000000000 name=JaiShreeram acctNo=12121212<file_sep> public class SharedClass { public static boolean done; public static boolean isDone() { return done; } public void setDone(boolean done) { SharedClass.done=done; } } <file_sep>package com.rits; import java.lang.reflect.Method; import org.springframework.beans.factory.support.MethodReplacer; public class ElephantReplacer implements MethodReplacer { @Override public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable { return " MYSORE ELEPHANT "; } } <file_sep>package bank.iserver.internal.service; import bank.server.internal.Account; public interface AccountRepository { Account findAccountByAcctNumber(int acctNo); } <file_sep>package bank.server.internal; import org.springframework.beans.factory.annotation.Required; import bank.iserver.internal.service.AccountService; public class SavingsType implements AccountService { String custName; public SavingsType(String custName, float interestRate) { super(); this.custName = custName; this.interestRate = interestRate; } public SavingsType(String custName) { super(); this.custName = custName; } float interestRate; public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public float getInterestRate() { return interestRate; } @Required public void setInterestRate(float interestRate) { this.interestRate = interestRate; System.out.println("Saving Account : @Required set SO must be in config file"); } @Override public String toString() { return "SavingsType [custName=" + custName + ", interestRate=" + interestRate + "]"; } } <file_sep> public class LeaveApplication { private String fname; private String lname; private int noofDays; private boolean hrApprovalStatus; private boolean mgrApprovalStatus; public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public int getNoofDays() { return noofDays; } public void setNoofDays(int noofDays) { this.noofDays = noofDays; } public boolean isHrApprovalStatus() { return hrApprovalStatus; } public void setHrApprovalStatus(boolean hrApprovalStatus) { this.hrApprovalStatus = hrApprovalStatus; } public boolean isMgrApprovalStatus() { return mgrApprovalStatus; } public void setMgrApprovalStatus(boolean mgrApprovalStatus) { this.mgrApprovalStatus = mgrApprovalStatus; } public LeaveApplication(String fname,String lname,int noofDays) { // TODO Auto-generated constructor stub this.fname=fname; this.lname=lname; this.noofDays=noofDays; } public static void main(String[] args) { // TODO Auto-generated method stub LeaveApplication application =new LeaveApplication("Manas", "Joshi", 2); HRThread hr=new HRThread(application); hr.setName("HR-Thread"); ManagerThread mgr=new ManagerThread(application); mgr.setName("Manager-Thread"); hr.start(); mgr.start(); AccountsMgrThread accts=new AccountsMgrThread(application,new Thread[] {hr,mgr}); accts.start(); } } <file_sep>package bank.server.internal.aspects; import java.lang.reflect.Field; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.core.annotation.Order; import bank.server.internal.LoanAccount; @Aspect public class FieldValueChangeTracker { @Around(value="execution(* bank.server.internal.*.set*(..))") void trackChange(ProceedingJoinPoint jp){ String methodName = jp.getSignature().getName(); Object newValue = jp.getArgs()[0]; Object target = jp.getTarget(); System.out.println("Property is about to change"); System.out.println("DEBUG BEFOR State "+target); try { Object o = jp.proceed(); System.out.println("Inside AROUND advise and returned value is "+o); System.out.println("Chaning retunred value "); ((LoanAccount)o).setLoanAmount(-200); } catch (Throwable e) { // TODO Auto-generated catch block System.out.println("DEBUG : Inside Around ADVISE catch block"); e.printStackTrace(); } System.out.println("DEBUG : AFTER state "+target); } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'square' }) export class SquarePipe implements PipeTransform { transform(value: any, ...args: any): unknown { console.log("value which is of type any " + typeof value); console.log("args which is array of any[]" + args); return value*value; } } <file_sep>package bank.server.internal.aspects; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.core.annotation.Order; @Aspect public class PropertyChangeTracker { @Pointcut(" execution(* update*(..)) || execution(* set*(..))") void updateORSetMethod(){} @Pointcut("(!execution(* bank.server.internal.BankImpl.get*(*))) && execution(* get*(..))") void getMethodAdvice(){} @Order(value=2) @Before("updateORSetMethod()") void trackChange(JoinPoint jp){ String methodName = jp.getSignature().getName(); Object newValue = jp.getArgs()[0]; System.out.println("trackchange method of PropertyChangeTracker1 invoked for method "+methodName); System.out.println("1 Property About to change to "+newValue); } @After("updateORSetMethod()") void trackChange2(JoinPoint jp){ String methodName = jp.getSignature().getName(); Object newValue = jp.getArgs()[0]; System.out.println("trackChange2 method in After Advice of PropertyChangeTracker1 invoked for method "+methodName); System.out.println("After 1 Property changed to "+newValue); } @AfterThrowing(value="getMethodAdvice()",throwing="e") void handleException(JoinPoint p, Throwable e){ System.out.println("DEBUG AfterThrowing invoked due ot Exception "+e.getMessage()+"By method "+p.getSignature().getName()+" On Class "+p.getTarget().getClass().getName()); } } <file_sep> public class A { B b; A(B b){ System.out.println("A created "); } } <file_sep> public class AccountsMgrThread extends Thread{ private LeaveApplication application; private Thread[] dependantThreads= new Thread[2]; public AccountsMgrThread(LeaveApplication app,Thread[] threads) { this.application=app; this.dependantThreads=threads; } public void run() { System.out.println("Accounts Manager Recieved he will do some preprocessing and others will wait"); for(Thread t: dependantThreads) { try { t.join(); System.out.println("Wait over for "+t.getName()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(this.application.isHrApprovalStatus()&&this.application.isMgrApprovalStatus()) { System.out.println("AccountMgr Thread : Leave Application of "+application.getFname()+"is approved"); } else { System.out.println("Leave Application Rejected"); } } } <file_sep>package com.training.MyApp.ui; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import br.gov.frameworkdemoiselle.vaadin.template.VaadinApplication; import br.gov.frameworkdemoiselle.util.ResourceBundle; import com.training.MyApp.ui.presenter.MainPresenter; import com.vaadin.ui.Window; @SessionScoped public class BookmarkApplication extends VaadinApplication { private static final long serialVersionUID = 1L; @Inject private ResourceBundle bundle; @Inject private MainPresenter mainPresenter; public void init() { setTheme("bookmark"); final Window window = new Window(bundle.getString("app.title")); window.addComponent(mainPresenter.getView()); setMainWindow(window); } } <file_sep>import { Component } from "@angular/core"; @Component({ selector : 'financecomp', template : `<h5>This is the area for Finance News <h5>` }) export class FinanceNewsComponent { }<file_sep>import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class MyApp { public static void main(String[] args) { SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session = factory.openSession(); Transaction txn= session.beginTransaction(); Vehicle vehicle= new Vehicle(); vehicle.setVehicleName("Vanilla Vehicle"); session.save(vehicle); // TwoWheeler twoWheeler1=new TwoWheeler(); twoWheeler1.setVehicleName("Royal Enfield"); twoWheeler1.setTwoWheelerModel("Bullet007"); session.save(twoWheeler1); FourWheeler fourWheeler1 =new FourWheeler(); fourWheeler1.setVehicleName("<NAME>"); fourWheeler1.setFourWheelerModel("Ciaz"); session.save(fourWheeler1); txn.commit(); session.close(); } } <file_sep> public class TestBank { /** * @param args * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException */ public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Bank bank = BankFactory.getBankInstance(); System.out.println("Main : balance after withdrawal"+bank.withdraw(50)); Product product = ProductFactory.newProduct("Umbrella"); System.out.println("ClassName "+product.getClass().getName()); System.out.println("Main Product price "+product.getPrice()); System.out.println("Main : Description is "+product.getDescription()); } } <file_sep> public class FourWheeler extends Vehicle{ private String fourWheelerModel; public String getFourWheelerModel() { return fourWheelerModel; } public void setFourWheelerModel(String fourWheelerModel) { this.fourWheelerModel = fourWheelerModel; } } <file_sep>#Thu Apr 08 12:54:17 IST 2021 org.eclipse.core.runtime=2 org.eclipse.platform=4.18.0.v20201202-1800 <file_sep> public class Thread_B implements Runnable { private SharedClass sharedObj; public Thread_B(SharedClass obj) { this.sharedObj = obj; } @Override public void run() { int i = 0; while (true) { synchronized(sharedObj) { if (!sharedObj.isDone()) { try { sharedObj.wait(); } catch (InterruptedException e) { // TOO Auto-generated catch block e.printStackTrace(); } } this.sharedObj.setDone(true); try { Thread.sleep(5000); System.out.println("property changed by"+ Thread.currentThread().getName()+" Now notifying"); sharedObj.notify(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }<file_sep>import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'aadharno' }) export class AadharnoPipe implements PipeTransform { transform(value: string, ...args: string[]): any{ let delim:string = args[0]; let first:string=value.toString().substr(0,4); let second:string=value.toString().substr(4,4); let third:string=value.toString().substr(8,4); return first+ delim +second+delim+third; } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Localbook } from './localbook'; import { Observable, throwError } from 'rxjs'; import { retry, catchError } from 'rxjs/operators'; import { RemoteBook } from './remotebook'; @Injectable({ providedIn: 'root' }) export class BookdataService { constructor(private httpservice: HttpClient) { } localurl:string = './assets/bookset.json '; remoteurl:string='https://jsonplaceholder.typicode.com/posts'; myData() { return 'This is the data from my DataService !'; } GetLocalBooks(): Observable<Localbook> { return this.httpservice.get<Localbook>(this.localurl).pipe( retry(1), catchError(this.myerrorhandler)); } GetRemoteBooks():Observable<RemoteBook>{ return this.httpservice.get<RemoteBook>(this.remoteurl).pipe( retry(1), catchError(this.myerrorhandler)); } // Error handling myerrorhandler(error) { let errorMessage = ''; if(error.error instanceof ErrorEvent) { // Get client-side error errorMessage = error.error.message; } else { // Get server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } console.log(errorMessage); return throwError(errorMessage); } } <file_sep> public class InvalidAccountException extends Exception { InvalidAccountException(){ System.out.println("Account Not Found"); } } <file_sep>hdfc.csv= 13:59:20 dataBasehdfc = accountFirstName varchar(50),accountLastName varchar(50),accountNumber int(16),accountBalance int(16) icici.csv= 13:00:00 dataBaseicici=accountFirstName varchar(50),accountLastName varchar(50),accountNumber int(16)<file_sep>import java.util.ArrayList; public interface BankDAO { boolean openAccount(Account acc); int updateTransaction(Account acc); void closeAccount(Account acc); Account getAccount(int accNo); int getLastAccNo(); ArrayList<Transaction> displayTransactions(int accNo,int notxns); } <file_sep>package com.rits; import java.lang.reflect.Method; import org.springframework.beans.factory.support.MethodReplacer; public class ElephantBox implements MagicBox{ public String getContents(){ return "MYSORE ELEPHANT"; } } <file_sep>import { Component } from '@angular/core'; import { BookdataService } from './bookdata.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'bookserviceapp'; somedata : string = ""; localbookList: any[]; remotebooklist:any[]; constructor(private bookservice:BookdataService){} /* ngOnInit() is a lifecycle hook, which runs when the component loads */ ngOnInit() { this.somedata=this.bookservice.myData(); this.loadlocalbooks(); this.loadRemotebooks(); } // Load localbooks loadlocalbooks(){ return this.bookservice.GetLocalBooks().subscribe( (data:any)=>{ this.localbookList=data; } ) } loadRemotebooks(){ return this.bookservice.GetRemoteBooks().subscribe( (data:any)=>{ this.remotebooklist=data; } ) } } <file_sep>import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Tester { public static void main(String[] args) { try { throw new IOException(); } catch(IOException e) { System.out.println("IOE CALL"); Map<String,Map> map= ConvertToMap.exceptionHandler("Project1", "Module1", e); List<String> keys = new ArrayList<String>(map.keySet()); for (String key : keys) { // System.out.println(key +": "+ map.get(key)); } } try { throw new SQLException(); } catch(SQLException e) { System.out.println("SQL CALL"); Map<String,Map> map= ConvertToMap.exceptionHandler("Project1", "Module1", e); } } } <file_sep>import java.lang.reflect.Proxy; public class BankFactory { public static Bank getBankInstance() { Bank bank = new BankImpl(); Bank bankProxy = (Bank) Proxy.newProxyInstance(Bank.class.getClassLoader(), bank.getClass().getInterfaces(), new LoggerAspect(bank)); return bankProxy; } }
eeda8628333c0500d02434e9273dc0936f5a70d7
[ "JavaScript", "Java", "TypeScript", "INI" ]
65
INI
manasjoshi1/PerennialTraining
aeba9a7ed6d2d5584694df2c7434cb70a47a6bdc
8edefaa3a7cf4a19660f77677a133b8ac96edde2
refs/heads/master
<file_sep>import logging import smtplib from email.header import Header from email.mime.text import MIMEText class SMTPClient(object): def __init__(self, config): self.config = config def send(self, subject, msg): try: message = MIMEText(msg, 'plain', 'utf-8') message['From'] = self.config['mail_user'] message['To'] = self.config['receiver'] message['Subject'] = Header(subject, 'utf-8') if 'mail_host' in self.config: mail_host = self.config['mail_host'] else: domian = self.config['mail_user'][self.config['mail_user'].index('@') + 1:] mail_host = 'smtp.' + domian mail_port = self.config.get('mail_port') if mail_port is None: mail_port = 465 SMTP_client = smtplib.SMTP_SSL(mail_host, mail_port) SMTP_client.login(self.config['mail_user'], self.config['mail_password']) SMTP_client.sendmail(self.config['mail_user'], [self.config['receiver']], message.as_string()) logging.info("邮件发送成功") except smtplib.SMTPException as ex: logging.error("邮件发送,error:\n{}".format(ex.__traceback__)) if __name__ == '__main__': config = {"mail_user": "<EMAIL>", "mail_password": "<PASSWORD>", 'mail_host': 'smtp.163.com', 'mail_port': 465, 'receiver': '464840<EMAIL>'} smtp_client = SMTPClient(config) smtp_client.send('监控邮件测试', '监控邮件测试') <file_sep>import os import logging from logging.handlers import TimedRotatingFileHandler import sys from datetime import datetime def set_rotating_logger(log_name): logger = logging.getLogger() logger.setLevel(logging.INFO) # formatter log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s' formatter = logging.Formatter(log_fmt) # file log if not os.path.exists('log'): os.mkdir('log') log_file_path = 'log/{0}.log'.format(log_name) file_handler = TimedRotatingFileHandler(log_file_path, when='D', interval=1, backupCount=15) file_handler.setFormatter(formatter) logger.addHandler(file_handler) def set_console_logger(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(filename)s - %(levelname)s - %(message)s') def set_file_logger(log_name): logging.basicConfig(filename='{0}.log'.format(log_name), level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(message)s') def set_print(): old_f = sys.stdout class F: def write(self, s): old_f.write(s.replace("\n", " [%s]\n" % str(datetime.now()))) def flush(self): old_f.flush() sys.stdout = F() <file_sep>import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="common_pyutil", version="1.2.3", author="kylinat2688", author_email="<EMAIL>", url="https://github.com/kylinat2688/common_pyutil", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", ] ) <file_sep>import time # 获取时间戳 def get_timestamp(): return int(round(time.time() * 1000)) <file_sep># common_pyutil 只支持python3 # 发布步骤 1.修改setup.py中的version 2.打包,上传,安装 * rm -r dist * python setup.py sdist bdist_wheel * twine upload -u wenjie.yuan -p SKYWHEEL2012 dist/* * pip install -U common_pyutil 代码托管地址:https://github.com/kylinat2688/common_pyutil<file_sep># -*- coding: utf-8 -*- """ 适用于单卡多卡跑任务的程序,自动根据memory或利用率选择n张显卡 import os from manager import GPUManage gm = GPUManager() inds = gm.auto_choice(mode="memory", num=1)#mode参数取值"memory":选显存剩的大的,"power"是跟gpu利用率正相关的,选利用率低的,默认 memory, num参数按mode选择n张显卡, 默认1 os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = inds """ import os def check_gpus(): ''' GPU available check reference : http://feisky.xyz/machine-learning/tensorflow/gpu_list.html ''' # ============================================================================= # all_gpus = [x.name for x in device_lib.list_local_devices() if x.device_type == 'GPU'] # ============================================================================= first_gpus = os.popen('nvidia-smi --query-gpu=index --format=csv,noheader').readlines()[0].strip() if not first_gpus == '0': print('This script could only be used to manage NVIDIA GPUs,but no GPU found in your device') return False elif not 'NVIDIA System Management' in os.popen('nvidia-smi -h').read(): print("'nvidia-smi' tool not found.") return False return True if check_gpus(): def parse(line, qargs): ''' line: a line of text qargs: query arguments return: a dict of gpu infos Pasing a line of csv format text returned by nvidia-smi 解析一行nvidia-smi返回的csv格式文本 ''' numberic_args = ['memory.free', 'memory.total', 'power.draw', 'power.limit'] # 可计数的参数 power_manage_enable = lambda v: (not 'Not Support' in v) # lambda表达式,显卡是否滋瓷power management(笔记本可能不滋瓷) to_numberic = lambda v: float(v.upper().strip().replace('MIB', '').replace('W', '')) # 带单位字符串去掉单位 process = lambda k, v: ( (int(to_numberic(v)) if power_manage_enable(v) else 1) if k in numberic_args else v.strip()) return {k: process(k, v) for k, v in zip(qargs, line.strip().split(','))} def query_gpu(qargs=[]): ''' qargs: query arguments return: a list of dict Querying GPUs infos 查询GPU信息 ''' qargs = ['index', 'gpu_name', 'memory.free', 'memory.total', 'power.draw', 'power.limit'] + qargs cmd = 'nvidia-smi --query-gpu={} --format=csv,noheader'.format(','.join(qargs)) results = os.popen(cmd).readlines() return [parse(line, qargs) for line in results] def query_gpu_memory(): gpu_stats = query_gpu() gpu_stats = [{'index': gpu_stat['index'], 'memory.free': gpu_stat['memory.free'], 'memory.total': gpu_stat['memory.total']} for gpu_stat in gpu_stats] return gpu_stats def by_power(d): ''' helper function fo sorting gpus by power ''' power_infos = (d['power.draw'], d['power.limit']) if any(v == 1 for v in power_infos): print('Power management unable for GPU {}'.format(d['index'])) return 1 return float(d['power.draw']) / d['power.limit'] class GPUManager(): ''' qargs: query arguments A manager which can list all available GPU devices and sort them and choice the most free one.Unspecified ones pref. GPU设备管理器,考虑列举出所有可用GPU设备,并加以排序,自动选出 最空闲的设备。在一个GPUManager对象内会记录每个GPU是否已被指定, 优先选择未指定的GPU。 ''' def __init__(self, qargs=[]): ''' ''' self.qargs = qargs self.gpus = query_gpu(qargs) for gpu in self.gpus: gpu['specified'] = False self.gpu_num = len(self.gpus) # print(self.gpu_num, "self.gpu_num") def _sort_by_memory(self, gpus, by_size=False): if by_size: print('Sorted by free memory size') return sorted(gpus, key=lambda d: d['memory.free'], reverse=True) else: print('Sorted by free memory rate') return sorted(gpus, key=lambda d: float(d['memory.free']) / d['memory.total'], reverse=True) def _sort_by_power(self, gpus): return sorted(gpus, key=by_power) def _sort_by_custom(self, gpus, key, reverse=False, qargs=[]): if isinstance(key, str) and (key in qargs): return sorted(gpus, key=lambda d: d[key], reverse=reverse) if isinstance(key, type(lambda a: a)): return sorted(gpus, key=key, reverse=reverse) raise ValueError( "The argument 'key' must be a function or a key in query args,please read the documention of nvidia-smi") def auto_choice(self, mode="memory", num=1, env=False): ''' mode: 0:(default)sorted by free memory size return: a TF device object Auto choice the freest GPU device,not specified ones 自动选择最空闲GPU 多此一举,改成只memory,power memory power ''' for old_infos, new_infos in zip(self.gpus, query_gpu(self.qargs)): old_infos.update(new_infos) unspecified_gpus = [gpu for gpu in self.gpus if not gpu['specified']] or self.gpus # print(unspecified_gpus,self.gpus) if mode == "memory": print('Choosing the GPU device has largest free memory...') chosen_gpu = self._sort_by_memory(unspecified_gpus, True)[:num] elif mode == "power": print('Choosing the GPU device by power...') chosen_gpu = self._sort_by_power(unspecified_gpus)[:num] else: print('Given an unaviliable mode,will be chosen by memory') chosen_gpu = self._sort_by_memory(unspecified_gpus)[:num] for choose_ind in chosen_gpu: choose_ind["specified"] = True # print("nums", len(chosen_gpu)) indexs = [x['index'] for x in chosen_gpu] for one in range(len(indexs)): print('Using GPU {i}:\n{info}'.format(i=indexs[one], info='\n'.join( [str(k) + ':' + str(v) for k, v in chosen_gpu[one].items()]))) if not env: return ",".join(indexs) else: inds = ",".join(indexs) os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = inds print("Environment has been configured.") else: raise ImportError('GPU available check failed ') <file_sep>def write_list(data_list, save_path): """ 将list写入文本中,一个元素一行 :return: """ with open(save_path, 'w') as w: if data_list is None or len(data_list) == 0: return for data in data_list: w.write(str(data)) w.write('\n') def write_embedded_list(data_list, save_path, sep=' '): """ 将一个嵌套的list写入文本中,一行写入一个list,list的元素使用sep连接 :return: """ with open(save_path, 'w') as w: if data_list is None or len(data_list) == 0: return for embedded_list in data_list: w.write(sep.join(embedded_list)) w.write('\n') def read_to_list(data_path): with open(data_path, 'r') as file: data_list = file.readlines() data_list = [line.strip() for line in data_list] return data_list def read_to_embedded_list(data_path, sep=' '): with open(data_path, 'r') as file: data_list = file.readlines() data_list = [line.strip().split(sep) for line in data_list] return data_list <file_sep>""" 日志监控工具 """ import argparse import datetime as dt import json import logging import os import time import psutil from common_pyutil import log_util from common_pyutil.smtp_client import SMTPClient log_util.set_console_logger() parser = argparse.ArgumentParser(description='日志监控,需要使用sudo,不支持windows' '使用示例:task-watch --log /data1/train.log') config_example = {"mail_user": "<EMAIL>", "mail_password": "<PASSWORD>", "receiver": "<EMAIL>", 'mail_host': 'smtp.163.com', 'mail_port': 465} config_example = json.dumps(config_example) parser.add_argument('--log', type=str, default=None, help='监控目标日志路径') parser.add_argument('--mail_to', type=str, default=None, help='邮件接收人') parser.add_argument('--config', type=str, default='~/.task_watch.config', help='邮件配置文件路径,默认~/.task_watch.config,' '内容示例:{}' .format(config_example)) parser.add_argument('--interval', type=int, default=120, help='消息发送间隔(分钟),默认120') parser.add_argument('--lines', type=int, default=50, help='消息发送行数,默认50') parser.add_argument('--errors', type=str, nargs='*', default='Traceback', help='失败关键词,不区分大小写,支持多个,默认Traceback') parser.add_argument('--swap_kill_pids', type=int, nargs='*', help='如果导致swap,kill掉的进程,默认False') parser.add_argument('--swap_log_pids', type=int, default=0, help='是否使用监控日志关联的进程做swap监控') args = parser.parse_args() default_mail_config = {"mail_user": "<EMAIL>", "mail_password": "<PASSWORD>", 'mail_host': 'smtp.163.com', 'mail_port': 465} def search_log_pid(log_path): """ 找出和文件关联的进程 """ rel_pids = [] cur_pid = psutil.Process() cur_username = cur_pid.username() pid_list = psutil.pids() for pid in pid_list: p = psutil.Process(pid) if p.pid==cur_pid.pid: continue # 如果不是root,而且当前进程的用户不是当前用户,跳过 if cur_username != 'root' and p.username() != cur_username: continue file_list = p.open_files() for file in file_list: if os.path.samefile(file.path, log_path): rel_pids.append(pid) return list(set(rel_pids)) def get_pid_info(pids): pids_info = '' for pid in pids: p = psutil.Process(pid) cmd = ' '.join(p.cmdline()) pids_info = pids_info + f'pid:{pid},cmd:{cmd}\n' return pids_info def swap_kill(pids): swap_stats = psutil.swap_memory() if swap_stats.used > 0: for pid in pids: p = psutil.Process(pid) p.kill() return True return False def start_watch(): config_path = os.path.expanduser(args.config) if os.path.exists(config_path): with open(config_path) as file: config = json.load(file) else: logging.info('use default mail config') config = default_mail_config if args.mail_to: config['receiver'] = args.mail_to if not config.get('receiver'): raise EnvironmentError('没有邮件接收人') smtp_client = SMTPClient(config) if isinstance(args.errors, str): args.errors = [args.errors] error_words = [word.upper() for word in args.errors] if not os.path.exists(args.log): raise EnvironmentError('监控目标日志不存在,监控日志:{}'.format(args.log)) rel_pids = search_log_pid(args.log) swap_pids = [] if args.swap_kill_pids: swap_pids.extend(swap_pids) if args.swap_log_pids: swap_pids.extend(rel_pids) # 初始化消息通知 error_words_str = ','.join(error_words) rel_pids_info = get_pid_info(rel_pids) meta_msg = f'监控日志:{args.log} \n' \ f'监控日志关联进程信息: \n' \ f'{rel_pids_info}' \ f'监控时间间隔:{args.interval}分钟 \n' \ f'正常消息发送行数:{args.lines} \n' \ f'失败关键字:{error_words_str} \n' \ f'swap监控进程信息:\n' swap_info = '' if args.swap_kill_pids: kill_pids_info = get_pid_info(args.swap_kill_pids) swap_info = kill_pids_info if args.swap_kill_pids is None and args.swap_log_pids: swap_info += '日志关键进程的swap已经监控\n' if len(swap_info) == 0: swap_info = '无' meta_msg = meta_msg + swap_info + '\n' cur_p = psutil.Process() cur_username = cur_p.username() start_msg = f'监控开始\n' \ f'监控使用用户:{cur_username},请确保该用户对监控进程有控制权限\n' start_msg += meta_msg logging.info('监控开始:\n{}'.format(start_msg)) now_date_str=dt.datetime.now().strftime('%Y-%M-%d %H:%M:%S') smtp_client.send(now_date_str+' 监控开始', start_msg) is_finish = False log_file = open(args.log) pre_time = dt.datetime.now() cache_lines = [] while not is_finish: line = log_file.readline() if line: # 判断错误信息 line_upper = line.upper() for word in error_words: if word in line_upper: # 读取错误信息时,延时3秒确认错误信息以及输出 time.sleep(3) error_lines = [line] error_lines.extend(log_file.readlines()) error_msg = ''.join(error_lines) error_msg = meta_msg + '消息:\n' + error_msg logging.info('错误信息:\n{}'.format(error_msg)) now_date_str = dt.datetime.now().strftime('%Y-%M-%d %H:%M:%S') smtp_client.send(now_date_str+' 错误监控信息', error_msg) # 定时发送正常消息 cache_lines.append(line) if len(cache_lines) > args.lines: cache_lines.pop(0) now_time = dt.datetime.now() now_interval = (now_time - pre_time).days * 24 * 60 + (now_time - pre_time).seconds / 60 if now_interval > args.interval: info_msg = ''.join(cache_lines) info_msg = meta_msg + '消息:\n' + info_msg logging.info('正常监控信息:\n{}'.format(info_msg)) now_date_str = dt.datetime.now().strftime('%Y-%M-%d %H:%M:%S') smtp_client.send(now_date_str+' 正常监控信息', info_msg) pre_time = now_time if len(swap_pids) > 0: is_kill = swap_kill(swap_pids) if is_kill: kill_pids_info = get_pid_info(swap_pids) kill_msg = f'swap被占用,以下进程被kill\n' \ f'{kill_pids_info}\n' kill_msg = meta_msg + '消息:\n' + kill_msg logging.info('swap被占用:\n{}'.format(kill_msg)) now_date_str = dt.datetime.now().strftime('%Y-%M-%d %H:%M:%S') smtp_client.send(now_date_str+' swap被占用,进程被杀', kill_msg) else: if not rel_pids: is_finish = True time.sleep(60) rel_pids = search_log_pid(args.log) log_file.close() end_msg = '监控结束\n' + meta_msg now_date_str = dt.datetime.now().strftime('%Y-%M-%d %H:%M:%S') smtp_client.send(now_date_str+' 监控结束', end_msg) logging.info('监控结束:\n{}'.format(end_msg)) def mail_test(): config_path = os.path.expanduser(args.config) if os.path.exists(config_path): with open(config_path) as file: config = json.load(file) else: logging.info('use default mail config') config = default_mail_config if args.mail_to: config['receiver'] = args.mail_to if not config.get('receiver'): raise EnvironmentError('没有邮件接收人') print(config) smtp_client = SMTPClient(config) smtp_client.send('监控邮件测试', '监控邮件测试') if __name__ == '__main__': args = parser.parse_args('--mail_to 46484006<EMAIL>'.split()) mail_test() <file_sep>""" 任务计划工具 """ import argparse import datetime as dt import psutil import time import logging from common_pyutil import log_util log_util.set_console_logger() parser = argparse.ArgumentParser(description='定时任务,使用示例:task-plan -pid 154 --gpu_num 2' ' && your command') parser.add_argument('--pids', type=int, default=None, nargs=2, help='等待结束的进程,支持多个') parser.add_argument('--wait', type=int, default=None, help='等待的时长(分钟)') parser.add_argument('--date', default=None, help='指定日期启动,格式:yyyy-MM-dd-HH-mm') parser.add_argument('--time', default=None, help='指定时间启动,格式:HH-mm') parser.add_argument('--cpu_rate', type=float, default=0.8, help='cpu使用率低于的阈值,默认0.8') parser.add_argument('--cpu_memory', type=int, default=1024, help='cpu内存要求(M),默认1024') parser.add_argument('--gpu_num', type=int, default=1, help='gpu空闲数量,默认1') parser.add_argument('--gpu_memory', type=int, default=None, help='显存要求(M)') args = parser.parse_args() def start_plan(): logging.info('计划开始') # 初始化状态 pids = args.pids if pids is None: is_pids_ok = True else: is_pids_ok = False logging.info('pids:', str(pids)) wait_duration = args.wait start_time = dt.datetime.now() if wait_duration is None: is_wait_ok = True else: is_wait_ok = False logging.info('wait duration:{} minutes'.format(wait_duration)) wait_date = args.date if wait_date is None: is_date_ok = True else: is_date_ok = False wait_date_list = wait_date.split('-') wait_date_list = [int(x) for x in wait_date_list] wait_date = dt.datetime(*wait_date_list) logging.info('wait date:', str(wait_date)) wait_time = args.time if wait_date is None and wait_time is not None: is_time_ok = False wait_time_list = wait_time.split('-') wait_time_list = [int(x) for x in wait_time_list] wait_date = dt.datetime(start_time.year, start_time.month, start_time.day, *wait_time_list) logging.info('wait date:', str(wait_date)) else: is_time_ok = True cpu_rate = args.cpu_rate * 100 cur_cpu_rate = psutil.cpu_percent(interval=1) is_cpu_rate_ok = False logging.info('current cpu rate:{},request cpu rate:{}'.format(cur_cpu_rate, cpu_rate)) cpu_memory = args.cpu_memory mem_stats = psutil.virtual_memory() cur_cpu_memory = mem_stats.available / 1024 / 1024 is_cpu_memory_ok = False logging.info('request cpu memory:{},current cpu memory:{}'.format(cpu_memory, cur_cpu_memory)) gpu_num = args.gpu_num gpu_memory = args.gpu_memory is_gpu_ok = False if gpu_num > 0: from common_pyutil import gpu_manager is_contain_gpu=gpu_manager.check_gpus() if not is_contain_gpu: raise OSError('no gpu find') gpu_stats = gpu_manager.query_gpu_memory() logging.info('request gpu num:{},gpu memory:{},current gpu info:\n{}' .format(gpu_num, gpu_memory, str(gpu_stats))) # 循环判断状态 while not is_pids_ok or not is_wait_ok or not is_date_ok or not is_time_ok \ or not is_cpu_rate_ok or not is_cpu_memory_ok or not is_gpu_ok: if not is_pids_ok: all_running_pids = psutil.pids() running_pids = [pid for pid in pids if pid in all_running_pids] if len(running_pids) == 0: is_pids_ok = True logging.info('pids ok') now_time = dt.datetime.now() if not is_wait_ok: now_wait_time = (now_time - start_time) now_wait_duration = now_wait_time.days * 24 * 60 + now_wait_time.seconds / 60 if now_wait_duration > wait_duration: is_wait_ok = True logging.info('wait ok') if not is_date_ok or not is_time_ok: if now_time > wait_date: is_date_ok = True is_time_ok = True logging.info('date and time ok') cur_cpu_rate = psutil.cpu_percent(interval=0.2) if cur_cpu_rate <= cpu_rate: is_cpu_rate_ok = True else: is_cpu_rate_ok = False logging.info('current cpu rate:{},request cpu rate:{}'.format(cur_cpu_rate, cpu_rate)) mem_stats = psutil.virtual_memory() cur_cpu_memory = mem_stats.available / 1024 / 1024 if cur_cpu_memory >= cpu_memory: is_cpu_memory_ok = True else: is_cpu_memory_ok = False logging.info('request cpu memory:{},current cpu memory:{}'.format(cpu_memory, cur_cpu_memory)) is_gpu_ok = True if gpu_num > 0: from common_pyutil import gpu_manager gpu_stats = gpu_manager.query_gpu_memory() match_gpu_stats = [gpu_stat for gpu_stat in gpu_stats if gpu_memory is None or gpu_stat['memory.free'] >= gpu_memory] if len(match_gpu_stats) < gpu_num: is_gpu_ok = False logging.info('request gpu num:{},gpu memory:{},current gpu info:\n{}' .format(gpu_num, gpu_memory, str(gpu_stats))) if not is_pids_ok or not is_wait_ok or not is_date_ok or not is_time_ok \ or not is_cpu_rate_ok or not is_cpu_memory_ok or not is_gpu_ok: time.sleep(60) logging.info('计划结束') if __name__ == '__main__': start_plan() <file_sep>def is_chinese(uchar): """汉字""" if u'\u4e00' <= uchar <= u'\u9fa5': return True else: return False def is_number(uchar): """数字""" if u'\u0030' <= uchar <= u'\u0039': return True else: return False def is_alphabet(uchar): """英文字母""" if (u'\u0041' <= uchar <= u'\u005a') or (u'\u0061' <= uchar <= u'\u007a'): return True else: return False <file_sep>from multiprocessing.pool import Pool def map(fn, iter_data, pool_size=10): with Pool(pool_size) as pool: result = pool.map(fn, iter_data) return result <file_sep>name = "common_pyutil"
a79280ffd00f9dc302cfbf9f30f1247714c17ae2
[ "Markdown", "Python" ]
12
Python
kylinat2688/common_pyutil
f01ea483f084a97ee889fc89f9f147a9cb70baa8
bb62975f8030db7bc19c20d1740c2c6fb247835e
refs/heads/master
<repo_name>hexabitzinc/H1ARxx-Firmware<file_sep>/H1AR0/H1AR0.c /* BitzOS (BOS) V0.1.6 - Copyright (C) 2017-2019 Hexabitz All rights reserved File Name : H1AR0.c Description : Source code for module H1AR0. USB 2.0 - UART (FT230XQ) Required MCU resources : >> USARTs 1,2,3,5,6 for module ports. >> USART 4 for FT230XQ. */ /* Includes ------------------------------------------------------------------*/ #include "BOS.h" /* Define UART variables */ UART_HandleTypeDef huart1; UART_HandleTypeDef huart2; UART_HandleTypeDef huart3; UART_HandleTypeDef huart4; UART_HandleTypeDef huart5; UART_HandleTypeDef huart6; /* Module exported parameters ------------------------------------------------*/ module_param_t modParam[NUM_MODULE_PARAMS] = {{.paramPtr=NULL, .paramFormat=FMT_FLOAT, .paramName=""}}; /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Create CLI commands --------------------------------------------------------*/ /* ----------------------------------------------------------------------- | Private Functions | ----------------------------------------------------------------------- */ /* --- H1AR0 module initialization. */ void Module_Init(void) { /* Array ports */ MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_USART3_UART_Init(); MX_USART5_UART_Init(); MX_USART6_UART_Init(); /* USB port */ MX_USART4_UART_Init(); } /*-----------------------------------------------------------*/ /* --- H1AR0 message processing task. */ Module_Status Module_MessagingTask(uint16_t code, uint8_t port, uint8_t src, uint8_t dst) { Module_Status result = H1AR0_OK; switch (code) { default: result = H1AR0_ERR_UnknownMessage; break; } return result; } /*-----------------------------------------------------------*/ /* --- Register this module CLI Commands */ void RegisterModuleCLICommands(void) { } /*-----------------------------------------------------------*/ /* --- Get the port for a given UART. */ uint8_t GetPort(UART_HandleTypeDef *huart) { if (huart->Instance == USART2) return P1; else if (huart->Instance == USART6) return P2; else if (huart->Instance == USART3) return P3; else if (huart->Instance == USART1) return P4; else if (huart->Instance == USART5) return P5; else if (huart->Instance == USART4) return P6; return 0; } /* ----------------------------------------------------------------------- | APIs | ----------------------------------------------------------------------- */ /*-----------------------------------------------------------*/ /* ----------------------------------------------------------------------- | Commands | ----------------------------------------------------------------------- */ /*-----------------------------------------------------------*/ /************************ (C) COPYRIGHT HEXABITZ *****END OF FILE****/
288c8eb2db35a46a26fa7033ff8e0c1a1e6dead1
[ "C" ]
1
C
hexabitzinc/H1ARxx-Firmware
0606987ea691e36f6fcdb7d3ba8c4ff5da23abfe
ae28ab7ffecdc7743e5d240d86fa3aabdee7397a
refs/heads/master
<repo_name>LeeMinJii/c-mentoring<file_sep>/도서관리프로그램/student.h typedef struct stNode{ struct stNode* next; char stnum[20]; char passward[20]; char name[20]; }student; student* head; student* tail; student* member; void signUp(); void logIn(); void Freedata(); void node_print(); void st_InitNode(); void Import_studentData(); <file_sep>/도서관리프로그램/Manage_student.c #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> // #include "student.h" #include "book.h" void signUp(); void logIn(); void SuccessLogin_menu(); void StudentFreedata(); typedef struct stNode{ struct stNode* next; char stnum[20]; char passward[20]; char name[20]; }student; student* stHead; student* member; void myflush() { while(getchar() != '\n'); } void st_InitNode() { stHead = (student*)malloc(sizeof(student)); if (stHead == NULL) return; stHead->next = NULL; member = stHead->next; } //학생 정보 (리스트로) 가져오기 void Import_studentData() { FILE* stfp = fopen("student.txt", "r"); int ret = 0; while (1) { student* tmp = (student*)malloc(sizeof(student)); if (tmp == NULL) return; ret = fscanf(stfp, "%s %s %s", tmp->stnum, tmp->passward, tmp->name); if (ret == EOF) break; tmp->next = stHead->next; stHead->next = tmp; } fclose(stfp); } void Update_studentData() { //리스트에서 파일로 입력해주는 함수 FILE* fp = fopen("bk.txt", "w"); student* tmp = (student*)malloc(sizeof(student)); tmp = stHead->next; while (tmp != NULL) { fprintf(fp, "%s %s %s", tmp->stnum, tmp->passward, tmp->name); tmp = tmp->next; } fclose(fp); } int main() { int menu=0, m; FILE* stfp = fopen("student.txt", "w"); fclose(stfp); bk_init(); st_InitNode(); Import_studentData(); Book_load(); while (1) { printf("\n[도서관서비스]\n\ 1.회원가입\n\ 2.로그인\n\ 3.종료\n\ -----------------\n"); m = scanf("%d", &menu); if (menu == 1) signUp(); else if (menu == 2) logIn(); else if (menu == 3) { printf("===프로그램 종료==="); break; } } StudentFreedata(); return 0; } // 회원가입 void signUp() { int m; student* newstudent = (student*)malloc(sizeof(student)); if (newstudent == 0) return; printf("학번 : "); m=scanf("%s", newstudent->stnum); myflush(); printf("비밀번호 : "); m=scanf("%s", newstudent->passward);myflush(); printf("이름 : "); m=scanf("%s", newstudent->name);myflush(); newstudent->next = stHead->next; stHead->next = newstudent; Update_studentData(); } // 로그인 void logIn() { int m, loginError = 1, loginMenu; char studentNUM[20] = { 0 }, PW[20] = { 0 }, i=1; while (i){ member = stHead->next; printf("학번 : "); m = scanf("%s", studentNUM);myflush(); printf("비밀번호 : "); m = scanf("%s", PW);myflush(); printf("%s, %s\n", studentNUM, PW); /* 학번 = studentNUM, 비밀번호 = PW 로 입력 받음. member에 저장하는 부분없음 -> 계속 로그인 실패 do while 문을 사용하긴 했지만 그냥 while문 사용해되 될듯해 if - break 문이 있기 때문에 while 문에 조건을 안써도 됨. */ do { member = member->next; if (member == NULL) break; if (strcmp(studentNUM, member->stnum) == 0 && strcmp(PW, member->passward) == 0) { //학번 & 비번 일치 i = 0; loginError = 0; SuccessLogin_menu(); break; } else if (strcmp(studentNUM, "admin") == 0 && strcmp(PW, "<PASSWORD>") == 0) { //관리자 모드 i = 0; loginError = 0; Admin(); break; } else{ //학번 or 비번 일치X if (member->next != NULL) continue; } } while (member != NULL); // 로그인 실패시 if (loginError == 1) { printf("\ ERROR : 로그인 실패\n\ 1. 다시 로그인\n\ 2. 메인으로 돌아가기\n\ 3. 회원가입\n\ ---------------------------\n"); m = scanf("%d", &loginMenu); if (loginMenu == 1) continue; else if (loginMenu == 2) return; else if (loginMenu == 3) { signUp(); break; } } else if (loginError == 0) break; } } void SuccessLogin_menu() { int SLmenu, BookReturn; printf("\n\ [목록]\n\ 1. 도서 검색\n\ 2. 내 대여 목록\n\ 3. 회원 탈퇴\n\ 4. 로그아웃\n\ 5. 프로그램 종료\n"); scanf("%d", &SLmenu); if (SLmenu == 1) BookReturn = Find_book(); else if (SLmenu == 2) //내 대여 목록 찾는 함수 추가 ; else if (SLmenu == 3) //회원 탈퇴 함수 추가(대출 목록에 이름 있으면 불가, 삭제 후 txt파일 업데이트) Update_studentData(); else if (SLmenu == 4) return; else if (SLmenu == 5){ StudentFreedata(); exit(1); } } void StudentFreedata() { Update_studentData(); student* tmp; while (stHead->next != NULL) { tmp = stHead; if (tmp->next == NULL) free(tmp); else tmp = tmp->next; } free(stHead); } <file_sep>/도서관리프로그램/borrow.h typedef struct borrow{ int num; int isbn[10]; struct borrow* next; }borrow; borrow* br_head; borrow* br_tail; void borrow_init(); int confirm_stnum(); int confirm_isbn(); void add_borrowlist(); void save_borrow(); void delete_borrow();
ad366f922408ad4e3b54da5a18f18b35d9f4e58b
[ "C" ]
3
C
LeeMinJii/c-mentoring
3a7e1947e6671c4997330cb333109d61ec402c90
cb53dc95091640c1762fb7cc6d46ad75a330049c
refs/heads/master
<file_sep>document.writeln('hello world!') document.writeln("</br>");<file_sep>import { c24obj } from "./24"; console.log(c24obj)<file_sep>//对象 //原始的方式 var person = new Object(); person.name = "程序亦非猿"; person.age = 333; person.hi = function () { console.log("hi"); } //工厂方式 function createPerson() { var person = new Object(); person.name = "程序亦非猿"; person.age = 333; person.hi = function () { console.log("hi"); } return person; } //工厂方式 传递参数 function createPerson(name, age) { var person = new Object(); person.name = name; person.age = age; person.hi = function () { console.log("hi"); } return person; } //在外部定义方法 function hi() { console.log("hi" + this.name); } function createPerson(name, age) { var person = new Object(); person.name = name; person.age = age; person.hi = hi; return person; } //构造函数 function Person(name, age) { this.name = name; this.age = age; this.hi = function () { console.log("hi" + this.name); } } var cxyfy = new Person('程序亦非猿', 28); cxyfy.hi(); function Person() { } Person.prototype.name = '程序亦非猿'; Person.prototype.age = 12; Person.prototype.hi = function () { } //混合 function Person(name, age) { this.name = name; this.age = age; } Person.prototype.hi = function () { console.log("hi" + this.name); } //动态原型 function Person(name, age) { this.name = name; this.age = age; if (Person._initialized == 'undefined') { Person.prototype.hi = function () { console.log("hi" + this.name); }; }; Person._initialized = true; } //继承 function Person(name) { this.name = name; this.greeting = function () { console.log('hi im ' + this.name) } } function Man(name, age) { this.newMethod = Person; this.newMethod(name); delete this.newMethod; this.age = age; this.sayAge = function () { console.log(this.age); }; } var person1 = new Person('Fitz'); var person2 = new Man('程序亦非猿', 12); person1.greeting();//hi im Fitz person2.greeting();// hi im 程序亦非猿 person2.sayAge();//12 person2 instanceof Person//false person2 instanceof Man//true function greeting(name) { console.log('hi ' + name, ',im ' + this.myname) } var me = new Object(); me.myname = "程序亦非猿"; greeting.call(me, 'Fitz'); //apply 第二个参数是数组 greeting.apply(me, new Array('Fitz')); // function Person(){} // function Man(){} // Person.prototype = new Man() <file_sep>//Array 相关 var arr = [1, 2, 3]; arr.map(function (n) { return n + 1; })//[2,3,4] arr//[1,2,3] var arr2 = [1, 2, 3] arr2.forEach(function (n) { n = n * 2; }) arr2//[1,2,3] var out = []; [1, 2, 3].forEach(function (n) { this.push(n * 2); }, out); out//[2,4,6] var arr3 = [1,2,3] arr3.filter(function(n){ return n>1; })[2,3] [1,2,3,4,5].reduce(function(a,b){ return a+b; })//15 <file_sep> document.writeln('3.变量的解构赋值') document.writeln('</br>') let [a, b, c] = [1, 2, 3] document.writeln(a + ' ' + b + ' ' + c); let [, , third] = [1, 2, 3]; third //3 let [x, , y] = [1, 2, 3] x//1 y//3 let [head, ...tail] = [1, 2, 3, 4]; head//1 tail//[2,3,4] let [x, y, ...z] = [1]; x//1 y//undefined z//[] //也可以对 Set 解构 let [x, y, z] = new Set(['a', 'b', 'c']); x // "a" //默认值 let [foo = true] = []; foo//true function f() { console.log('aaa'); //不会被执行 } let [x = f()] = [1]; let { foo, bar } = { foo: 'aaa', bar: 'bbb' }; foo//'aaa' bar//'bbb' let { baz } = { foo: 'aaa', bar: 'bbb' }; baz // undefined const obj1 = {}; const obj2 = { foo: 'bar' }; Object.setPrototypeOf(obj1, obj2); const { foo } = obj1; foo // "bar" let { x = 3 } = {} x//3 let { x, y = 5 } = { x: 1 } x//1 y//5 var { x = 3 } = { x: undefined }; x // 3 var { x = 3 } = { x: null }; x // null let arr = [1, 2, 3] let { 0: first, [arr.length - 1]: last } = arr first//1 last//3 const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o" let { toString: s } = 123; s === Number.prototype.toString // true let { toString: s } = true; s === Boolean.prototype.toString // true //函数参数解构 function add([x, y]) { return x + y; } add([1, 2]);//3 function move({ x, y } = { x: 0, y: 0 }) { return [x, y]; } move({ x: 3, y: 8 });//[3,8] move({ x: 3 });//[3,undefined] move({});//[undefined,undefined] move();//[0,0] let x = 1; let y = 2; [x, y] = [y, x]; function example() { return [1, 2, 3] } let [a, b, c] = example(); function example2() { return { foo: 1, bar: 2 } } let { foo, bar } = example2(); const map = new Map(); map.set('first','hello'); map.set('second','world'); for(let [key,value] of map){ console.log(key + " is " + value); }<file_sep> document.writeln('</br>'); document.writeln('第二章'); document.writeln('</br>'); var flight={ airline: "Oceanic", number : 815, status : "good", departure: { IATA : "SYD", time : "2004-09-22 14:55", city: "Sydney" }, arrival : { IATA: "LAX", time: "2004-09-23 10:42", city: "Los Angeles" } } var status = flight.status || "unknown"; flight.equipment = { model: 'Boeing 777' } flight.status = 'overdue'; typeof flight.number //number typeof flight.status //string typeof flight.arrival //object typeof flight.manifest //undefined typeof flight.toString //function typeof flight.constructor //function flight.hasOwnProperty('number') //true flight.hasOwnProperty('constructor')//false var name; for (name in flight){ if(typeof flight[name] !=='function'){ document.writeln(name + ':'+flight[name]); } } document.writeln("</br>");<file_sep># 学习下 Web ## books books 目录下面是书籍里的代码。 - jsyyjc :《JavaScript 语言精粹》 - es6rm :《ECMAScript 6 入门》 - srreactjsz:《深入 React 技术栈》 - reactjjzl: 《React 进阶之路》, - srqc-react-and-redux:《深入浅出React和Redux》,用 create-react-app 创建的 - jsgjcxsj:《JavaScript 高级程序设计》第三版,mkdir 创建 ## jsjc JavaScript 教程,的练习代码 教程地址:https://wangdoc.com/javascript/stdlib/attributes.html ## react 学 react 的,代码都写在 html 的 script 标签里。 由于没有 webpack 配置,只能写简单的 react。 ## react-demo 学 react 的,但是是通过 create-react-app 创建的工程,拥有配套的环境,更加推荐。 ## react-tutorial 是用 create-react-app 创建的项目工程,方便用来学 react 官方教程的。 cd 到目录执行 npm start 可以查看效果。 教程地址:https://zh-hans.reactjs.org/tutorial/tutorial.html#setup-for-the-tutorial 官方 codepen :https://codepen.io/gaearon/pen/gWWZgR?editors=0010 ## react-router-demo 是用 create-react-app 创建的项目工程,用来学 react-router 的。 cd react-router-demo npm install react-router-dom ## projects projects 打算放仿写的项目 TODO ## ts 学习 ts 用的。 TODO ## 其他 其他目录比较杂 index.html :这个文件通常将包括你的主页内容,也就是说,人们第一次进入你的网页看到的文本和图像。 images 文件夹 :这个文件夹包含你网页上所有使用的图像。在 test-site 文件夹内创建一个 images 文件夹。 styles 文件夹 :这个文件夹包含了为你的内容添加样式的样式表(比如,设置文本颜色和背景颜色)。 scripts 文件夹 :这个文件夹包含了所有为你网页添加交互功能的 JavaScript 代码(比如点击时读取数据的按钮)。<file_sep>//第 8 章 document.writeln('</br>'); document.writeln('第八章'); document.writeln('</br>'); var a =['a','b','c']; var b = ['x','y','z']; var c = a.concat(b,true)//[a b c x y z true] document.writeln(c); document.writeln('</br>'); var a =['a','b','c']; a.push('d'); var c = a.join('-');//'a-b-c-d' 字符串 var a = ['a', 'b', 'c']; var b = ['x', 'y', 'z']; var d = a.push(b, true) //a=["a", "b", "c", Array(3), true] ; d=5 var digits = '0123456789' var a = digits.split('',5); <file_sep>//第七章 var factorial = function f(num) { if (num < 1) { return 1; } else { return num * f(num - 1); } } const result = factorial(4); console.log(result);//24 sayHi(); var sayHi = function () { console.log('Hi'); } //不要这样做! if (condition) { function sayHi() { alert("Hi!"); } } else { function sayHi() { alert("Yo!"); } } var sayHi; if (condition) { sayHi = function () { } } else { sayHi = function () { } }<file_sep>import CommonParent from './CommonParent' export default CommonParent;<file_sep>//Promise 对象 const promise = new Promise(function (resolve, reject) { if (true) { resolve(); } else { reject(); } })<file_sep>//async 函数 async function testAsync(){ const result1 = await stepOne(); const result = await stepTwo(result1); return result; } function stepOne(){ return new Promise(function(resolve,reject){ setTimeout(function () { console.log('stepOne') resolve(); }, 300) }) }; function stepTwo(){ return new Promise(function (resolve, reject) { setTimeout(function () { console.log('stepTwo') resolve('hello async'); }, 700) }) } testAsync().then(function(result){ console.log('then'); console.log(result); });<file_sep>//class 相关 functin Point(x, y) { this.x = x; this.y = y; }; Point.prototype.toString = function(){ return '(' + this.x + ',' + this.y + ')'; } //ES6 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ',' + this.y + ')'; } }<file_sep>//Symbol let s1 = Symbol(); let s2 = Symbol(); s1 === s2//false // 有参数的情况 let s1 = Symbol('foo'); let s2 = Symbol('foo'); s1 === s2 // false const sym = Symbol('foo'); sym.description;//'foo' let mySymbol = Symbol(); // 第一种写法 let a = {}; a[mySymbol] = 'Hello!'; // 第二种写法 let a = { [mySymbol]: 'Hello!' }; // 第三种写法 let a = {}; Object.defineProperty(a, mySymbol, { value: 'Hello!' }); // 以上写法都得到同样结果 a[mySymbol] // "Hello!"<file_sep>//对象的扩展 const foo = 'bar'; const baz = { foo }; console.log(baz);//{ foo: 'bar' } const obj = { method() { return '程序亦非猿'; } } // 等同于 const obj = { method: function () { return '程序亦非猿'; } } const cart2 = { _wheels: 4, get wheels() { console.log('get 被调用') return this._wheels; }, set wheels(value) { console.log('set 被调用') if (value < this._wheels) { throw new Error('数值太小了!'); } this._wheels = value; } } let propKey = 'foo'; let obj2 = { [propKey]:true,//foo:true } obj2.foo //true const proto = { foo : 'hello', } const obj3 = { foo : 'world', find(){ return super.foo;//hello } } Object.setPrototypeOf(obj3,proto); obj3.find()//hello let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; x // 1 y // 2 z // { a: 3, b: 4 }<file_sep> // import http from 'http'; var http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { // res.setHeader('Access-Control-Allow-Origin', 'null'); res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Headers", "content-type"); //跨域允许的请求方式 res.setHeader("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS"); res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); const result = [ { name: 'a', age: 1 }, { name: 'b', age: 2 }, { name: 'c', age: 3 }, ]; res.end(JSON.stringify(result)); }) server.listen(port, hostname, () => { console.log('server running at..') console.log('server running at http://%s:%s', hostname, port) })<file_sep>//Object 相关 var obj = { 'p': 'a', } Object.getOwnPropertyDescriptor(obj, 'p'); var obj = Object.defineProperties({}, { p1: { value: 1, writable: true, enumerable: false }, p2: { value: 'hello world', writable: true, enumerable: true }, p3: { enumerable: true, configurable: true, get: function () { return this.p1 + this.p2; } } }) Object.getOwnPropertyNames(obj)// ["p1", "p2"] <file_sep>import {firstName,isRich} from './23module' function printInfo(){ console.log(firstName+' is rich ?'+isRich); } printInfo(); <file_sep>//字符串的扩展 let name = '程序亦非猿'; let time = 'today'; var msg = `${time} ,${name} is awesome.` console.log(msg)//today ,程序亦非猿 is awesome. 'x'.repeat(3)//xxx 'hello'.repeat(2) // "hellohello" 'na'.repeat(0) // ""<file_sep> var c24obj = { name :"程序亦非猿", age: 18, } export { c24obj}<file_sep> document.writeln('</br>'); document.writeln('第七章'); document.writeln('</br>');<file_sep>//数组 function add(a,b){ return a+b; } add(...[1,2]);
15dd4647f54c6bd0da7f79a408fc51ec6c408e39
[ "JavaScript", "Markdown" ]
22
JavaScript
AlanCheen/HeadFirstWeb
fa0b93e6d5c5696bb1b51b365ee86b81efe82902
3a36e24299da0ea8f941d0a591af0986656f81ea
refs/heads/main
<file_sep># formula1 Aplicação que fornece um histórico de dados das corridas de Fórmula 1
acf8ed401192d9aea3390355575cc776cf00f7af
[ "Markdown" ]
1
Markdown
miguel-souza/formula1
b3eed22ade644b44f4b249cd0097e53ec96c379e
baaef7d0b4d93c2dfade23c7f5be97c5a0538774
refs/heads/master
<file_sep># Silex Search Service Provider [![Build Status](https://travis-ci.org/euskadi31/SearchServiceProvider.svg?branch=master)](https://travis-ci.org/euskadi31/SearchServiceProvider) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/942ec52e-ba58-478a-b212-36715220153b/mini.png)](https://insight.sensiolabs.com/projects/942ec52e-ba58-478a-b212-36715220153b) A Search Service Provider for Silex 2.0 ## Install Add `euskadi31/search-service-provider` to your `composer.json`: % php composer.phar require euskadi31/search-service-provider:~1.0 ## Usage ### Configuration ```php <?php $app = new Silex\Application; $app->register(new \Euskadi31\Silex\Provider\SearchServiceProvider); ``` ## License SearchServiceProvider is licensed under [the MIT license](LICENSE.md). <file_sep><?php /* * This file is part of the SearchServiceProvider. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Euskadi31\Silex\Provider; use Pimple\Container; use Pimple\ServiceProviderInterface; use Search\Engine\SearchInterface; use UnexpectedValueException; use InvalidArgumentException; /** * Search integration for Silex. * * @author <NAME> <<EMAIL>> */ class SearchServiceProvider implements ServiceProviderInterface { /** * {@inheritDoc} */ public function register(Container $app) { $app['search.options'] = [ 'engine' => '\Search\Engine\SphinxQL', 'cache' => [ 'driver' => '\Doctrine\Common\Cache\ArrayCache', 'life' => 0 ], 'server' => [ 'host' => 'localhost', 'port' => 9306 ] ]; $app['search'] = function($app) { $engineName = $app['search.options']['engine']; if (!class_exists($engineName)) { throw new InvalidArgumentException(sprintf( 'Engine "%s" not found.', $engineName )); } $search = new $engineName( $app['search.options']['server']['host'], $app['search.options']['server']['port'] ); if (!$search instanceof SearchInterface) { throw new UnexpectedValueException(sprintf( '"%s" does not implement \\Search\\Engine\\SearchInterface', get_class($search) )); } $search->setEventDispatcher($app['dispatcher']); if (isset($app['cache.factory'])) { $cacheFactory = $app['cache.factory']($app['search.options']['cache']); $search->setCache($cacheFactory()); } return $search; }; } } <file_sep><?php /* * This file is part of the SearchServiceProvider. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Euskadi31\Silex\Provider; use Euskadi31\Silex\Provider\SearchServiceProvider; use Euskadi31\Silex\Provider\CacheServiceProvider; use Silex\Application; class SearchProviderTest extends \PHPUnit_Framework_TestCase { public function testRegister() { $app = new Application(['debug' => true]); $app->register(new SearchServiceProvider()); $this->assertTrue(isset($app['search.options'])); $this->assertEquals('\Search\Engine\SphinxQL', $app['search.options']['engine']); $this->assertEquals('\Doctrine\Common\Cache\ArrayCache', $app['search.options']['cache']['driver']); $this->assertEquals(0, $app['search.options']['cache']['life']); $this->assertEquals('localhost', $app['search.options']['server']['host']); $this->assertEquals(9306, $app['search.options']['server']['port']); $this->assertInstanceOf('Search\Engine\SphinxQL', $app['search']); } public function testRegisterWithCache() { $app = new Application(['debug' => true]); $app->register(new CacheServiceProvider()); $app->register(new SearchServiceProvider()); $this->assertTrue(isset($app['search.options'])); $this->assertEquals('\Search\Engine\SphinxQL', $app['search.options']['engine']); $this->assertEquals('\Doctrine\Common\Cache\ArrayCache', $app['search.options']['cache']['driver']); $this->assertEquals(0, $app['search.options']['cache']['life']); $this->assertEquals('localhost', $app['search.options']['server']['host']); $this->assertEquals(9306, $app['search.options']['server']['port']); $this->assertInstanceOf('Search\Engine\SphinxQL', $app['search']); $this->assertInstanceOf('\Doctrine\Common\Cache\Cache', $app['search']->getCache()); } /** * @expectedException UnexpectedValueException */ public function testBadEngineClassName() { $app = new Application(); $app->register(new SearchServiceProvider(), [ 'search.options' => [ 'engine' => '\\stdClass' ] ]); $app['search']; } /** * @expectedException InvalidArgumentException */ public function testBadEngine() { $app = new Application(); $app->register(new SearchServiceProvider, [ 'search.options' => [ 'engine' => 'foo' ] ]); $app['search']; } }
71fbf9e0ef3137e249d439a469baa52c1f4e5e91
[ "Markdown", "PHP" ]
3
Markdown
euskadi31/SearchServiceProvider
27731d5756d8442ff8e22c682f34c8f7da04b238
7273b25cf2005d199d08ba44b80942b0bd66bb71