static async Task RunAsync() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:4810//"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP POST var command = new Command() { Id = Guid.NewGuid(), Name = "My Name is Pepper" }; HttpResponseMessage response = await client.PostAsJsonAsync("api/command", command); if (response.IsSuccessStatusCode) { Console.WriteLine("Sucsesfully posted a command"); } } }
private async static void Process() { //获取当前联系人列表 HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); IEnumerable<Contact> contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); Console.WriteLine("当前联系人列表:"); ListContacts(contacts); //添加新的联系人 Contact contact = new Contact { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "*****@*****.**" }; await httpClient.PostAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts", contact); Console.WriteLine("添加新联系人“王五”:"); response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); ListContacts(contacts); //修改现有的某个联系人 response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts/001"); contact = (await response.Content.ReadAsAsync<IEnumerable<Contact>>()).First(); contact.Name = "赵六"; contact.EmailAddress = "*****@*****.**"; await httpClient.PutAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts/001", contact); Console.WriteLine("修改联系人“001”信息:"); response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); ListContacts(contacts); //删除现有的某个联系人 await httpClient.DeleteAsync("http://localhost/selfhost/api/contacts/002"); Console.WriteLine("删除联系人“002”:"); response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); ListContacts(contacts); }
static async Task InvokeRequestResponseService() { using (var client = new HttpClient()) { var scoreRequest = new { Inputs = new Dictionary<string, StringTable>() { { "input1", new StringTable() { ColumnNames = new string[] {"Title", "Category", "Text"}, Values = new string[,] { { "Apple Inc.", "Information Technology", "nasdaq 100 component s p 500 component foundation founder location city apple campus 1 infinite loop street infinite loop cupertino california cupertino california location country united states u s locations 406 retail stores may 2013 area served worldwide key people ref tim cook ceo steve jobs founder former ceo industry products services market capitalization 446b operating income us 48 999 nbsp billion 2013 subsid homepage apple inc is an american multinational corporation headquartered in cupertino california cupertino california that designs develops and sells consumer electronics computer software and personal computers its best known hardware products are the macintosh mac line of computers the ipod mobile digital media player media player the iphone smartphone and the ipad tablet computer its consumer software includes the os x and ios operating systems the itunes media browser the safari web browser safari web browser and the ilife and iwork creativity and productivity suites apple was founded by steve jobs steve wozniak and ronald wayne on april 1 1976 to develop and sell personal computers it was incorporated as apple computer inc on january 3 1977 and was renamed as apple inc on january 9 2007 to reflect its shifted focus towards consumer electronics apple is the list of the largest information technology companies world s second largest information technology company by revenue after samsung electronics and the mobile phone manufacturers world s third largest mobile phone maker after samsung telecommunications samsung and nokia fortune magazine fortune magazine named apple the most admired company in the united states in 2008 and in the world from 2008 to 2012 on september 30 2013 apple surpassed coca cola to become the world s most valuable brand in the omnicom group s best global brands report however the company has received criticism of apple inc criticism for its contractors labor practices and for apple s own environmental and business practices as of may 2013 apple maintains 408 apple store retail stores in fourteen countries as well as the online apple store online apple store and itunes store the latter of which is the world s largest music retailer apple is the list of corporations by market capitalization largest publicly traded corporation in the world by market capitalization with an estimated market capitalization of 446 billion by january 2014 as of september 29 2012 the company had 72 800 permanent full time employees and 3 300 temporary full time employees worldwide its worldwide annual revenue in 2013 totalled 170 billion as of q1 2014 apple s five year growth average is 39 for top line top line growth and 45 for bottom line bottom line growth in may 2013 apple entered the top ten of the fortune 500 list of companies for the first time rising 11 places above its 2012 ranking to take the sixth position apple is the most successful startup company of all time by market capitalization revenue and growth history 1976 80 founding and incorporation file apple i jpg thumb right the apple i apple s first product was sold as an assembled circuit board and lacked basic features such as a keyboard monitor and case the owner of this unit added a keyboard and a wooden case apple was established on april 1 1976 by steve jobs steve wozniak and ronald wayne to sell the apple i personal computer kit a computer single handedly designed by wozniak the kits were hand built by wozniak and first shown to the public at the homebrew computer club the apple i was sold as a motherboard with cpu ram and basic textual video chips which is less than what is today considered a complete personal computer the apple i went on sale in july 1976 and was market priced at 666 66 in dollars adjusted for inflation apple was incorporated january 3 1977 without wayne who sold his share of the company back to jobs and wozniak for us 800 during the first five years of operations revenues doubled every four months an average growth rate of 700 the apple ii series apple ii also invented by wozniak was introduced on april 16 1977 at the first west coast computer faire it differed from its major rivals the trs 80 and commodore pet due to its character cell based color graphics and an open architecture open computer architecture architecture while early models used ordinary cassette tapes as storage devices they were superseded by the introduction of a 5 nbsp 1 4 nbsp inch floppy disk drive and interface the disk ii the apple ii was chosen to be the desktop platform for the first killer application killer app of the business world visicalc a spreadsheet computer program program visicalc created a business market for the apple ii and gave home users compatibility with the office an additional reason to buy an apple ii by the end of the 1970s apple had a staff of computer designers and a production line the company introduced the apple iii in may 1980 in an attempt to compete with ibm and microsoft in the business and corporate computing market jobs and several apple employees including jef raskin visited xerox parc in december 1979 to see the xerox alto xerox granted apple engineers three days of access to the parc facilities in return for the option to buy 100 000 shares 800 000 split adjusted shares of apple at the pre ipo price of 10 a share jobs was immediately convinced that all future computers would use a graphical user interface gui and development of a gui began for the apple lisa on december 12 1980 apple went public at 22 per share generating more capital than any ipo since ford motor company in 1956 and instantly creating more millionaires about 300 than any company in history 1981 89 success with macintosh file ad apple 1984 jpg left thumb apple s 1984 television commercial 1984 television ad set in a dystopian future modeled after the george orwell novel nineteen eighty four set the tone for the introduction of the macintosh apple began working on the apple lisa in 1978 in 1982 jobs was pushed from the lisa team due to infighting jobs took over jef raskin s low cost computer project the macintosh a race broke out between the lisa team and the macintosh team over which product would ship first lisa won the race in 1983 and became the first personal computer sold to the public with a gui but was a commercial failure due to its high price tag and limited software titles file macintosh 128k transparency png thumb the first macintosh released in 1984 in 1984 apple next launched the macintosh its debut was announced by the now famous 1 5 million 1984 television commercial television commercial 1984 it was directed by ridley scott and was aired during the third quarter of super bowl xviii on january 22 1984 it is now hailed as a watershed event for apple s success and a masterpiece the macintosh initially sold well but follow up sales were not strong due to its high price and limited range of software titles the macintosh was the first personal computer to be sold without a programming language at all the machine s fortunes changed with the introduction of the laserwriter the first postscript laser printer to be sold at a reasonable price and pagemaker an early desktop publishing package it has been suggested that the combination of these three products was responsible for the creation of the desktop publishing market the mac was particularly powerful in the desktop publishing market due to its advanced graphics capabilities which had necessarily been built in to create the intuitive macintosh gui in 1985 a power struggle developed between jobs and ceo john sculley who had been hired two years earlier the apple board of directors instructed sculley to contain jobs and limit his ability to launch expensive forays into untested products rather than submit to sculley s direction jobs attempted to oust him from his leadership role at apple sculley found out that jobs had been attempting to organize a coup and called a board meeting at which apple s board of directors sided with sculley and removed jobs from his managerial duties file macintosh portable jpg thumb the macintosh portable was apple s first portable macintosh computer released in 1989 the macintosh portable was introduced in 1989 and was designed to be just as powerful as a desktop macintosh but weighed a bulky with a 12 hour battery life after the macintosh portable apple introduced the powerbook in 1991 the same year apple introduced system 7 a major upgrade to the operating system which added color to the interface and introduced new networking capabilities it remained the architectural basis for mac os until 2001 the success of the powerbook and other products brought increasing revenue 1990 99 decline and restructuring during this time apple experimented with a number of other failed consumer targeted products including quicktake digital cameras powercd portable cd audio players appledesign powered speakers speakers bandai pippin video consoles and apple interactive television box tv appliances enormous resources were also invested in the problem plagued newton platform newton division based on john sculley s unrealistic market forecasts ultimately none of these products helped as apple s market share and stock prices continued to slide apple saw the apple ii series as too expensive to produce while taking away sales from the low end macintosh in 1990 apple released the macintosh lc with a single expansion slot for the apple iie card to migrate apple ii users to the macintosh platform apple relied on high profit margins and never developed a clear response instead they sued microsoft for using a graphical user interface similar to the apple lisa in apple computer inc v microsoft corporation the lawsuit dragged on for years before it was finally dismissed at the same time a series of major product flops and missed deadlines sullied apple s reputation and sculley was replaced as ceo by michael spindler file newton img 0320 cleanup jpg thumb right the newton platform newton was apple s first foray into the personal digital assistant pda markets as well as one of the first in the industry despite being a financial flop at the time of its release it helped pave the way for the palm pilot and apple s own iphone and ipad in the future by the early 1990s apple was developing alternative platforms to the macintosh such as the a ux apple had also begun to experiment in providing a mac only online portal which they called eworld developed in collaboration with america online and designed as a mac friendly alternative to other online services such as compuserve the macintosh platform was itself becoming outdated because it was not built for multitasking and several important software routines were programmed directly into the hardware in addition apple was facing competition from os 2 and unix vendors such as sun microsystems the macintosh would need to be replaced by a new platform or reworked to run on more powerful hardware in 1994 apple allied with ibm and motorola in the aim alliance the goal was to create a new computing platform the powerpc reference platform which would use ibm and motorola hardware coupled with apple s software the aim alliance hoped that prep s performance and apple s software would leave the pc far behind thus countering microsoft the same year apple introduced the power macintosh the first of many apple computers to use motorola s powerpc processor in 1996 michael spindler was replaced by gil amelio as ceo gil amelio made many changes at apple including extensive layoffs after numerous failed attempts to improve mac os first with the taligent project then later with copland operating system copland and gershwin operating system gershwin amelio chose to purchase next and its nextstep operating system bringing steve jobs back to apple as an advisor on july 9 1997 gil amelio was ousted by the board of directors after overseeing a three year record low stock price and crippling financial losses jobs became the interim ceo and began restructuring the company s product line at the 1997 macworld expo steve jobs announced that apple would join microsoft to release new versions of microsoft office for the macintosh and that microsoft made a 150 million investment in non voting apple stock on november 10 1997 apple introduced the apple store online apple online store tied to a new build to order manufacturing strategy on august 15 1998 apple introduced a new all in one computer reminiscent of the macintosh 128k the imac the imac design team was led by jonathan ive who would later design the ipod and the iphone the imac featured modern technology and a unique design and sold almost 800 000 units in its first five months through this period apple purchased several companies to create a portfolio of professional and consumer oriented digital production software in 1998 apple announced the purchase of macromedia s final cut pro final cut software signaling its expansion into the digital video editing market the following year apple released two video editing products imovie for consumers and for professionals final cut pro which has gone on to be a significant video editing program with 800 000 registered users in early 2007 in 2002 apple purchased nothing real for their advanced digital compositing application shake software shake as well as emagic for their music productivity application logic pro logic which led to the development of their consumer level garageband application iphoto s release the same year completed the ilife suite 2000 06 return to profitability file apple store north michigan ave chicago il 2005 10 22 rotated jpg thumb apple retail stores allow potential customers to use floor models without making a purchase br apple store north michigan avenue chicago illinois in 2005 mac os x based on next s openstep and bsd unix was released on march 24 2001 after several years of development aimed at consumers and professionals alike mac os x aimed to combine the stability reliability and security of unix with the ease of use afforded by an overhauled user interface to aid users in migrating from mac os 9 the new operating system allowed the use of os 9 applications through mac os x s classic mac os x classic environment on may 19 2001 apple opened the first official apple store retail apple retail stores in virginia and california on july 9 they bought spruce technologies a dvd authoring company on october 23 of the same year apple announced the ipod portable digital audio player and started selling it on november 10 the product was phenomenally successful nbsp over 100 million units were sold within six years in 2003 apple s itunes store was introduced offering online music downloads for 0 99 a song and integration with the ipod the service quickly became the market leader in online music services with over 5 billion downloads by june 19 2008 since 2001 apple s design team has progressively abandoned the use of translucent colored plastics first used in the imac g3 this began with the titanium powerbook and was followed by the white polycarbonate ibook and the flat panel imac file macbook pro jpg thumb the macbook pro apple s first laptop with an intel microprocessor announced in january 2006 at the worldwide developers conference keynote address on june 6 2005 steve jobs announced that apple would begin producing intel based mac computers in 2006 on january 10 2006 the new macbook pro and imac became the first apple computers to use intel s core duo cpu by august 7 2006 apple had transitioned the entire mac product line to intel chips over one year sooner than announced on april 29 2009 the wall street journal reported that apple was building its own team of engineers to design microchips apple introduced boot camp software boot camp to help users install windows xp or windows vista on their intel macs alongside mac os x apple s success during this period was evident in its stock price between early 2003 and 2006 the price of apple s stock increased more than tenfold from around 6 per share split adjusted to over 80 in january 2006 apple s market cap surpassed that of dell nine years prior dell s ceo michael dell said that if he ran apple he would shut it down and give the money back to the shareholders although apple s market share in computers had grown it remained far behind competitors using microsoft windows with only about 8 of desktops and laptops in the us 2007 10 success with mobile devices apple achieved widespread success with its iphone ipod touch and ipad products which introduced innovations in mobile phones portable music players and personal computers respectively in addition the implementation of a store for the purchase of software applications represented a new business model touch screens had been invented and seen in mobile devices before but apple was the first to achieve mass market adoption of such a user interface that included particular pre programmed touch gestures delivering his keynote speech at the macworld expo on january 9 2007 jobs announced that apple computer inc would from that point on be known as apple inc because computers were no longer the main focus of the company which had shifted its emphasis to mobile electronic devices the event also saw the announcement of the iphone and the apple tv the following day apple shares hit 97 80 an all time high at that point in may apple s share price passed the 100 mark in an article posted on apple s website on february 6 2007 steve jobs wrote that apple would be willing to sell music on the itunes store without digital rights management drm which would allow tracks to be played on third party players if record labels would agree to drop the technology on april 2 2007 apple and emi jointly announced the removal of drm technology from emi s catalog in the itunes store effective in may other record labels followed later that year in july of the following year apple launched the app store ios app store to sell third party applications for the iphone and ipod touch within a month the store sold 60 million applications and brought in 1 million daily on average with jobs speculating that the app store could become a billion dollar business for apple three months later it was announced that apple had become the third largest mobile handset supplier in the world due to the popularity of the iphone on december 16 2008 apple announced that after over 20 years of attending macworld 2009 would be the last year apple would be attending the macworld expo and that philip w schiller phil schiller would deliver the 2009 keynote in lieu of the expected jobs almost exactly one month later on january 14 2009 an internal apple memo from jobs announced that he would be taking a six month leave of absence until the end of june 2009 to allow him to better focus on his health and to allow the company to better focus on its products without having the rampant media speculating about his health despite jobs s absence apple recorded its best non holiday quarter q1 fy 2009 during the late 2000s recession recession with a revenue of 8 16 billion and a profit of 1 21 billion after years of speculation and multiple rumored leaks apple announced a large screen tablet like media device known as the ipad on january 27 2010 the ipad runs the same touch based operating system that the iphone uses and many of the same iphone apps are compatible with the ipad this gave the ipad a large app catalog on launch even with very little development time before the release later that year on april 3 2010 the ipad was launched in the us and sold more than 300 000 units on that day reaching 500 000 by the end of the first week in may of the same year apple s market cap exceeded that of competitor microsoft for the first time since 1989 apple released the iphone 4 which introduced video calling computer multitasking multitasking and a new electrical insulation uninsulated stainless steel design which acts as the phone s antenna because of this antenna implementation some iphone 4 users reported a reduction in signal strength when the phone is held in specific ways after a large amount of media coverage including mainstream news organizations apple held a press conference where they offered buyers a free rubber bumper case which had been proven to eliminate the signal reduction issue later that year apple again refreshed its ipod line of mp3 players which introduced a multi touch ipod nano ipod touch with facetime and ipod shuffle with buttons which brought back the buttons of earlier generations in october 2010 apple shares hit an all time high eclipsing 300 additionally on october 20 apple updated their macbook air laptop ilife suite of applications and unveiled mac os x lion the last version with the name mac os x on january 6 2011 the company opened their mac app store a digital software distribution platform similar to the existing ios app store apple was featured in the documentary something ventured film something ventured which premiered in 2011 2011 12 steve jobs s death file apple store yonkers ny january 8 2013 jpg thumb apple store in yonkers new york on january 17 2011 jobs announced in an internal apple memo that he would take another medical leave of absence for an indefinite period to allow him to focus on his health chief operating officer tim cook assumed jobs s day to day operations at apple although jobs would still remain involved in major strategic decisions for the company apple became the most valuable consumer facing brand in the world in june 2011 steve jobs surprisingly took the stage and unveiled icloud an online storage and syncing service for music photos files and software which replaced mobileme apple s previous attempt at content syncing this would be the last product launch jobs would attend before his death it has been argued that apple has achieved such efficiency in its supply chain that the company operates as a monopsony one buyer many sellers in that it can dictate terms to its suppliers in july 2011 due to the united states debt ceiling crisis of 2011 american debt ceiling crisis apple s financial reserves were briefly larger than those of the federal government of the united states u s government on august 24 2011 jobs resigned his position as ceo of apple he was replaced by tim cook and jobs became apple s chairman prior to this apple did not have a chairman and instead had two co lead directors andrea jung and arthur d levinson who continued with those titles until levinson became chairman of the board in november on october 4 2011 apple announced the iphone 4s which included an improved camera with 1080p video recording a dual core a5 chip capable of 7 times faster graphics than the a4 an intelligent software assistant named siri and cloud sourced data with icloud the iphone 4s was officially released on october 14 2011 on october 5 2011 apple announced that jobs had died marking the end of an era for apple inc on october 29 2011 apple purchased c3 technologies a mapping company for 240 million becoming the third mapping company apple has purchased on january 10 2012 apple paid 500 million to acquire anobit an israeli hardware company that developed and supplies a proprietary memory signal processing technology that improves the performance of flash memory used in iphones and ipads on january 19 2012 apple s phil schiller introduced ibooks textbooks for ios and ibook author for mac os x in new york city this was the first major announcement by apple since the passing of steve jobs who stated in his biography that he wanted to reinvent the textbook and education the ipad third generation third generation ipad was announced on march 7 2012 it includes a retina display a new cpu a five megapixel camera and 1080p video recording on july 24 2012 during a conference call with investors tim cook said that he loved india but that apple was going to expect larger opportunities outside of india citing the reason as the 30 sourcing requirement from india on august 20 2012 apple s rising stock rose the company s value to a world record 624 billion this beat the non inflation adjusted record for market capitalization set by microsoft in 1999 on august 24 2012 a us jury ruled that samsung should pay apple 1 05 billion 665m in damages in an intellectual property lawsuit samsung said they will appeal the court ruling samsung subsequently prevailed on its motion to vacate this damages award which the court reduced by 450 million the court further granted samsung s request for a new trial it was made available on september 21 2012 and became apple s biggest iphone launch with over 2 million pre orders pushing back the delivery date to late october on october 23 2012 apple unveiled the ipad mini which features a 7 9 inch screen in contrast to the ipad s 9 7 inch screen apple also released a third generation 13 inch macbook pro with a retina display the ipad fourth generation fourth generation ipad featuring a faster processor and a lightning dock connector after the launch of apple s ipad mini and fourth generation ipad on november 3 2012 apple announced that they had sold 3 million ipads in three days of the launch but it did not mention the sales figures of specific ipad models on november 10 2012 apple confirmed a global settlement that would dismiss all lawsuits between apple and htc up to that date in favor of a ten year license agreement for current and future patents between the two companies it is predicted that apple will make 280 million a year from this deal with htc in december 2012 in a tv interview for nbc s rock center with brian williams rock center and also aired on the today u s tv program today morning show apple ceo tim cook said that in 2013 the company will produce one of its existing lines of mac computers in the united states in january 2013 cook stated that he expected china to overtake the us as apple s biggest market 2013 present acquisitions and expansions in march 2013 apple announced a patent for an augmented reality ar system that can identify objects in a live video stream and present information corresponding to these objects through a computer generated information layer overlaid on top of the real world image at the worldwide developer s conference on june 10 2013 apple announced the ios 7 seventh ios operating system alongside os x mavericks the tenth version of mac os x and a new internet radio service called itunes radio ios 7 and os x mavericks are both expected to be released during fall 2013 on july 2 2013 apple announced the recruitment of paul deneve belgian president and ceo of yves saint laurent brand yves saint laurent to apple s top ranks a spokesperson for the company stated we re thrilled to welcome paul deneve to apple he ll be working on special projects as a vice president reporting directly to tim cook alongside google vice president vint cerf and at t ceo randall stephenson cook attended a closed door summit held by president obama on august 8 2013 in regard to government surveillance and the internet in the wake of the edward snowden 2013 mass surveillance disclosures nsa incident a report on august 22 2013 confirmed that apple acquired embark inc a small silicon valley based mapping company embark builds free transit apps to help smartphone users navigate public transportation in u s cities such as new york san francisco and chicago following the confirmation of the acquisition an apple spokesperson explained apple buys smaller technology companies from time to time and we generally do not discuss our purpose or plans in november 2012 embark claimed that over 500 000 people used its apps an anonymous apple employee revealed to the bloomberg media publication that the opening of a tokyo japan store is planned for 2014 the construction of the store will be completed in february 2014 but as of august 29 2013 takashi takebayashi a tokyo based spokesman for apple has not made any comment to the media a japanese analyst has stated for apple the japanese market is appealing in terms of quantity and price there is room to expand tablet sales and a possibility the japanese market expands if apple s mobile carrier partners increase on october 1 2013 apple india executives unveiled a plan to expand further into the indian market following cook s acknowledgment of the country in july 2013 when sales results showed that iphone sales in india grew 400 during the second quarter of 2013 in attendance at the confidential meeting were 20 ceos and senior executives from telecom and electronic retail companies a mid october 2013 announcement revealed that burberry executive angela ahrendts will commence as a senior vice president at apple in mid 2014 ahrendts oversaw burberry s digital strategy for almost eight years and during her tenure sales increased to about us 3 2 billion 2 billion pounds and shares gained more than threefold in a company wide memo sent on the morning of october 15 2013 cook explained the decision to hire ahrendts blockquote she ahrendts shares our values and our focus on innovation she places the same strong emphasis as we do on the customer experience she cares deeply about people and embraces our view that our most important resource and our soul is our people she believes in enriching the lives of others and she is wicked smart blockquote on november 24 2013 apple inc confirmed the purchase of primesense an israeli 3d sensing company based in tel aviv in december 2013 apple inc purchased social analytics firm topsy one of a small number of firms with real time access to the messages that appear on twitter every tweet published since 2006 is within its scope debra aho williamson an analyst with emarketer inc explained a key point is they are one of the few companies that has access to the twitter fire hose and can do real time analysis of the trends and discussions happening on twitter while an exact amount is still unknown the deal was apparently worth more than us 200 million according to people with knowledge of the secret deal and apple spokespeople have refused to disclose the purpose of the acquisition on december 6 2013 apple inc launched ibeacon technology across its 254 u s retail stores using bluetooth wireless technology ibeacon senses the user s exact location within the apple store and sends the user messages about products events and other information tailored to the user s location ibeacon works as long as the user has downloaded the apple store app and has given apple permission to track them products mac file macbook air black jpg thumb macbook air macbook air consumer ultra thin ultra portable notebook introduced in 2008 macbook pro professional notebook introduced in 2006 mac mini consumer sub desktop computer and server introduced in 2005 imac consumer all in one desktop computer introduced in 1998 mac pro workstation desktop computer introduced in 2006 apple sells a variety of computer accessories for macs including apple thunderbolt display thunderbolt display magic mouse magic trackpad apple wireless keyboard wireless keyboard apple battery charger battery charger the airport wireless networking products and apple time capsule time capsule ipad on january 27 2010 apple introduced their much anticipated media tablet computer tablet the ipad running a modified version of ios it offers multi touch interaction with multimedia formats including newspapers magazines ebooks textbooks photos movies videos of tv shows music word processing documents spreadsheets videogames and most existing iphone apps it also includes a mobile version of safari web browser safari for web browsing as well as access to the app store itunes library ibookstore contacts and notepad content is downloadable via wi fi and optional 3g service or synced through the user s computer at t inc at t was initially the sole us provider of 3g wireless access for the ipad on march 2 2011 apple introduced the ipad 2 which had a faster processor and a camera on the front and back it also added support for optional 3g service provided by verizon wireless verizon in addition to the existing offering by at t inc at t however the availability of the ipad 2 has been limited as a result of the devastating earthquake and ensuing tsunami in japan in march 2011 on march 7 2012 apple introduced the third generation ipad marketed as ipad third generation the new ipad it added 3gpp long term evolution lte service from at t or verizon the upgraded a5x processor and the retina display 2048 by 1536 resolution originally implemented on the iphone 4 and iphone 4s the dimensions and form factor remained relatively unchanged with the new ipad being a fraction thicker and heavier than the previous version and minor positioning changes on october 23 2012 apple s fourth generation ipad came out marketed as the ipad fourth generation ipad with retina display it added the upgraded a6x processor and replaced the traditional 30 pin dock connector with the all digital lightning connector the ipad mini was also introduced with a reduced 7 9 inch display and featuring much of the same internal specifications as the ipad 2 on october 22 2013 apple introduced the ipad air it added the new 64 bit apple a7 processor the ipad mini with retina display was also introduced featuring the apple a7 processor as well since its launch ipad users have downloaded three billion apps while the total number of app store downloads is over 25 billion ipod file ipod family png thumb the 2012 ipod shuffle ipod nano ipod classic and ipod touch on october 23 2001 apple introduced the ipod digital music player several updated models have since been introduced and the ipod brand is now the market leader in portable music players by a significant margin with more than 350 million units shipped apple has partnered with nike inc nike to offer the nike ipod sports kit enabling runners to synchronize and monitor their runs with itunes and the nike website apple currently sells four variants of the ipod ipod shuffle ultra portable digital audio player currently available in a 2 nbsp gb model introduced in 2005 ipod nano portable media player currently available in a 16 nbsp gb model introduced in 2005 earlier models featured the traditional ipod click wheel though the current generation features a multi touch interface and includes an fm radio and a pedometer ipod touch portable media player than runs ios currently available in 16 32 and 64 nbsp gb models introduced in 2007 the current generation which released on september 12 2012 features the apple a5 processor a retina display and dual cameras on the front 1 2 megapixel sensor and back 5 megapixel isight the latter of which supports hd video recording at 1080p and siri ipod classic portable media player currently available in a 160 nbsp gb model first introduced in 2001 iphone file iphone montage png thumb 150px the iphone first generation first generation iphone iphone 3g 3g iphone 4 4 iphone 5 5 iphone 5c 5c and iphone 5s 5s to scale at the macworld conference expo in january 2007 steve jobs introduced the long anticipated iphone a convergence of an internet enabled smartphone and ipod the iphone first generation first generation iphone was released on june 29 2007 for 499 4 nbsp gb and 599 8 nbsp gb with an at t inc at t contract on february 5 2008 it was updated to have 16 nbsp gb of memory in addition to the 8 nbsp gb and 4 nbsp gb models it combined a 2 5g quad band global system for mobile communications gsm and enhanced data rates for gsm evolution edge cellular phone with features found in handheld devices running scaled down versions of apple s mac os x dubbed iphone os later renamed ios with various mac os x applications such as safari web browser safari and mail software mail it also includes web based and dashboard mac os dashboard apps such as google maps and dashboard mac os weather the iphone features a touchscreen display bluetooth and wi fi both b and g this version added support for 3g networking and assisted gps navigation the flat silver back and large antenna square of the original model were eliminated in favor of a curved glossy black or white back software capabilities were improved with the release of the app store providing applications for download that were compatible with the iphone on april 24 2009 the app store surpassed one billion downloads at wwdc on june 8 2009 apple announced the iphone 3gs it provided an incremental update to the device including faster internal components support for faster 3g speeds video recording capability and voice control at wwdc on june 7 2010 apple announced the redesigned iphone 4 it features a 960x640 display the apple a4 processor also used in the ipad a gyroscope for enhanced gaming 5mp camera with led flash front facing vga camera and facetime video calling shortly after its release reception issues were discovered by consumers due to the stainless steel band around the edge of the device which also serves as the phone s cellular signal and wi fi antenna the issue was corrected by a bumper case distributed by apple for free to all owners for a few months in june 2011 apple overtook nokia to become the world s biggest smartphone maker by volume on october 4 2011 apple unveiled the iphone 4s which was first released on october 14 2011 it features the apple a5 processor and is the first model offered by sprint nextel sprint joining at t mobility at t and verizon wireless as the united states carriers offering iphone models on october 19 2011 apple announced an agreement with c spire wireless to sell the iphone 4s with that carrier in the near future marking the first time the iphone was officially supported on a regional carrier s network another notable feature of the iphone 4s was siri voice assistant technology which apple had acquired in 2010 as well as other features including an updated 8mp camera with new optics apple sold 4 million iphone 4s phones in the first three days of availability on september 12 2012 apple introduced the iphone 5 it added a 4 inch display 4g lte connectivity and the upgraded apple a6 chip among several other improvements two million iphones were sold in the first twenty four hours of pre ordering and over five million handsets were sold in the first three days of its launch a patent filed in july 2013 revealed the development of a new iphone battery system that uses location data in combination with data on the user s habits to moderate the handsets power settings accordingly apple is working towards a power management system that will provide features such as the ability of the iphone to estimate the length of time a user will be away from a power source to modify energy usage and a detection function that adjusts the charging rate to best suit the type of power source that is being used in march 2013 one of the largest cellular phone companies in the united states t mobile announced that it would begin selling the iphone 5 on april 12 the announcement of the iphone came with the announcement that the company would begin implementing 4g cellular service for its users upon the launch of the iphone 5s and iphone 5c apple sold over nine million devices in the first three days of its launch which sets a new record for first weekend smartphone sales this was the first time that apple has simultaneously launched two models and the inclusion of china in the list of markets contributed to the record sales result on october 15 2013 u s cellular the united states fifth largest cell phone provider announced that it would in fact begin to carry the iphone it is the last of the five major carriers including at t verizon sprint corporation sprint and t mobile to acquire the phone the phone went on sale on november 8 at u s cellular stores around the country the finalization of a deal between apple and china mobile the world s largest mobile network was announced in late december 2013 the multi year agreement provides iphone access to over 760 million china mobile subscribers apple tv file appletv top2 png thumb the current generation apple tv at the 2007 macworld conference jobs demonstrated the apple tv previously known as the itv a set top video device intended to bridge the sale of content from itunes with high definition televisions the device links up to a user s tv and syncs either via wi fi or a wired network with one computer s itunes library and streams from an additional four the apple tv originally incorporated a 40 nbsp gb hard drive for storage includes outputs for hdmi and component video and plays video at a maximum resolution of 720p on may 31 2007 a 160 gb drive was released alongside the existing 40 nbsp gb model and on january 15 2008 a software update was released which allowed media to be purchased directly from the apple tv in september 2009 apple discontinued the original 40 gb apple tv and now continues to produce and sell the 160 gb apple tv on september 1 2010 alongside the release of the new line of ipod devices for the year apple released a completely redesigned apple tv the new device is 1 4 the size runs quieter and replaces the need for a hard drive with media streaming from any itunes library on the network along with 8 gb of flash memory to cache computing cache media downloaded apple with the apple tv has added another device to its portfolio that runs on its a4 processor along with the ipad and the iphone the memory included in the device is the half of the iphone 4 at 256 mb the same as the ipad iphone 3gs third and fourth generation ipod touch it has hdmi out as the only video out source features include access to the itunes store to rent movies and tv shows purchasing has been discontinued streaming from internet video sources including youtube and netflix and media streaming from an itunes library apple also reduced the price of the device to 99 a third generation of the device was introduced at an apple event on march 7 2012 with new features such as higher resolution 1080p and a new user interface software apple develops its own operating system to run on macs os x the latest version being os x mavericks version 10 9 apple also independently develops computer software titles for its os x operating system much of the software apple develops is bundled with its computers an example of this is the consumer oriented ilife software package that bundles imovie iphoto and garageband for presentation page layout and word processing iwork is available which includes keynote presentation software keynote pages iwork pages and numbers software numbers itunes quicktime media player and software update are available as free downloads for both os x and microsoft windows windows apple also offers a range of professional software titles their range of server software includes the operating system os x server apple remote desktop a remote systems management application and xsan a storage area network file system for the professional creative market there is aperture software aperture for professional raw image format raw format photo processing final cut pro a video production suite logic pro a comprehensive music toolkit and motion software motion an advanced effects composition program apple also offers online services with icloud which provides cloud storage and syncing for a wide range of data including email contacts calendars photos and documents it also offers ios device backup and is able to integrate directly with third party apps for even greater functionality icloud is the fourth generation of online services provided by apple and was preceded by mobileme mac and itools all which met varying degrees of success corporate identity logo ref according to steve jobs apple was so named because jobs was coming back from an apple farm and he was on a fruitarian diet he thought the name was fun spirited and not intimidating apple s first logo designed by ron wayne depicts sir isaac newton sitting under an apple tree it was almost immediately replaced by rob janoff s rainbow apple the now familiar rainbow colored silhouette of an apple with a bite taken out of it janoff presented jobs with several different monochromatic themes for the bitten logo and jobs immediately took a liking to it while jobs liked the logo he insisted it be in color to humanize the company the logo was designed with a bite so that it would not be confused with a cherry the colored stripes were conceived to make the logo more accessible and to represent the fact the apple ii could generate graphics in color both janoff and apple deny any homage to turing in the design of the logo on august 27 1999 but apple inc had trademark issues with apple corps apple corps ltd a multimedia company started by the beatles in 1967 involving their name and logo this resulted in a apple corps v apple computer series of lawsuits and tension between the two companies these issues ended with settling of their most recent lawsuit in 2007 advertising apple s first slogan byte into an apple was coined in the late 1970s from 1997 2002 the slogan think different was used in advertising campaigns and is still closely associated with apple apple also has slogans for specific product lines nbsp for example ithink therefore imac was used in 1998 to promote the imac and say hello to iphone has been used in iphone advertisements hello was also used to introduce the original macintosh newton platform newton imac hello again and ipod since the introduction of the macintosh in 1984 with the 1984 television commercial 1984 super bowl commercial to the more modern get a mac adverts apple has been recognized in the past for its efforts towards effective advertising and marketing for its products though its apple inc advertising criticism advertising was criticized for the claims made by some later campaigns particularly the 2005 power mac ads and iphone ads in britain apple s product commercials gained fame for launching musicians into stardom as a result of their eye popping graphics and catchy tunes first the company popularized canadian singer feist singer feist s 1234 song 1234 song in its ad campaign apple s brand loyalty is considered unusual for any product at one time apple evangelists were actively engaged by the company but this was after the phenomenon was already firmly established apple evangelist guy kawasaki has called the brand fanaticism something that was stumbled upon apple has however supported the continuing existence of a network of macintosh user group mac user groups in most major and many minor centers of population where mac computers are available mac users would meet at the european apple expo and the san francisco macworld conference expo trade shows where apple traditionally introduced new products each year to the industry and public until apple pulled out of both events while the conferences continue apple does not have official representation there mac developers in turn continue to gather at the annual apple worldwide developers conference apple store openings can draw crowds of thousands with some waiting in line as much as a day before the opening or flying in from other countries for the event the new york city fifth avenue cube store had a line as long as half a mile a few mac fans took the opportunity of the setting to propose marriage the ginza opening in tokyo was estimated in the thousands with a line exceeding eight city blocks john sculley told the guardian newspaper in 1997 people talk about technology but apple was a marketing company it was the marketing company of the decade research in 2002 by nielsen online netratings indicate that the average apple consumer was usually more affluent and better educated than other pc company consumers the research indicated that this correlation could stem from the fact that on average apple inc products are more expensive than other pc products corporate affairs during the mac s early history apple generally refused to adopt prevailing industry standards for hardware instead creating their own this trend was largely reversed in the late 1990s beginning with apple s adoption of the peripheral component interconnect pci bus in the power macintosh 7500 7500 power macintosh 8500 8500 power macintosh 9500 9500 power macintosh power macs apple has since adopted usb agp hypertransport wi fi and other industry standards in its computers and was in some cases a leader in the adoption of standards such as usb firewire is an apple originated standard that has seen widespread industry adoption after it was standardized as ieee 1394 ever since the first apple store opened apple has sold third party accessories for instance at one point nikon and canon company canon digital cameras were sold inside the store adobe software adobe one of apple s oldest software partners also sells its mac compatible software as does microsoft who sells microsoft office for the mac books from john wiley sons who publishes the for dummies series of instructional books are a notable exception however the publisher s line of books were banned from apple stores in 2005 because steve jobs disagreed with their decision to publish an unauthorized jobs biography icon after the launch of the ibookstore apple stopped selling physical books both online and at the apple retail stores headquarters apple inc s world corporate headquarters are located in the middle of silicon valley at 1 6 infinite loop street infinite loop cupertino california cupertino california this apple campus has six buildings that total and was built in 1993 by sobrato development cos in 2006 apple announced its intention to build a second campus on assembled from various contiguous plots east of n wolfe road between pruneridge avenue and vallco parkway later acquisitions increased this to 175 acres the new campus also in cupertino will be about east of the current campus the new campus building will be designed by norman foster on october 15 2013 it was announced that the cupertino city council has approved the proposed spaceship design campus on june 7 2011 steve jobs gave a presentation to cupertino city council detailing the architectural design of the new building and its environs the new campus is planned to house up to 13 000 employees in one central four storied circular building with a caf for 3 000 sitting people integrated surrounded by extensive landscape with parking mainly underground and the rest centralized in a parking structure the new campus will be built on the former hp headquarters next to interstate 280 the morning of the announcement apple ceo tim cook tweeted our home for innovation and creativity for decades to come cupertino city council gives unanimous approval for apple s new campus the 2 8 million square foot facility which will include steve jobs s original designs for a fitness center and corporate auditorium will be able to house 14 000 employees and will have enough parking to accommodate almost all of them apple s headquarters for europe the middle east and africa emea are located in cork city cork in the south of republic of ireland ireland the facility which opened in 1980 was apple s first location outside of the united states apple sales international which deals with all of apple s international sales outside of the usa is located at apple s campus in cork along with apple distribution international which similarly deals with apple s international distribution network on april 20 2012 apple announced the addition of 500 new jobs to its european headquarters this will bring the total workforce from around 2 800 to 3 300 employees the company will build a new office block on its hollyhill campus to accommodate the additional staff corporate culture apple was one of several highly successful companies founded in the 1970s that bucked the traditional notions of what a corporate culture should look like in organizational hierarchy flat versus tall casual versus formal attire etc other highly successful firms with similar cultural aspects from the same period include southwest airlines and microsoft originally the company stood in opposition to staid competitors like ibm by default thanks to the influence of its founders steve jobs often walked around the office barefoot even after apple was a fortune 500 company by the time of the 1984 television commercial 1984 tv ad this trait had become a key way the company attempted to differentiate itself from its competitors according to a 2011 report in fortune magazine fortune this has resulted in a corporate culture more akin to a startup rather than a multinational corporation as the company has grown and been led by a series of chief executives each with his own idea of what apple should be some of its original character has arguably been lost but apple still has a reputation for fostering individuality and excellence that reliably draws talented people into its employ this was especially after jobs s return to recognize the best of its employees apple created the apple fellows program awarding individuals who made extraordinary technical or leadership contributions to personal computing while at the company the apple fellowship has so far been awarded to a few individuals including bill atkinson steve capps rod holt guy kawasaki al alcorn don norman numerous employees of apple have cited that projects without jobs s involvement often took longer than projects with his involvement at apple employees are specialists who are not exposed to functions outside their area of expertise jobs saw this as a means of having best in class employees in every role for instance ron johnson businessman ron johnson who was senior vice president of retail operations until november 1 2011 was responsible for site selection in store service and store layout yet he had no control of the inventory in his stores which is done company wide by then coo and now ceo tim cook who has a background in supply chain management this is the opposite of general electric s corporate culture which has created well rounded managers the company previously advertised its products as being made in america up to the late 1990s however as a result of outsourcing initiatives in the 2000s almost all of its manufacturing is now done abroad according to a report by the new york times apple insiders believe the vast scale of overseas factories as well as the flexibility diligence and industrial skills of foreign workers have so outpaced their american counterparts that made in the u s a is no longer a viable option for most apple products unlike other major us companies apple has a relatively simple compensation policy for executives which does not include perks that other ceos enjoy such as country club fees and private use of company aircraft the company usually grants stock options to executives every other year a media article published in july 2013 provided details about apple s at home apple advisors customer support program that serves as the corporation s call center the advisors are employed within the u s and work remotely after undergoing a four week training program that also serves as a testing period the advisors earn between us 9 and 12 per hour and receive intensive management to ensure a high quality of customer support employee relations a class action lawsuit alleging that the company suppressed employee compensation has been filed against apple in a california federal district court litigation apple has been a participant in various legal proceedings and claims since it began operation and like its competitors and peers engages in litigation trying legal cases before the courts in its normal course of business for a variety of reasons in particular apple is known for and promotes itself as actively and aggressively enforcing its intellectual property interests some examples include apple v samsung apple v microsoft motorola mobility v apple inc motorola v apple apple corps v apple computer finance in its fiscal year ending in september 2011 apple inc reported a total of 108 billion in annual revenues a significant increase from its 2010 revenues of 65 billion and nearly 82 billion in cash reserves apple achieved these results while losing market share in certain product categories on march 19 2012 apple announced plans for a 2 65 per share dividend beginning in fourth quarter of 2012 per approval by their board of directors on september 2012 apple reached a record share price of more than 705 and closed at above 700 with 936 596 000 outstanding shares as of june 30 2012 it had a market capitalization of about 660 billion at the time this was the list of corporations by market capitalization highest nominal market capitalization ever reached by a publicly traded company surpassing a record set by microsoft in 1999 environmental record climate change and clean energy on april 21 2011 greenpeace released a report highlighting the fact that data centers consumed up to 2 of all global electricity and this amount was projected to increase phil radford of greenpeace said we are concerned that this new explosion in electricity use could lock us into old polluting energy sources instead of the clean energy available today on april 17 2012 following a greenpeace protest of apple apple inc released a statement committing to ending its use of coal and shifting to 100 clean energy in 2013 apple announced it was using 100 renewable energy to power their data centers and overall 75 of its power comes from renewable sources in 2010 climate counts a nonprofit organization dedicated to directing consumers toward the greenest companies gave apple a score of 52 points out of a possible 100 which puts apple in their top category striding this was an increase from may 2008 when climate counts only gave apple 11 points out of 100 which placed the company last among electronics companies at which time climate counts also labeled apple with a stuck icon adding that apple at the time was a choice to avoid for the climate conscious consumer toxics greenpeace has campaigned against apple because of various environmental issues including a global end of life take back plan non recyclable hardware components and toxins within iphone hardware since 2003 greenpeace has campaigned against apple s use of particular chemicals in its products more specifically the inclusion of polyvinyl chloride pvc and brominated flame retardant bfrs in their devices on may 2 2007 steve jobs released a report announcing plans to eliminate pvc and bfrs by the end of 2008 apple has since eliminated pvc and bfrs from its product range becoming the first laptop manufacturer to do so in the first edition of the greenpeace green electronics guide released in august 2006 apple only scored 2 7 10 the united states environmental protection agency environmental protection agency rates apple highest amongst producers of notebooks and fairly well compared to producers of desktop computers and lcd displays in june 2007 apple upgraded the macbook pro replacing cold cathode fluorescent lamp ccfl backlit lcd displays with mercury element mercury free led backlit lcd displays and arsenic free glass apple offers information about emissions materials and electrical usage concerning each product in june 2009 apple s iphone 3gs was free of pvc arsenic bfrs and had an efficient power adapter in october 2009 apple upgraded the imac and macbook replacing the cold cathode fluorescent lamp ccfl backlit lcd displays with mercury free led backlit lcd displays and arsenic free glass this means all apple computers have mercury free led backlit displays arsenic free glass and are without pvc cables all apple computers also have epeat gold status in november 2011 apple featured in greenpeace s guide to greener electronics which ranks electronics manufacturers on sustainability climate and energy policy and how green their products are the company ranked fourth of fifteen electronics companies moving up five places from the previous year with a score of 4 6 10 down from 4 9 greenpeace praises apple s sustainability noting that the company exceeded its 70 global recycling goal in 2010 it continues to score well on the products rating with all apple products now being free of pvc vinyl plastic and brominated flame retardants however the guide criticizes apple on the energy criteria for not seeking external verification of its greenhouse gas emissions data and for not setting out any targets to reduce emissions in june 2012 apple inc withdrew its products from the electronic product environmental assessment tool electronic product environmental assessment tool epeat certification system but reversed this decision in july labor practices in 2006 the mail on sunday reported on the working conditions that existed at factories in china where the contract manufacturers foxconn and inventec produced the ipod the article stated that one complex of factories that assembles the ipod among other items had over 200 000 workers that lived and worked in the factory with employees regularly working more than 60 hours per week the article also reported that workers made around 100 per month and were required to live pay for rent and food from the company which generally amounted to a little over half of workers earnings apple immediately launched an investigation and worked with their manufacturers to ensure acceptable working conditions in 2007 apple started yearly audits of all its suppliers regarding worker s rights slowly raising standards and pruning suppliers that did not comply yearly progress reports have been published since 2008 in 2010 workers in china planned to sue iphone contractors over poisoning by a cleaner used to clean lcd screens one worker claimed that he and his coworkers had not been informed of possible occupational illnesses after a spate of suicides in a foxconn facility in china making ipads and iphones albeit at a lower rate than in china as a whole workers were forced to sign a legally binding document guaranteeing that they would not kill themselves in 2011 apple admitted that its suppliers child labor practices in china had worsened workers in factories producing apple products have also been exposed to n hexane a neurotoxin that is a cheaper alternative than alcohol for cleaning the products in 2013 china labor watch said it found violations of the law and of apple s pledges about working conditions at facilities operated by pegatron including discrimination against ethnic minorities and women withholding employees pay excessive work hours poor living conditions health and safety problems and pollution tax practices class wikitable style float right global taxes paid by asi 2009 2011 scope col 2011 scope col 2010 scope col 2009 scope col total scope row pre tax earnings us 22 billion us 12 billion us 4 billion us 38 billion scope row global tax us 10 million us 7 million us 4 million us 21 million scope row tax rate 0 05 0 06 0 1 0 06 apple created subsidiaries in low tax places such as the republic of ireland the netherlands luxembourg and the british virgin islands to cut the taxes it pays around the world according to the new york times in the 1980s apple was among the first tech companies to designate overseas salespeople in high tax countries in a manner that allowed the company to sell on behalf of low tax subsidiaries on other continents sidestepping income taxes in the late 1980s apple was a pioneer of an accounting technique known as the double irish arrangement dutch sandwich double irish with a dutch sandwich which reduces taxes by routing profits through irish subsidiaries and the netherlands and then to the caribbean british conservative party member of parliament charlie elphicke published research on october 30 2012 which showed that some multinational companies including apple inc were making billions of pounds of profit in the uk but were paying an effective tax rate to the uk treasury of only 3 percent well below standard corporation tax he followed this research by calling on the chancellor of the exchequer george osborne to force these multinationals which also included google and coca cola to state the effective rate of tax they pay on their uk revenues elphicke also said that government contracts should be withheld from multinationals who do not pay their fair share of uk tax charitable causes as of 2012 apple is listed as a partner of the product red campaign together with other brands such as nike girl american express and converse the campaign s mission is to prevent the transmission of hiv from mother to child by 2015 its byline is fighting for an aids free generation in november 2012 apple donated 2 5 million to the american red cross to aid relief efforts after hurricane sandy see also apple campus apple media events apple inc litigation ireview music used by apple inc pixar references further reading div class references small gil amelio william l simon 1999 on the firing line my 500 days at apple isbn 978 0 88730 919 9 jim carlton apple the inside story of intrigue egomania and business blunders isbn 978 0 88730 965 6 alan deutschman 2000 the second coming of steve jobs broadway books broadway isbn 978 0 7679 0432 2 andy hertzfeld 2004 revolution in the valley o reilly books isbn 978 0 596 00719 5 paul kunkel appledesign the work of the apple industrial design group isbn 978 1 888001 25 9 steven levy 1994 insanely grea" }, { "value", "value", "value" }, } } }, }, GlobalParameters = new Dictionary<string, string>() { } }; const string apiKey = "J6JVifZvJh9b7wUjny4MB3joZ529Q5/pdcjqHuLgNbPnU4k1nChBaZap7P37fiaDKzR1Sj0ppUO3OMJlVOPVtQ=="; // Replace this with the API key for the web service client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/f05b36fa1fa84506a4f7d1fd20e5b879/services/6a258bc2912f4f098dc0e4516df4dac5/execute?api-version=2.0&details=true"); // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application. // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context. // For instance, replace code such as: // result = await DoSomeTask() // with the following: // result = await DoSomeTask().ConfigureAwait(false) HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); Console.WriteLine("Result: {0}", result); } else { Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode)); // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure Console.WriteLine(response.Headers.ToString()); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } } }
public void MessageAnalysis(string message) { #region Commented Old Version //string responseXml = ""; // pass it to some service //var client=new HttpClient(); //string url = ConfigurationManager.AppSettings["ServiceUrl"].ToString(CultureInfo.InvariantCulture); //client.BaseAddress = new Uri(url); //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //var irequest = new UssdRequestMessage() { TransactionId = "53635424", MSISDN = "911734365", TransactionTime = DateTime.UtcNow.ToString("o"), response = false, USSDServiceCode = "809", USSDRequestString = "*809#" }; ////HttpResponseMessage response = client.GetAsync("api/Communication/GetResponse?request=" + message).Result; //HttpResponseMessage iresponse = client.PostAsJsonAsync("api/communication/GetResponse", irequest).Result; //var cont = iresponse.Content.ReadAsAsync<UssdResponseMessage>(); ////HttpResponseMessage response = client.GetAsync("api/Communication/GetResponse?request=" + message).Result; ////HttpResponseMessage response = client.PostAsJsonAsync("api/communication/GetResponse", message).Result; //if (iresponse.IsSuccessStatusCode) //{ // var content = iresponse.Content.ReadAsAsync<UssdResponseMessage>(); // responseXml = new USSDXMLWriter(content.Result).GenerateXml(); //} //else //{ // var request = new USSDXMLReader(message).GenerateMessageObject(); // var fault = new FaultResponse() {TransactionId = request.TransactionId,FaultCode = "303",FaultString = "Error occured processing the request",TransactionTime = DateTime.UtcNow}; // responseXml = new USSDXMLWriter(fault).GenerateXml(); //} //var request = new USSDXMLReader(message).GenerateMessageObject(); //var response = new Gate().GetResponse(request); //responseXml = new USSDXMLWriter(response).GenerateXml(); #endregion var client = new HttpClient(); string url = ConfigurationManager.AppSettings["ServiceUrl"].ToString(CultureInfo.InvariantCulture); client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string transactionId = ""; Random random = new Random(); var trId = random.Next(0, 99999999); transactionId = trId.ToString("0000000#"); //var request = new UssdRequestMessage() { TransactionId = transactionId, MSISDN = "251911734365", TransactionTime = DateTime.UtcNow.ToString("o"), response = false, USSDServiceCode = "809", USSDRequestString = "*809#" }; var request = new USSDXMLReader(message).GenerateMessageObject(); var serializer = new JavaScriptSerializer(); var requestCsv = serializer.Serialize(request);//new CsvHelper().WriteObjectToCsv(request); HttpResponseMessage response = client.PostAsJsonAsync("service/api/communication/GetResponse", requestCsv).Result; var cont = response.Content.ReadAsStringAsync(); new UssdSender().XmlRpcCall(cont.Result);//.SendUssdResponse(cont.Result); }
private UssdResponse GetResponse(object[] parameters) { var client = new HttpClient(); string url = ConfigurationManager.AppSettings["ServiceUrl"].ToString(CultureInfo.InvariantCulture); client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var request = new USSDXMLReader().GetUssdRequest(parameters); var serializer = new JavaScriptSerializer(); var requestCsv = serializer.Serialize(request);//new CsvHelper().WriteObjectToCsv(request); HttpResponseMessage response = client.PostAsJsonAsync("service/api/communication/GetResponse", requestCsv).Result; var cont = response.Content.ReadAsAsync<object[]>(); var resul = (object[])cont.Result; return new UssdResponse() { TransactionId = resul[0].ToString(), TransactionTime = Convert.ToDateTime(resul[1].ToString()), USSDResponseString = resul[2].ToString().Replace("©","\n"), action = resul[3].ToString(), ResponseCode = Convert.ToInt32(resul[4]) }; //return new UssdResponse() { TransactionId = "123456", TransactionTime = DateTime.Now, USSDResponseString = "Hello Geez " + rpcStruct["MSISDN"].ToString(), action = "end", ResponseCode = 0 }; }
static void Main() { CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = cookies; using (var httpClient = new HttpClient(handler)) { var response = httpClient.PostAsJsonAsync( POST, new {Username = "******", Password = "******" }, CancellationToken.None ).Result; response.EnsureSuccessStatusCode(); bool success = response.IsSuccessStatusCode; Console.WriteLine("1: " + response.Headers.GetValues("Set-Cookie").FirstOrDefault()); if (success) { HttpRequestMessage request = new HttpRequestMessage(); request.Method = HttpMethod.Get; request.RequestUri = new Uri(GET); if (response.IsSuccessStatusCode) { Console.WriteLine(request.Headers); } var secret = httpClient.GetStringAsync(GET); var h= httpClient.GetAsync(GET); Console.WriteLine(secret.Result); } else { Console.WriteLine("Sorry you provided wrong credentials"); } } Console.Read(); }
public ActionResult Create(LanguageVM Lang) { client.PostAsJsonAsync <LanguageVM>("language", Lang).ContinueWith((e => e.Result.EnsureSuccessStatusCode())); return(RedirectToAction("Index")); }
private async Task Transactie(String PasID, String RekeningID, int balans) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; using (var client = new HttpClient(new HttpClientHandler { UseProxy = false, ClientCertificateOptions = ClientCertificateOption.Automatic })) { client.BaseAddress = new Uri("https://hrsqlapp.tk"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var trans = new Transactie() { Balans = balans, PasID = Int32.Parse(PasID), RekeningID = RekeningID, locatie = "HRO" }; HttpResponseMessage response = await client.PostAsJsonAsync("api/transacties", trans).ConfigureAwait(false); if (response.IsSuccessStatusCode) { //Error.show("SUCCES"); } else { //Error.show("FAIL"); } } }
public async Task CreateNewSubscriptionCycles() { var subscriptionCycles = _subscriptionCycleRepository.GetSoonExpires(DateTime.Now, _clientOptions.OrderDaysToExpire); foreach (var cycle in subscriptionCycles) { using var unitOfWork = UnitOfWorkManager.Begin(); SubscriptionCycle newCycle = _subscriptionCycleDomainService.CreateSubscriptionCycle(cycle.Subscription, DateTime.Now); _subscriptionCycleDomainService.PaymentPendingSubscriptionCycle(newCycle); _subscriptionCycleRepository.Insert(newCycle); Order oldOrder = _orderRepository.GetBySubscriptionCycle(cycle); PlanPrice planPrice = cycle.Subscription.Plan.PlanPrices.Single(x => x.Currency.Code == oldOrder.Currency.Code); Order order = _orderDomainService.CreateOrderForRenewSubscription(planPrice, oldOrder.UserId, DateTime.Now); _orderDomainService.PaymentPendingOrder(order); order = _orderRepository.Insert(order); SubscriptionCycleOrder subscriptionCycleOrder = _subscriptionCycleOrderDomainService.CreateSubscriptionCycleOrder(newCycle, order); _subscriptionCycleOrderRepository.Insert(subscriptionCycleOrder); Invoice invoice = _invoiceDomainService.CreateInvoice(order, DateTime.Now); _invoiceDomainService.ActiveInvoice(invoice); _invoiceRepository.Insert(invoice); InvoicePaymentProvider invoicePaymentProvider = planPrice.Currency.Code switch { Domain.ValueObjects.Currency.CurrencyValue.USD => await _paypalService.CreateUriForPayment(invoice, order, cycle.Subscription.Plan), Domain.ValueObjects.Currency.CurrencyValue.ARS => await _mobbexService.CreateUriForPayment(invoice, order, cycle.Subscription.Plan), _ => throw new NotImplementedException() }; _invoicePaymentProviderRepository.Insert(invoicePaymentProvider); Notification notification = _notificationDomainService.CreateNotification(order); _notificationDomainService.SetNewSubscribeCycle(notification); _noticationRepository.Insert(notification); NotificationDto notificationDto = _mapper.Map <NotificationDto>(notification); HttpResponseMessage httpResponse = await _httpClient.PostAsJsonAsync(_clientOptions.NotificactionUrl, notificationDto); if (httpResponse.IsSuccessStatusCode) { _noticationRepository.Delete(notification); } else { _notificationDomainService.AddAttempt(notification); _noticationRepository.Update(notification); } unitOfWork.Complete(); } }
public async Task <IResult <int> > SaveAsync(AddEditDocumentCommand request) { var response = await _httpClient.PostAsJsonAsync(Routes.DocumentsEndpoints.Save, request); return(await response.ToResult <int>()); }
public ActionResult Create(Project collection, string Prange, FormCollection form) { try { int Priority = 1; int.TryParse(Prange, out Priority); string CheckDate = form["hdnChk"].ToString(); string UserID = form["User"].ToString(); //validate : if (collection.Project1 == "") { ModelState.AddModelError(string.Empty, "Please enter all the fileds below"); if (Session["ProjectToEdit"] == null) { ViewBag.SubmitValue = "Add"; } else { ViewBag.SubmitValue = "Update"; } collection.User_info = UserList(); collection.Priority = Priority; ViewData["project"] = collection; ViewData["oList"] = (List <Project>)Session["ProjectList"]; return(View("ProjectView")); } if (CheckDate == "true") { if (collection.Start_Date < DateTime.Now || collection.Start_Date == null || collection.End_date <= DateTime.Now.Date || collection.End_date == null) { ModelState.AddModelError(string.Empty, "Please enter Correct start and end date"); if (Session["ProjectToEdit"] == null) { ViewBag.SubmitValue = "Add"; } else { ViewBag.SubmitValue = "Update"; } collection.User_info = UserList(); collection.Priority = Priority; ViewData["project"] = collection; ViewData["oList"] = (List <Project>)Session["ProjectList"]; return(View("ProjectView")); } } string PostString; collection.Priority = Priority; if (Session["ProjectToEdit"] == null) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(Baseurl); //HTTP POST var postTask = client.PostAsJsonAsync <Project>("PostProject", collection); postTask.Wait(); var result = postTask.Result; PostString = result.StatusCode.ToString(); if (PostString.Contains("InternalServerError") == true) { PostString = "OK"; } } //update the same in the User table AddUserProject(collection, UserID); } else { //update Project ProjectToSave = new Project(); ProjectToSave = (Project)Session["ProjectToEdit"]; //Clear the session Session["ProjectToEdit"] = null; ProjectToSave.Project1 = collection.Project1; ProjectToSave.Start_Date = collection.Start_Date; ProjectToSave.End_date = collection.End_date; ProjectToSave.Priority = Priority; ProjectToSave.User_info = null;//this will not add any extra row in the User table. ProjectToSave.Tasks = null; oUser(UserID, ProjectToSave.Project_ID); //Call the Put Method using (var client = new HttpClient()) { client.BaseAddress = new Uri(Baseurl); //HTTP POST var postTask = client.PutAsJsonAsync <Project>("PutProject", ProjectToSave); postTask.Wait(); var result = postTask.Result; PostString = result.StatusCode.ToString(); if (PostString.Contains("NoConte") == true) { PostString = "OK"; } } } return(RedirectToAction("Index")); } catch { return(RedirectToAction("Index")); } }
public async Task <UpdateChargeResponse> Update(UpdateChargeRequest request, IEnumerable <KeyValuePair <string, string> > pairs) { var response = new UpdateChargeResponse(); //根据经纪人获取手机号 IBxAgent agentModel = GetAgentModelFactory(request.Agent); //logInfo.Info("获取到的经纪人信息:"+agentModel.ToJson()); //参数校验 if (!agentModel.AgentCanUse()) { response.Status = HttpStatusCode.Forbidden; return(response); } if (!ValidateReqest(pairs, agentModel.SecretKey, request.SecCode)) { response.Status = HttpStatusCode.Forbidden; return(response); } bx_charge charge = _chargeRepository.Find(request.Agent, request.BusyKey); if (charge == null) { response.Status = HttpStatusCode.BadRequest; return(response); } try { //发送请求 checkneed using (var client = new HttpClient()) { client.BaseAddress = new Uri(_url); var requestmodel = new { LicenseNo = request.LicenseNo, Agent = request.Agent }; HttpResponseMessage res = await client.PostAsJsonAsync("api/userinfo/FindCarInfoBy", requestmodel); if (res.IsSuccessStatusCode) { WaFindCarInfoResponse result = await res.Content.ReadAsAsync <WaFindCarInfoResponse>(); if (result.ErrCode == 0) { //更新bx_charge if (charge.total_count == charge.used_count) { //余额不足 response.Status = HttpStatusCode.OK; response.ErrCode = -2; return(response); } charge.used_count += 1; charge.update_time = DateTime.Now; var chargeCount = _chargeRepository.Update(charge); if (chargeCount == 1) { //插入bx_charge_history var history = new bx_charge_history { charge_id = charge.id, license_no = request.LicenseNo, result_status = 1 //成功 }; _chargeHistoryRepository.Add(history); } response.TotalCount = charge.total_count.HasValue ? charge.total_count.Value : 0; response.UsedCount = charge.used_count.HasValue ? charge.used_count.Value : 0; response.MoldName = result.CarInfo.MoldName; response.CarVin = result.CarInfo.CarVin; response.RegisterDate = result.CarInfo.RegisteDate; response.LicenseNo = result.CarInfo.PlateNo; response.EngineNo = result.CarInfo.EngineNo; response.LicenseOwner = result.CarInfo.LicenseOwner; response.OwnerIdNo = result.CarInfo.OwnerIdNo; response.Status = HttpStatusCode.OK; response.ErrCode = 0; return(response); } else { //插入bx_charge_history var history = new bx_charge_history { charge_id = charge.id, license_no = request.LicenseNo, result_status = 0 //失败 }; _chargeHistoryRepository.Add(history); response.Status = HttpStatusCode.OK; response.ErrCode = -1; return(response); } } } } catch (Exception ex) { response.Status = HttpStatusCode.ExpectationFailed; logError.Info("收费服务-获取车辆信息发生异常:" + ex.Source + "\n" + ex.StackTrace + "\n" + ex.Message + "\n" + ex.InnerException); } return(response); }
static async Task InvokeBatchExecutionService() { // How this works: // // 1. Assume the input is present in a local file (if the web service accepts input) // 2. Upload the file to an Azure blob - you'd need an Azure storage account // 3. Call the Batch Execution Service to process the data in the blob. Any output is written to Azure blobs. // 4. Download the output blob, if any, to local file const string BaseUrl = "https://ussouthcentral.services.azureml.net/workspaces/ede12cb3aaf24c7e826493f4e309f1e1/services/ad3b577804c443d08f0f30b6c8028411/jobs"; const string StorageAccountName = "loy2018sa"; // Replace this with your Azure Storage Account name const string StorageAccountKey = "4oKF2tzfkDk/H6eYzHa8YwpV/pNB9oVprOpc3PNIRrL/EduRP6/o2css1tX4p47ateS8AfT2DUetjgLv4Tr3hg=="; // Replace this with your Azure Storage Key const string StorageContainerName = "blob1"; // Replace this with your Azure Storage Container name string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, StorageAccountKey); const string apiKey = "IJh2PfzFAh5Q4Hsj/vod6PjgOlTBWeng2f2C+89Sv/1t1Vr7KaDZfequmXPzhAZNs9KjkaklAcSuRvTLy47/yw=="; // Replace this with the API key for the web service // set a time out for polling status const int TimeOutInMilliseconds = 120 * 1000; // Set a timeout of 2 minutes UploadFileToBlob("c:\\ml\\input1data.csv" /*Replace this with the location of your input file*/, "input1datablob.csv" /*Replace this with the name you would like to use for your Azure blob; this needs to have the same extension as the input file */, StorageContainerName, storageConnectionString); using (HttpClient client = new HttpClient()) { var request = new BatchExecutionRequest() { Inputs = new Dictionary <string, AzureBlobDataReference>() { { "input1", new AzureBlobDataReference() { ConnectionString = storageConnectionString, RelativeLocation = string.Format("{0}/input1datablob.csv", StorageContainerName) } }, }, Outputs = new Dictionary <string, AzureBlobDataReference>() { { "output1", new AzureBlobDataReference() { ConnectionString = storageConnectionString, RelativeLocation = string.Format("/{0}/output1results.csv", StorageContainerName) } }, }, GlobalParameters = new Dictionary <string, string>() { } }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application. // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context. // For instance, replace code such as: // result = await DoSomeTask() // with the following: // result = await DoSomeTask().ConfigureAwait(false) Console.WriteLine("Submitting the job..."); // submit the job var response = await client.PostAsJsonAsync(BaseUrl + "?api-version=2.0", request); if (!response.IsSuccessStatusCode) { await WriteFailedResponse(response); return; } string jobId = await response.Content.ReadAsAsync <string>(); Console.WriteLine(string.Format("Job ID: {0}", jobId)); // start the job Console.WriteLine("Starting the job..."); response = await client.PostAsync(BaseUrl + "/" + jobId + "/start?api-version=2.0", null); if (!response.IsSuccessStatusCode) { await WriteFailedResponse(response); return; } string jobLocation = BaseUrl + "/" + jobId + "?api-version=2.0"; Stopwatch watch = Stopwatch.StartNew(); bool done = false; while (!done) { Console.WriteLine("Checking the job status..."); response = await client.GetAsync(jobLocation); if (!response.IsSuccessStatusCode) { await WriteFailedResponse(response); return; } BatchScoreStatus status = await response.Content.ReadAsAsync <BatchScoreStatus>(); if (watch.ElapsedMilliseconds > TimeOutInMilliseconds) { done = true; Console.WriteLine(string.Format("Timed out. Deleting job {0} ...", jobId)); await client.DeleteAsync(jobLocation); } switch (status.StatusCode) { case BatchScoreStatusCode.NotStarted: Console.WriteLine(string.Format("Job {0} not yet started...", jobId)); break; case BatchScoreStatusCode.Running: Console.WriteLine(string.Format("Job {0} running...", jobId)); break; case BatchScoreStatusCode.Failed: Console.WriteLine(string.Format("Job {0} failed!", jobId)); Console.WriteLine(string.Format("Error details: {0}", status.Details)); done = true; break; case BatchScoreStatusCode.Cancelled: Console.WriteLine(string.Format("Job {0} cancelled!", jobId)); done = true; break; case BatchScoreStatusCode.Finished: done = true; Console.WriteLine(string.Format("Job {0} finished!", jobId)); ProcessResults(status); break; } if (!done) { Thread.Sleep(1000); // Wait one second } } } }
/// <summary> /// Posts or Puts the data depending on httpMethod returning result as a string (if there is a result) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="postPath">The post path.</param> /// <param name="data">The data.</param> /// <param name="httpMethod">The HTTP method.</param> /// <exception cref="Rock.Net.HttpErrorException"></exception> private string PostPutData <T>(string postPath, T data, int id, HttpMethod httpMethod) { string contentResult = null; Uri requestUri = new Uri(rockBaseUri, postPath); HttpClient httpClient = new HttpClient(new HttpClientHandler { CookieContainer = this.CookieContainer }); HttpError httpError = null; HttpResponseMessage httpResponseMessage = null; Action <Task <HttpResponseMessage> > handleContinue = new Action <Task <HttpResponseMessage> >(postTask => { httpResponseMessage = postTask.Result; if (postTask.Result.IsSuccessStatusCode) { postTask.Result.Content.ReadAsAsync <object>().ContinueWith(c => { if (c.Result is HttpError) { httpError = c.Result as HttpError; } }).Wait(); postTask.Result.Content.ReadAsStringAsync().ContinueWith(c => { contentResult = c.Result; }).Wait(); } else { postTask.Result.Content.ReadAsStringAsync().ContinueWith(s => { httpError = GetHttpError(requestUri, httpError, postTask, s); }).Wait(); } }); if (httpMethod == HttpMethod.Post) { // POST is for INSERTs httpClient.PostAsJsonAsync <T>(requestUri.ToString(), data).ContinueWith(handleContinue).Wait(); } else { // PUT is for UPDATEs Uri putRequestUri = new Uri(requestUri, string.Format("{0}", id)); httpClient.PutAsJsonAsync <T>(putRequestUri.ToString(), data).ContinueWith(handleContinue).Wait(); } if (httpError != null) { throw new HttpErrorException(httpError, httpResponseMessage); } if (httpResponseMessage != null) { httpResponseMessage.EnsureSuccessStatusCode(); } return(contentResult); }
private async void btnSimpanJasa_Click(object sender, EventArgs e) { if (tbLynJasa.Text.ToString().Trim() != "" && tbHrgJasa.Text.ToString().Trim() != "") { if (check.Equals("simpan")) { Service service = new Service { service_name = tbLynJasa.Text.ToString(), price = Convert.ToDouble(tbHrgJasa.Text.ToString()) }; var response = client.PostAsJsonAsync("api/services", service).Result; if (response.IsSuccessStatusCode) { var a = await response.Content.ReadAsStringAsync(); Debug.WriteLine(a); dgJasa.DataSource = await GetDataJasa(); dgJasa.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dgJasa.DataBindingComplete += (o, _) => { var dataGridView = o as DataGridView; if (dataGridView != null) { dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dataGridView.Columns[dataGridView.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } }; MessageBox.Show("Berhasil Input Data Jasa"); } else { Debug.WriteLine("Gagal"); } } else if (check.Equals("edit")) { Service service = new Service { id_service = id, service_name = tbLynJasa.Text.ToString(), price = Convert.ToDouble(tbHrgJasa.Text.ToString()) }; HttpResponseMessage response = await client.PutAsJsonAsync( $"api/services/{service.id_service}", service); response.EnsureSuccessStatusCode(); service = await response.Content.ReadAsAsync <Service>(); dgJasa.DataSource = await GetDataJasa(); dgJasa.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dgJasa.DataBindingComplete += (o, _) => { var dataGridView = o as DataGridView; if (dataGridView != null) { dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dataGridView.Columns[dataGridView.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } }; MessageBox.Show("Berhasil Update Data Jasa"); } clearInput(); disableInput(); } else { MessageBox.Show("Data Anda Masih Kosong atau tidak lengkap"); } }
public async Task <ActionResult> Create(ProductCreateViewModel productViewModel) { TokenViewModel _token = HttpContext.Session.Get <TokenViewModel>(Constant.TOKEN); if (_token != null) { try { if (ModelState.IsValid) { using (var client = new HttpClient()) { // TODO: Add insert logic here ProductEditViewModel productEditViewModel = null; if (productViewModel.Product.IsSale ?? false) { if (productViewModel.Product.PriceSale == 0) { ViewBag.Error = "Price Sale is required when IsSale is True"; productEditViewModel = new ProductCreateViewModel { User = _token, Product = productViewModel.Product, Categories = await GetAllCate(_token), }; return(View(productEditViewModel)); } } else { productViewModel.Product.PriceSale = null; } client.BaseAddress = new Uri("https://cocshopwebapi20190925023900.azurewebsites.net/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_token.Access_token}"); HttpResponseMessage response = await client.PostAsJsonAsync($"api/Products", productViewModel.Product); var jsonString = await response.Content.ReadAsStringAsync(); var body = JsonConvert.DeserializeObject <BaseViewModel <UpdateProductViewModel> >(jsonString); if (response.IsSuccessStatusCode) { TempData["Success"] = "Create Successfully"; return(RedirectToAction("Index", "Product")); } else { productEditViewModel = new ProductEditViewModel { User = _token, Product = productViewModel.Product, Categories = await GetAllCate(_token), }; ViewBag.Error = body.Description; return(View(productEditViewModel)); } } } else { ProductCreateViewModel productEditViewModel = new ProductCreateViewModel { User = _token, Product = productViewModel.Product, Categories = await GetAllCate(_token), }; return(View(productEditViewModel)); } } catch { return(View()); } } return(RedirectToAction("Login", "Auth")); }
public Task <HttpResponseMessage> Create(Guid id, string title) => _client.PostAsJsonAsync("", new { Id = id, Title = title });
public async Task Add(ProposalModel model) { await client.PostAsJsonAsync("v1/Proposal", model); }
static async Task InvokeBatchExecutionService() { // How this works: // // 1. Assume the input is present in a local file (if the web service accepts input) // 2. Upload the file to an Azure blob - you'd need an Azure storage account // 3. Call the Batch Execution Service to process the data in the blob. Any output is written to Azure blobs. // 4. Download the output blob, if any, to local file const string BaseUrl = "https://ussouthcentral.services.azureml.net/workspaces/8c68810612b849a994aec53eb470d02d/services/69bd399586ba43a98384b72bd9240b2b/jobs"; const string StorageAccountName = "mystorageacct"; // Replace this with your Azure Storage Account name const string StorageAccountKey = "Dx9WbMIThAvXRQWap/aLnxT9LV5txxw=="; // Replace this with your Azure Storage Key const string StorageContainerName = "mycontainer"; // Replace this with your Azure Storage Container name string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, StorageAccountKey); const string apiKey = "abc123"; // Replace this with the API key for the web service // set a time out for polling status const int TimeOutInMilliseconds = 120 * 1000; // Set a timeout of 2 minutes UploadFileToBlob("input1data.csv" /*Replace this with the location of your input file*/, "input1datablob.csv" /*Replace this with the name you would like to use for your Azure blob; this needs to have the same extension as the input file */, StorageContainerName, storageConnectionString); using (HttpClient client = new HttpClient()) { var request = new BatchExecutionRequest() { Inputs = new Dictionary <string, AzureBlobDataReference>() { { "input1", new AzureBlobDataReference() { ConnectionString = storageConnectionString, RelativeLocation = string.Format("{0}/input1datablob.csv", StorageContainerName) } }, }, Outputs = new Dictionary <string, AzureBlobDataReference>() { { "output1", new AzureBlobDataReference() { ConnectionString = storageConnectionString, RelativeLocation = string.Format("/{0}/output1results.csv", StorageContainerName) } }, }, GlobalParameters = new Dictionary <string, string>() { } }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application. // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context. // For instance, replace code such as: // result = await DoSomeTask() // with the following: // result = await DoSomeTask().ConfigureAwait(false) Console.WriteLine("Submitting the job..."); // submit the job var response = await client.PostAsJsonAsync(BaseUrl + "?api-version=2.0", request); if (!response.IsSuccessStatusCode) { await WriteFailedResponse(response); return; } string jobId = await response.Content.ReadAsAsync <string>(); Console.WriteLine(string.Format("Job ID: {0}", jobId)); // start the job Console.WriteLine("Starting the job..."); response = await client.PostAsync(BaseUrl + "/" + jobId + "/start?api-version=2.0", null); if (!response.IsSuccessStatusCode) { await WriteFailedResponse(response); return; } string jobLocation = BaseUrl + "/" + jobId + "?api-version=2.0"; Stopwatch watch = Stopwatch.StartNew(); bool done = false; while (!done) { Console.WriteLine("Checking the job status..."); response = await client.GetAsync(jobLocation); if (!response.IsSuccessStatusCode) { await WriteFailedResponse(response); return; } BatchScoreStatus status = await response.Content.ReadAsAsync <BatchScoreStatus>(); if (watch.ElapsedMilliseconds > TimeOutInMilliseconds) { done = true; Console.WriteLine(string.Format("Timed out. Deleting job {0} ...", jobId)); await client.DeleteAsync(jobLocation); } switch (status.StatusCode) { case BatchScoreStatusCode.NotStarted: Console.WriteLine(string.Format("Job {0} not yet started...", jobId)); break; case BatchScoreStatusCode.Running: Console.WriteLine(string.Format("Job {0} running...", jobId)); break; case BatchScoreStatusCode.Failed: Console.WriteLine(string.Format("Job {0} failed!", jobId)); Console.WriteLine(string.Format("Error details: {0}", status.Details)); done = true; break; case BatchScoreStatusCode.Cancelled: Console.WriteLine(string.Format("Job {0} cancelled!", jobId)); done = true; break; case BatchScoreStatusCode.Finished: done = true; Console.WriteLine(string.Format("Job {0} finished!", jobId)); ProcessResults(status); break; } if (!done) { Thread.Sleep(1000); // Wait one second } } } }
public async Task <IResult> CreateAsync(CreateTimesheetRequest request) { var response = await _httpClient.PostAsJsonAsync(Routes.TimesheetEndpoint.Create, request); return(await response.ToResult()); }
public async Task GetByQueryAsync_UsingDefaults_ReturnsExpectedResult() { // Arrange using HttpClient httpClient = await webApplicationFactory.CreateClientWithJwtAsync(); long?id = null; try { string nameSuffix = Guid.NewGuid().ToString("N"); string name = $"it--{nameof(GetByQueryAsync_UsingDefaults_ReturnsExpectedResult)}--{nameSuffix}"; var newTodoItemModel = new NewTodoItemModel { IsComplete = DateTime.UtcNow.Ticks % 2 == 0, Name = name }; HttpResponseMessage response = await httpClient.PostAsJsonAsync(BaseUrl, newTodoItemModel); response.IsSuccessStatusCode.Should().BeTrue(); response.StatusCode.Should().Be(HttpStatusCode.Created); id = await response.Content.ReadAsAsync <long>(); var queryString = new Dictionary <string, string> { { nameof(TodoItemQueryModel.Id), id.ToString() }, { nameof(TodoItemQueryModel.IsComplete), newTodoItemModel.IsComplete.ToString() }, { nameof(TodoItemQueryModel.NamePattern), name }, { nameof(TodoItemQueryModel.PageIndex), 0.ToString() }, { nameof(TodoItemQueryModel.PageSize), 5.ToString() }, { nameof(TodoItemQueryModel.SortBy), nameof(TodoItem.CreatedOn) }, { nameof(TodoItemQueryModel.IsSortAscending), bool.FalseString } }; string requestUri = QueryHelpers.AddQueryString(BaseUrl, queryString); // Act response = await httpClient.GetAsync(requestUri); // Assert using (new AssertionScope()) { response.IsSuccessStatusCode.Should().BeTrue(); response.StatusCode.Should().Be(HttpStatusCode.OK); List <TodoItemModel> todoItemModels = await response.Content.ReadAsAsync <List <TodoItemModel> >(); todoItemModels.Should().HaveCount(1); TodoItemModel todoItemModel = todoItemModels.Single(); todoItemModel.Should().NotBeNull(); todoItemModel.Name.Should().Be(newTodoItemModel.Name); todoItemModel.IsComplete.Should().Be(newTodoItemModel.IsComplete.Value); } } finally { if (id.HasValue) { HttpResponseMessage response = await httpClient.DeleteAsync($"{BaseUrl}/{id}"); response.IsSuccessStatusCode.Should().BeTrue(BecauseCleanupMustSucceed); } } }
static async Task GetRequest(string ID) { switch (ID) { //Get Request case "Get": Console.WriteLine("Enter id:"); int id = Convert.ToInt32(Console.ReadLine()); using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:49632/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response; //id == 0 means select all records if (id == 0) { response = await client.GetAsync("api/Weather"); if (response.IsSuccessStatusCode) { WeatherClient[] reports = await response.Content.ReadAsAsync <WeatherClient[]>(); foreach (var report in reports) { Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}", report.City, report.Temperature, report.Humidity, report.Precipitation, report.Wind); } } } else { response = await client.GetAsync("api/Weather/" + id); if (response.IsSuccessStatusCode) { WeatherClient report = await response.Content.ReadAsAsync <WeatherClient>(); Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}", report.City, report.Temperature, report.Humidity, report.Precipitation, report.Wind); } } } break; //Post Request case "Post": WeatherClient newReport = new WeatherClient(); Console.WriteLine("Enter data:"); Console.WriteLine("Enter City:"); newReport.City = Console.ReadLine(); Console.WriteLine("Enter Temperature:"); newReport.Temperature = Console.ReadLine(); Console.WriteLine("Enter Precipitation:"); newReport.Precipitation = Console.ReadLine(); Console.WriteLine("Enter Humidity:"); newReport.Humidity = Console.ReadLine(); Console.WriteLine("Enter Wind:"); newReport.Wind = Console.ReadLine(); using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:49632/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.PostAsJsonAsync("api/Weather", newReport); if (response.IsSuccessStatusCode) { bool result = await response.Content.ReadAsAsync <bool>(); if (result) { Console.WriteLine("Report Submitted"); } else { Console.WriteLine("An error has occurred"); } } } break; //Delete Request case "Delete": Console.WriteLine("Enter id:"); int delete = Convert.ToInt32(Console.ReadLine()); using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:49632/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.DeleteAsync("api/Weather/" + delete); if (response.IsSuccessStatusCode) { bool result = await response.Content.ReadAsAsync <bool>(); if (result) { Console.WriteLine("Report Deleted"); } else { Console.WriteLine("An error has occurred"); } } } break; } }
public async Task UpdateAsync_UsingNewlyCreatedTodoItem_MustSucceed() { // Arrange using HttpClient httpClient = await webApplicationFactory.CreateClientWithJwtAsync(); long?id = null; try { string name = $"it--{nameof(UpdateAsync_UsingNewlyCreatedTodoItem_MustSucceed)}--{Guid.NewGuid():N}"; bool isComplete = DateTime.UtcNow.Ticks % 2 == 0; var newTodoItemInfo = new NewTodoItemModel { Name = name, IsComplete = isComplete }; HttpResponseMessage response = await httpClient.PostAsJsonAsync(BaseUrl, newTodoItemInfo); response.IsSuccessStatusCode.Should().BeTrue(BecauseNewEntityHasBeenCreated); id = await response.Content.ReadAsAsync <long>(); var updateTodoItemModel = new UpdateTodoItemModel { IsComplete = !newTodoItemInfo.IsComplete, Name = $"CHANGED--{newTodoItemInfo.Name}" }; // Act response = await httpClient.PutAsJsonAsync($"{BaseUrl}/{id}", updateTodoItemModel); // Assert using (new AssertionScope()) { response.IsSuccessStatusCode.Should().BeTrue(BecauseEntityHasBeenPreviouslyCreated); response.StatusCode.Should().Be(HttpStatusCode.NoContent); response = await httpClient.GetAsync($"{BaseUrl}/{id}"); response.IsSuccessStatusCode.Should().BeTrue("an entity has been previously updated"); response.StatusCode.Should().Be(HttpStatusCode.OK); TodoItemModel todoItemModel = await response.Content.ReadAsAsync <TodoItemModel>(); todoItemModel.Should().NotBeNull(BecauseEntityHasBeenPreviouslyCreated); todoItemModel.Id.Should().Be(id); todoItemModel.IsComplete.Should().Be(updateTodoItemModel.IsComplete.Value); todoItemModel.Name.Should().Be(updateTodoItemModel.Name); } } finally { if (id.HasValue) { HttpResponseMessage response = await httpClient.DeleteAsync($"{BaseUrl}/{id}"); response.IsSuccessStatusCode.Should().BeTrue(BecauseCleanupMustSucceed); } } }
public static async Task <HttpResponseMessage> PostData <T>(string url, T data) { var res = await _client.PostAsJsonAsync(url, data); return(res); }
public static string Detect() { using (var client = new HttpClient()) { var scoreRequest = new { Inputs = new Dictionary<string, List<Dictionary<string, string>>>() { { "input1", new List<Dictionary<string, string>>(){new Dictionary<string, string>(){ { "class", "1" }, { "age", "45" }, { "heartbeat", "200" }, { "sp02", "70" }, { "height", "175" }, { "weight", "120" }, { "sex", "1" }, { "chol", "4" }, { "temp", "38" }, { "arythmie","1" } } } }, }, GlobalParameters = new Dictionary<string, string>() { } }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "+/yacIXKwg/gPh+mqVerS/j0WDLK1DcsY/FLVpj3VeuCapvcdMy4EELtzIZfUAK1eA68NvEj7UaSkF4QvJr4oQ=="); client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/23533c5facbe443ca4e19c86e7493546/services/89cd6441d6d344509ecbf5e05cdc9433/execute?api-version=2.0&format=swagger"); HttpResponseMessage response = client.PostAsJsonAsync("", scoreRequest).Result; string result; if (response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; } else { result = response.Content.ReadAsStringAsync().Result; } var test = JsonConvert.DeserializeObject<CardiacObject>(result, new JsonSerializerSettings() { FloatFormatHandling = FloatFormatHandling.String }); var root = JsonConvert.DeserializeObject<CardiacObject>(result, new DecimalFormatConverter()); var Sp = root.Results.output1.FirstOrDefault().ScoredProbabilities; var t2 = Double.Parse(Sp.Replace(".",",")); t2 = t2 * 100; return ((int)t2).ToString(); } }
static async Task Run() { try { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:21265/"); // base URL for API Controller i.e. RESTFul service // add an Accept header for JSON client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // 1 // get weather info for all cities // GET ../api/weather HttpResponseMessage response = await client.GetAsync("weather/"); // accessing the Result property blocks if (response.IsSuccessStatusCode) // 200.299 { // read result var weather = await response.Content.ReadAsAsync <IEnumerable <Weather> >(); foreach (var w in weather) { Console.WriteLine(w.City + " " + w.Temp + "C " + w.WindSpeed + "km/h " + w.Condition + " warning: " + w.WeatherWarning); } } else { Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } // 2 // get weather info for Dublin // GET ../api/weather/Dublin Weather weatherInfo = new Weather(); response = await client.GetAsync("weather/city/Dublin"); if (response.IsSuccessStatusCode) { // read result weatherInfo = await response.Content.ReadAsAsync <Weather>(); Console.WriteLine(weatherInfo.City + " " + weatherInfo.Temp + "C " + weatherInfo.WindSpeed + "km/h " + weatherInfo.Condition + " Warning: " + weatherInfo.WeatherWarning); } else { Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } // 3 // update by Put to api/weather/Dublin - now its sunny // weatherInfo.Condition = Conditions.sunny; weatherInfo.Condition = "Sunny"; response = await client.PutAsJsonAsync("weather/update/Dublin", weatherInfo); if (response.IsSuccessStatusCode) { Console.WriteLine(response.Content + " " + "city updated"); } else { Console.WriteLine("update failed"); Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } // 4 // get cities with weather warnings in place // GET ../api/weather?warning=true response = await client.GetAsync("weather/warning/true"); if (response.IsSuccessStatusCode) { // read result var cities = await response.Content.ReadAsAsync <IEnumerable <Weather> >(); foreach (var city in cities) { Console.WriteLine(city.City + " " + city.Condition); } } else { Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } response = await client.DeleteAsync("weather/delete/Dublin"); if (response.IsSuccessStatusCode) { Console.WriteLine("City deleted "); } else { Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } // POST /api/SMSGateway with a txt message serialised in request body // send a txt msg Weather newCity = new Weather() { City = "London", WindSpeed = 8, Temp = 8, Condition = "cold", WeatherWarning = true }; response = await client.PostAsJsonAsync("weather/add", newCity); if (response.IsSuccessStatusCode) { Console.WriteLine("Added City " + newCity.City + " with " + newCity.Condition + " conditions"); } else { Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase); } // Delete/weather/delete/01 4444444 } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public User CreateUser(User user) { user = _client.PostAsJsonAsync("users", user).Result.Content.ReadAsAsync <User>().Result; return(user); }
public async Task Start() { var client = new HttpClient(); const string userName = "******"; const string password = "******"; //const string userName = "******"; //const string password = "******"; try { client.BaseAddress = new Uri("https://caseapi.allegiancetech.com/CaseManagement.svc/"); //client.BaseAddress = new Uri("https://caseapiemea.allegiancetech.com/CaseManagement.svc/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var authPayload = new JObject { { "userName", userName }, { "password", password } }; var response = await client.PostAsJsonAsync("authenticate", authPayload); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.ReasonPhrase); return; } var authResponse = await response.Content.ReadAsAsync <JObject>(); var accessToken = authResponse["AuthenticateResult"]["token"]; var userId = authResponse["AuthenticateResult"]["userId"]; var caseRequest = new JObject { { "token", accessToken } }; response = await client.PostAsJsonAsync("getMobileCaseInboxItems", caseRequest); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.ReasonPhrase); return; } var caseData = await response.Content.ReadAsAsync <JObject>(); if (caseData != null) { var countProperty = caseData["GetMobileCaseInboxItemsResult"]["caseMobileInboxData"]["Rows"]; Console.WriteLine($"Total number of cases found: {countProperty}"); } } catch (Exception error) { Console.WriteLine(error.Message); } }
public async void Insert_Data() { //App.Current.Properties["Description"] = selectProduct.DESCR; //App.Current.Properties["Bin"] = selectProduct.BIN; //else if (selectProduct.DESCR == "" || selectProduct.DESCR == null) //{ // MessageBox.Show("DESCRIPTION Should not be blank.."); //} //else if (selectProduct.BIN == "" || selectProduct.BIN == null) //{ // MessageBox.Show("BIN Should not be blank.."); //} if (imageFile != null) { string file = imageFile.Name; var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); // get your 'Uploaded' folder var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "uploaded\\Product")); if (!dir.Exists) { dir.Create(); } // Copy file to your folder imageFile.CopyTo(System.IO.Path.Combine(dir.FullName + "\\", file), true); //Prepare ProductPicture Model ProductModel ppm = new ProductModel(); ppm.PICTURE_NAME = file; ppm.PRODUCT_CODE = selectProduct.PRODUCT_CODE; if (PRODUCT_CODE == "" || PRODUCT_CODE == null) { MessageBox.Show("PRODUCT CODE Should not be blank.."); } else { try { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.BaseAddress = new Uri(GlobalData.gblApiAdress); var response = await client.PostAsJsonAsync("api/ProductAPI/CreateProductPicture/", ppm); if (response.StatusCode.ToString() == "OK") { MessageBox.Show("Product Added Successfully"); Cancel_Product(); ProductDocument _PDVM = new ProductDocument(); _PDVM.ShowDialog(); } ////// //Refresh List } catch (Exception) { throw; } MessageBox.Show("Picture saved successfully"); foreach (System.Windows.Window window in System.Windows.Application.Current.Windows) { if (window.DataContext == this) { window.Close(); } } } } else { MessageBox.Show("Please Upload Image..."); } }
private async void btnSimpanAkun_Click(object sender, EventArgs e) { try { if (tbOldPassAkun.Text.ToString().Trim() != "" && tbNewPassAkun.Text.ToString().Trim() != "") { if (check.Equals("simpan")) { Debug.WriteLine("masuuuk simpan"); var pass = tbNewPassAkun.Text.ToString(); Debug.WriteLine(pass); User user = new User { id_user = id, password = tbNewPassAkun.Text.ToString() }; var response = client.PostAsJsonAsync("api/user", user).Result; if (response.IsSuccessStatusCode) { var a = await response.Content.ReadAsStringAsync(); Debug.WriteLine(a); DataTable t = await GetAkun(); t.Columns.Remove("role"); t.Columns.Remove("name"); dgAkunMetro.DataSource = t; dgAkunMetro.Columns[0].HeaderText = "ID"; //nama kolom sesuai indeks dgAkunMetro.Columns[1].HeaderText = "Nama"; dgAkunMetro.DataBindingComplete += (o, _) => { var dataGridView = o as DataGridView; if (dataGridView != null) { dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dataGridView.Columns[dataGridView.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } }; MessageBox.Show("Berhasil Mengganti Password"); } } else if (check.Equals("edit")) { var pass = tbNewPassAkun.Text.ToString(); User user = new User { id_user = id, password = tbNewPassAkun.Text.ToString() }; HttpResponseMessage response = await client.PutAsJsonAsync( $"api/users/{user.id_user}", user); response.EnsureSuccessStatusCode(); user = await response.Content.ReadAsAsync <User>(); DataTable t = await GetAkun(); t.Columns.Remove("role"); t.Columns.Remove("name"); dgAkunMetro.Columns[0].HeaderText = "ID"; //nama kolom sesuai indeks dgAkunMetro.Columns[1].HeaderText = "Nama"; dgAkunMetro.DataSource = t; dgAkunMetro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dgAkunMetro.DataBindingComplete += (o, _) => { var dataGridView = o as DataGridView; if (dataGridView != null) { dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; dataGridView.Columns[dataGridView.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } }; MessageBox.Show("Berhasil Update Password"); } clearInput(); disableInput(); } } catch (Exception exc) { MessageBox.Show(exc.Message); } }
//public ConferenceApiService(IHttpClientFactory httpClientFactory) //{ // HttpClient = httpClientFactory.CreateClient("Api"); //} async Task IConferenceService.Add(ConferenceModel model) { await HttpClient.PostAsJsonAsync("/v1/conference", model); }
public IActionResult Regist(RegisterInputModel data) { RegisterInputModel dataRegister = new RegisterInputModel(); dataRegister.FirstName = data.FirstName; dataRegister.LastName = data.LastName; dataRegister.Username = data.Username; dataRegister.NamaPerusahaan = data.NamaPerusahaan; dataRegister.EmailPerusahaan = data.EmailPerusahaan; dataRegister.NoTelp = data.NoTelp; dataRegister.Kategori = data.Kategori; dataRegister.NPWP = data.NPWP; dataRegister.Website = data.Website; dataRegister.Alamat = data.Alamat; dataRegister.Catatan = data.Catatan; dataRegister.Password = data.Password; JsonConvert.SerializeObject(dataRegister); using (var client = new HttpClient()) { client.BaseAddress = new Uri(BaseAPI + "MediaBuyer/"); //HTTP POST var postTask = client.PostAsJsonAsync <RegisterInputModel>("Register", dataRegister); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { var content = result.Content.ReadAsStringAsync(); RegisterResponseModel logincontent = Newtonsoft.Json.JsonConvert.DeserializeObject <RegisterResponseModel>(content.Result); if (logincontent.data != null && logincontent.data.UserID.ToString() != "") { HttpContext.Session.SetString(SessionKeyCurrent, ""); HttpContext.Session.SetString(SessionKeyError, ""); return(RedirectToAction("Index", "Home")); } else { HttpContext.Session.SetString(SessionKeyCurrent, "true"); HttpContext.Session.SetString(SessionKeyError, "Gagal Daftar."); return(RedirectToAction("ChangePassword", "Profile")); } } } #region Old //if (conpassword == data.Password) //{ // if (registype == "MO") // { // using (var client = new HttpClient()) // { // client.BaseAddress = new Uri(BaseAPI + "MediaOwner/"); // //HTTP POST // var postTask = client.PostAsJsonAsync<RegisterInputModel>("Register", dataRegister); // postTask.Wait(); // var result = postTask.Result; // if (result.IsSuccessStatusCode) // { // var content = result.Content.ReadAsStringAsync(); // RegisterResponseModel logincontent = Newtonsoft.Json.JsonConvert.DeserializeObject<RegisterResponseModel>(content.Result); // if (logincontent.data != null && logincontent.data.UserID.ToString() != "") // { // HttpContext.Session.SetString(SessionKeyCurrent, ""); // HttpContext.Session.SetString(SessionKeyError, ""); // return RedirectToAction("Index", "Home"); // } // else // { // HttpContext.Session.SetString(SessionKeyCurrent, "true"); // HttpContext.Session.SetString(SessionKeyError, "Gagal Daftar."); // return RedirectToAction("ChangePassword", "Profile"); // } // } // } // } // else if (registype == "MB") // { // using (var client = new HttpClient()) // { // client.BaseAddress = new Uri(BaseAPI + "MediaBuyer/"); // //HTTP POST // var postTask = client.PostAsJsonAsync<RegisterInputModel>("Register", dataRegister); // postTask.Wait(); // var result = postTask.Result; // if (result.IsSuccessStatusCode) // { // var content = result.Content.ReadAsStringAsync(); // RegisterResponseModel logincontent = Newtonsoft.Json.JsonConvert.DeserializeObject<RegisterResponseModel>(content.Result); // if (logincontent.data != null && logincontent.data.UserID.ToString() != "") // { // HttpContext.Session.SetString(SessionKeyCurrent, ""); // HttpContext.Session.SetString(SessionKeyError, ""); // return RedirectToAction("Index", "Home"); // } // else // { // HttpContext.Session.SetString(SessionKeyCurrent, "true"); // HttpContext.Session.SetString(SessionKeyError, "Gagal Daftar."); // return RedirectToAction("ChangePassword", "Profile"); // } // } // } // } //} #endregion HttpContext.Session.SetString(SessionKeyCurrent, "true"); HttpContext.Session.SetString(SessionKeyError, "Terjadi kesalahan server. Hubungi admin."); return(RedirectToAction("ChangePassword", "Profile")); }
public Task AddingMovie(MovieDataModel movieToAdd) { var uri = @"http://localhost:5000/api/Movies/add"; return(_Http.PostAsJsonAsync(uri, movieToAdd)); }
/// <summary> /// Register the application with a Spring-Boot-Admin server /// </summary> /// <param name="builder"><see cref="IApplicationBuilder"/></param> /// <param name="configuration">App configuration. Will be retrieved from builder.ApplicationServices if not provided</param> /// <param name="httpClient">A customized HttpClient. [Bring your own auth]</param> public static void RegisterWithSpringBootAdmin(this IApplicationBuilder builder, IConfiguration configuration = null, HttpClient httpClient = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (configuration is null) { configuration = builder.ApplicationServices.GetRequiredService <IConfiguration>(); } var logger = builder.ApplicationServices.GetService <ILogger <SpringBootAdminClientOptions> >(); var appInfo = builder.ApplicationServices.GetApplicationInstanceInfo(); var options = new SpringBootAdminClientOptions(configuration, appInfo); var mgmtOptions = new ManagementEndpointOptions(configuration); var healthOptions = new HealthEndpointOptions(configuration); var basePath = options.BasePath.TrimEnd('/'); httpClient ??= HttpClientHelper.GetHttpClient(options.ValidateCertificates, ConnectionTimeoutMs); var app = new Application() { Name = options.ApplicationName ?? "Steeltoe", HealthUrl = new Uri($"{basePath}{mgmtOptions.Path}/{healthOptions.Path}"), ManagementUrl = new Uri($"{basePath}{mgmtOptions.Path}"), ServiceUrl = new Uri($"{basePath}/"), Metadata = new Dictionary <string, object> { { "startup", DateTime.Now } }, }; app.Metadata.Merge(options.Metadata); var lifetime = builder.ApplicationServices.GetService <IHostApplicationLifetime>(); lifetime.ApplicationStarted.Register(() => { logger?.LogInformation("Registering with Spring Boot Admin Server at {0}", options.Url); var result = httpClient.PostAsJsonAsync($"{options.Url}/instances", app).GetAwaiter().GetResult(); if (result.IsSuccessStatusCode) { RegistrationResult = result.Content.ReadFromJsonAsync <RegistrationResult>().GetAwaiter().GetResult(); } else { logger.LogError($"Error registering with SpringBootAdmin {result}"); } }); lifetime.ApplicationStopped.Register(() => { if (RegistrationResult == null || string.IsNullOrEmpty(RegistrationResult.Id)) { return; } _ = httpClient.DeleteAsync($"{options.Url}/instances/{RegistrationResult.Id}").GetAwaiter().GetResult(); }); }
public async Task <HttpResponseMessage> UpdateSettings(string clockName, string?userName, string?administratorPassword, ClockSettings settings) => await Http.PostAsJsonAsync($"api/clocks/{clockName}/settings?user={userName}&password={administratorPassword}", settings).ConfigureAwait(false);
public Task <HttpResponseMessage> Post <T>(string url, T body) { return(_client.PostAsJsonAsync(url, body)); }
private void btnHoanThanh_Click(object sender, EventArgs e) { if (txtTenCT.Text == "" || dtpTuNgay == null || dtpDenNgay == null) { MessageBox.Show("Nhập đầy đủ thông tin chương trình khuyến mãi!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (radKMDH.Checked == true) { string tenct = txtTenCT.Text; string mota = txtMoTa.Text; DateTime ngaybd = Convert.ToDateTime(dtpTuNgay.Text); DateTime ngaykt = Convert.ToDateTime(dtpDenNgay.Text); float chietkhau = float.Parse(txtCK.Text); KhuyenMaiDTO CTKM = new KhuyenMaiDTO(tenct, mota, ngaybd, ngaykt, chietkhau); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseAddress); //HTTP POST var postTask = client.PostAsJsonAsync <KhuyenMaiDTO>("KhuyenMai", CTKM); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { MessageBox.Show("thêm thành công 1 phiếu đổi!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } } else { //KhuyenMaiDAO.Instance.HoanThanh(listCTKM, txtTenCT.Text, txtMoTa.Text, Convert.ToDateTime(dtpTuNgay.Text), Convert.ToDateTime(dtpDenNgay.Text)); string tenct = txtTenCT.Text; string mota = txtMoTa.Text; DateTime ngaybd = Convert.ToDateTime(dtpTuNgay.Text); DateTime ngaykt = Convert.ToDateTime(dtpDenNgay.Text); KhuyenMaiDTO CTKM = new KhuyenMaiDTO(listCT, tenct, mota, ngaybd, ngaykt); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseAddress); //HTTP POST var postTask = client.PostAsJsonAsync <KhuyenMaiDTO>("HoanThanh", CTKM); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { MessageBox.Show("thêm thành công 1 phiếu đổi!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } } fKhuyenMai KM = new fKhuyenMai(); this.Hide(); KM.ShowDialog(); this.Show(); }
static async Task InvokeRequestResponseService() { using (var client = new HttpClient()) { var scoreRequest = new { Inputs = new Dictionary<string, StringTable>() { { "input1", new StringTable() { ColumnNames = new string[] {"age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "income"}, Values = new string[,] { { "28", "Private", "338409", "Bachelors", "13", "Married-civ-spouse", "Prof-specialty", "Wife", "Black", "Female", "0", "0", "40", "Cuba", "value" } } } }, }, GlobalParameters = new Dictionary<string, string>() { } }; const string apiKey = "ipzYJXleUG6BTzkAcTfrrBLcvEE7XLFs28hVOHRXsZCMDEIqyRoHBQDV16TJB8LoTq7oY4d9mgmXPKsLq6nn+w=="; // Replace this with the API key for the web service client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/f05b36fa1fa84506a4f7d1fd20e5b879/services/5ed21bc4d8134ab7a6984eb9a5660ad1/execute?api-version=2.0&details=true"); // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application. // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context. // For instance, replace code such as: // result = await DoSomeTask() // with the following: // result = await DoSomeTask().ConfigureAwait(false) HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); Console.WriteLine("Result: {0}", result); } else { Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode)); // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure Console.WriteLine(response.Headers.ToString()); string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } } }