Chart.cs 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. //
  5. // Purpose: This file contains classes, which are used for Image
  6. // creation and chart painting. This file has also a
  7. // class, which is used for Paint events arguments.
  8. //
  9. using System;
  10. using System.Windows.Forms;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.ComponentModel;
  14. using System.ComponentModel.Design;
  15. using System.Data;
  16. using System.Diagnostics.CodeAnalysis;
  17. using System.Drawing;
  18. using System.Drawing.Design;
  19. using System.Drawing.Drawing2D;
  20. using System.Drawing.Imaging;
  21. using System.Drawing.Text;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Reflection;
  25. using System.Runtime.InteropServices;
  26. using System.Security;
  27. using FastReport.DataVisualization.Charting.Borders3D;
  28. using FastReport.DataVisualization.Charting.Utilities;
  29. namespace FastReport.DataVisualization.Charting
  30. {
  31. using FontStyle = System.Drawing.FontStyle;
  32. /// <summary>
  33. /// ChartImage class adds image type and data binding functionality to
  34. /// the base ChartPicture class.
  35. /// </summary>
  36. internal class ChartImage : ChartPicture
  37. {
  38. #region Fields
  39. // Private data members, which store properties values
  40. private int _compression = 0;
  41. // Chart data source object
  42. private object _dataSource = null;
  43. // Indicates that control was bound to the data source
  44. internal bool boundToDataSource = false;
  45. #endregion
  46. #region Constructor
  47. /// <summary>
  48. /// Chart internal constructor.
  49. /// </summary>
  50. /// <param name="container">Service container</param>
  51. internal ChartImage(IServiceContainer container)
  52. : base(container)
  53. {
  54. }
  55. #endregion // Constructor
  56. #region Properties
  57. /// <summary>
  58. /// Gets or sets the data source for the Chart object.
  59. /// </summary>
  60. [
  61. SRCategory("CategoryAttributeData"),
  62. Bindable(true),
  63. SRDescription("DescriptionAttributeDataSource"),
  64. DefaultValue(null),
  65. DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  66. SerializationVisibilityAttribute(SerializationVisibility.Hidden)
  67. ]
  68. public object DataSource
  69. {
  70. get
  71. {
  72. return _dataSource;
  73. }
  74. set
  75. {
  76. if(_dataSource != value)
  77. {
  78. _dataSource = value;
  79. this.boundToDataSource = false;
  80. }
  81. }
  82. }
  83. /// <summary>
  84. /// Image compression value
  85. /// </summary>
  86. [
  87. SRCategory("CategoryAttributeImage"),
  88. Bindable(true),
  89. DefaultValue(0),
  90. SRDescription("DescriptionAttributeChartImage_Compression"),
  91. ]
  92. public int Compression
  93. {
  94. get
  95. {
  96. return _compression;
  97. }
  98. set
  99. {
  100. if(value < 0 || value > 100)
  101. {
  102. throw (new ArgumentOutOfRangeException("value", SR.ExceptionChartCompressionInvalid));
  103. }
  104. _compression = value;
  105. }
  106. }
  107. #endregion
  108. #region Methods
  109. #region Image Manipulation
  110. /// <summary>
  111. /// Saves image into the metafile stream.
  112. /// </summary>
  113. /// <param name="imageStream">Image stream.</param>
  114. /// <param name="emfType">Image stream.</param>
  115. [SecuritySafeCritical]
  116. public void SaveIntoMetafile(Stream imageStream, EmfType emfType)
  117. {
  118. // Check arguments
  119. if (imageStream == null)
  120. throw new ArgumentNullException("imageStream");
  121. // Create temporary Graphics object for metafile
  122. using (Bitmap bitmap = new Bitmap(this.Width, this.Height))
  123. {
  124. using (Graphics newGraphics = Graphics.FromImage(bitmap))
  125. {
  126. IntPtr hdc = IntPtr.Zero;
  127. try
  128. {
  129. #if DESIGNER
  130. System.Security.Permissions.SecurityPermission securityPermission = new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode);
  131. securityPermission.Demand();
  132. #endif
  133. hdc = newGraphics.GetHdc();
  134. // Create metafile object to record.
  135. using (Metafile metaFile = new Metafile(
  136. imageStream,
  137. hdc,
  138. new Rectangle(0, 0, this.Width, this.Height),
  139. MetafileFrameUnit.Pixel,
  140. emfType))
  141. {
  142. // Create graphics object to record metaFile.
  143. using (IGraphics metaGraphics = new FastReport.GdiGraphics(metaFile))
  144. {
  145. // Note: Fix for issue #3674. Some 3D borders shadows may be drawn outside
  146. // of image boundaries. This causes issues when generated EMF file
  147. // is placed in IE. Image looks shifted down and hot areas do not align.
  148. if (this.BorderSkin.SkinStyle != BorderSkinStyle.None)
  149. {
  150. metaGraphics.Clip = new Region(new Rectangle(0, 0, this.Width, this.Height));
  151. }
  152. // Draw chart in the metafile
  153. this.ChartGraph.IsMetafile = true;
  154. this.Paint(metaGraphics, false);
  155. this.ChartGraph.IsMetafile = false;
  156. }
  157. }
  158. }
  159. finally
  160. {
  161. if (hdc != IntPtr.Zero)
  162. {
  163. newGraphics.ReleaseHdc(hdc);
  164. }
  165. }
  166. }
  167. }
  168. }
  169. public Bitmap GetImage()
  170. {
  171. return this.GetImage(96);
  172. }
  173. /// <summary>
  174. /// Create Image and draw chart picture
  175. /// </summary>
  176. public Bitmap GetImage(float resolution)
  177. {
  178. // Create a new bitmap
  179. Bitmap image = null;
  180. while (image == null)
  181. {
  182. bool failed = true;
  183. try
  184. {
  185. image = new Bitmap(Math.Max(1,Width), Math.Max(1,Height));
  186. image.SetResolution(resolution, resolution);
  187. failed = false;
  188. }
  189. catch (ArgumentException)
  190. {
  191. failed = true;
  192. }
  193. catch (OverflowException)
  194. {
  195. failed = true;
  196. }
  197. catch (InvalidOperationException)
  198. {
  199. failed = true;
  200. }
  201. catch (ExternalException)
  202. {
  203. failed = true;
  204. }
  205. if (failed)
  206. {
  207. // if failed to create the image, decrease the size and the resolution of the chart
  208. image = null;
  209. float newResolution = Math.Max(resolution / 2, 96);
  210. Width = (int)Math.Ceiling(Width * newResolution / resolution);
  211. Height = (int)Math.Ceiling(Height * newResolution / resolution);
  212. resolution = newResolution;
  213. }
  214. }
  215. // Creates a new Graphics object from the
  216. // specified Image object.
  217. IGraphics offScreen = new FastReport.GdiGraphics(image);
  218. Color backGroundColor;
  219. if (this.BackColor != Color.Empty)
  220. backGroundColor = this.BackColor;
  221. else
  222. backGroundColor = Color.White;
  223. // Get the page color if border skin is visible.
  224. if (GetBorderSkinVisibility() &&
  225. this.BorderSkin.PageColor != Color.Empty)
  226. {
  227. backGroundColor = this.BorderSkin.PageColor;
  228. }
  229. // draw a rctangle first with the size of the control, this prevent strange behavior when printing in the reporting services,
  230. // without this rectangle, the printed picture is blurry
  231. Pen pen = new Pen(backGroundColor);
  232. offScreen.DrawRectangle(pen, 0, 0, Width, Height);
  233. pen.Dispose();
  234. // Paint the chart
  235. Paint( offScreen , false);
  236. // Dispose Graphic object
  237. offScreen.Dispose();
  238. // Return reference to the image
  239. return image;
  240. }
  241. #endregion // Image Manipulation
  242. #region Data Binding
  243. /// <summary>
  244. /// Checks if the type of the data source is valid.
  245. /// </summary>
  246. /// <param name="dataSource">Data source object to test.</param>
  247. /// <returns>True if valid data source object.</returns>
  248. static internal bool IsValidDataSource(object dataSource)
  249. {
  250. if( null != dataSource &&
  251. (
  252. dataSource is IEnumerable ||
  253. dataSource is DataSet ||
  254. dataSource is DataView ||
  255. dataSource is DataTable ||
  256. dataSource is System.Data.Common.DbCommand ||
  257. dataSource is System.Data.Common.DbDataAdapter ||
  258. // ADDED: for VS2005 compatibility, DT Nov 25, 2005
  259. dataSource.GetType().GetInterface("IDataSource") != null
  260. // END ADDED
  261. )
  262. )
  263. {
  264. return true;
  265. }
  266. return false;
  267. }
  268. /// <summary>
  269. /// Gets an list of the data source member names.
  270. /// </summary>
  271. /// <param name="dataSource">Data source object to get the members for.</param>
  272. /// <param name="usedForYValue">Indicates that member will be used for Y values.</param>
  273. /// <returns>List of member names.</returns>
  274. [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
  275. Justification = "Too large of a code change to justify making this change")]
  276. static internal ArrayList GetDataSourceMemberNames(object dataSource, bool usedForYValue)
  277. {
  278. ArrayList names = new ArrayList();
  279. if (dataSource != null)
  280. {
  281. // ADDED: for VS2005 compatibility, DT Nov 25, 2004
  282. if (dataSource.GetType().GetInterface("IDataSource") != null)
  283. {
  284. try
  285. {
  286. MethodInfo m = dataSource.GetType().GetMethod("Select");
  287. if (m != null)
  288. {
  289. if (m.GetParameters().Length == 1)
  290. {
  291. // SQL derived datasource
  292. Type selectArgsType = dataSource.GetType().Assembly.GetType("System.Web.UI.DataSourceSelectArguments", true);
  293. ConstructorInfo ci = selectArgsType.GetConstructor(new Type[] { });
  294. dataSource = m.Invoke(dataSource, new object[] { ci.Invoke(new object[] { }) });
  295. }
  296. else
  297. {
  298. // object data source
  299. dataSource = m.Invoke(dataSource, new object[] { });
  300. }
  301. }
  302. }
  303. catch (TargetException)
  304. {
  305. }
  306. catch (TargetInvocationException)
  307. {
  308. }
  309. }
  310. // END ADDED
  311. // Check all DataTable based data souces
  312. DataTable dataTable = null;
  313. if (dataSource is DataTable)
  314. {
  315. dataTable = (DataTable)dataSource;
  316. }
  317. else if (dataSource is DataView)
  318. {
  319. dataTable = ((DataView)dataSource).Table;
  320. }
  321. else if (dataSource is DataSet && ((DataSet)dataSource).Tables.Count > 0)
  322. {
  323. dataTable = ((DataSet)dataSource).Tables[0];
  324. }
  325. else if (dataSource is System.Data.Common.DbDataAdapter)
  326. {
  327. dataTable = new DataTable();
  328. dataTable.Locale = CultureInfo.CurrentCulture;
  329. dataTable = ((System.Data.Common.DbDataAdapter)dataSource).FillSchema(dataTable, SchemaType.Mapped);
  330. }
  331. else if (dataSource is System.Data.Common.DbDataReader)
  332. {
  333. // Add table columns names
  334. for (int fieldIndex = 0; fieldIndex < ((System.Data.Common.DbDataReader)dataSource).FieldCount; fieldIndex++)
  335. {
  336. if (!usedForYValue || ((System.Data.Common.DbDataReader)dataSource).GetFieldType(fieldIndex) != typeof(string))
  337. {
  338. names.Add(((System.Data.Common.DbDataReader)dataSource).GetName(fieldIndex));
  339. }
  340. }
  341. }
  342. else if (dataSource is System.Data.Common.DbCommand)
  343. {
  344. System.Data.Common.DbCommand command = (System.Data.Common.DbCommand)dataSource;
  345. if (command.Connection != null)
  346. {
  347. command.Connection.Open();
  348. System.Data.Common.DbDataReader dataReader = command.ExecuteReader();
  349. if (dataReader.Read())
  350. {
  351. for (int fieldIndex = 0; fieldIndex < dataReader.FieldCount; fieldIndex++)
  352. {
  353. if (!usedForYValue || dataReader.GetFieldType(fieldIndex) != typeof(string))
  354. {
  355. names.Add(dataReader.GetName(fieldIndex));
  356. }
  357. }
  358. }
  359. dataReader.Close();
  360. command.Connection.Close();
  361. }
  362. }
  363. // Check if DataTable was set
  364. if (dataTable != null)
  365. {
  366. // Add table columns names
  367. foreach (DataColumn column in dataTable.Columns)
  368. {
  369. if (!usedForYValue || column.DataType != typeof(string))
  370. {
  371. names.Add(column.ColumnName);
  372. }
  373. }
  374. }
  375. else if (names.Count == 0 && dataSource is ITypedList)
  376. {
  377. foreach (PropertyDescriptor pd in ((ITypedList)dataSource).GetItemProperties(null))
  378. {
  379. if (!usedForYValue || pd.PropertyType != typeof(string))
  380. {
  381. names.Add(pd.Name);
  382. }
  383. }
  384. }
  385. else if (names.Count == 0 && dataSource is IEnumerable)
  386. {
  387. // .Net 2.0 ObjectDataSource processing
  388. IEnumerator e = ((IEnumerable)dataSource).GetEnumerator();
  389. e.Reset();
  390. e.MoveNext();
  391. foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(e.Current))
  392. {
  393. if (!usedForYValue || pd.PropertyType != typeof(string))
  394. {
  395. names.Add(pd.Name);
  396. }
  397. }
  398. }
  399. // Check if list still empty
  400. if (names.Count == 0)
  401. {
  402. // Add first column or any data member name
  403. names.Add("0");
  404. }
  405. }
  406. return names;
  407. }
  408. /// <summary>
  409. /// Data binds control to the data source
  410. /// </summary>
  411. [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily",
  412. Justification="Too large of a code change to justify making this change")]
  413. internal void DataBind()
  414. {
  415. // Set bound flag
  416. this.boundToDataSource = true;
  417. object dataSource = this.DataSource;
  418. if (dataSource != null)
  419. {
  420. // Convert data adapters to command object
  421. if (dataSource is System.Data.Common.DbDataAdapter)
  422. {
  423. dataSource = ((System.Data.Common.DbDataAdapter)dataSource).SelectCommand;
  424. }
  425. // Convert data source to recognizable source for the series
  426. if (dataSource is DataSet && ((DataSet)dataSource).Tables.Count > 0)
  427. {
  428. dataSource = ((DataSet)dataSource).DefaultViewManager.CreateDataView(((DataSet)dataSource).Tables[0]);
  429. }
  430. else if (dataSource is DataTable)
  431. {
  432. dataSource = new DataView((DataTable)dataSource);
  433. }
  434. else if (dataSource is System.Data.Common.DbCommand)
  435. {
  436. System.Data.Common.DbCommand command = (System.Data.Common.DbCommand)dataSource;
  437. command.Connection.Open();
  438. System.Data.Common.DbDataReader dataReader = command.ExecuteReader();
  439. this.DataBind(dataReader, null);
  440. dataReader.Close();
  441. command.Connection.Close();
  442. return;
  443. }
  444. else if (dataSource is IList)
  445. {
  446. dataSource = dataSource as IList;
  447. }
  448. else if (dataSource is IListSource )
  449. {
  450. if (((IListSource)dataSource).ContainsListCollection && ((IListSource)dataSource).GetList().Count > 0)
  451. {
  452. dataSource = ((IListSource)dataSource).GetList()[0] as IEnumerable;
  453. }
  454. else
  455. {
  456. dataSource = ((IListSource)dataSource).GetList();
  457. }
  458. }
  459. else
  460. {
  461. dataSource = dataSource as IEnumerable;
  462. }
  463. // Data bind
  464. DataBind(dataSource as IEnumerable, null);
  465. }
  466. }
  467. /// <summary>
  468. /// Data binds control to the data source
  469. /// </summary>
  470. /// <param name="dataSource">Data source to bind to.</param>
  471. /// <param name="seriesList">List of series to bind.</param>
  472. internal void DataBind(IEnumerable dataSource, ArrayList seriesList)
  473. {
  474. // Data bind series
  475. if(dataSource != null && this.Common != null)
  476. {
  477. //************************************************************
  478. //** If list of series is not provided - bind all of them.
  479. //************************************************************
  480. if(seriesList == null)
  481. {
  482. seriesList = new ArrayList();
  483. foreach(Series series in this.Common.Chart.Series)
  484. {
  485. // note: added for design time data binding
  486. if (this.Common.Chart.IsDesignMode())
  487. {
  488. if (series.YValueMembers.Length > 0)
  489. {
  490. seriesList.Add(series);
  491. }
  492. }
  493. else
  494. {
  495. seriesList.Add(series);
  496. }
  497. }
  498. }
  499. //************************************************************
  500. //** Clear all data points in data bound series
  501. //************************************************************
  502. foreach(Series series in seriesList)
  503. {
  504. if(series.XValueMember.Length > 0 || series.YValueMembers.Length > 0)
  505. {
  506. series.Points.Clear();
  507. }
  508. }
  509. //************************************************************
  510. //** Get and reset data enumerator.
  511. //************************************************************
  512. IEnumerator enumerator = dataSource.GetEnumerator();
  513. if(enumerator.GetType() != typeof(System.Data.Common.DbEnumerator) )
  514. {
  515. try
  516. {
  517. enumerator.Reset();
  518. }
  519. // Some enumerators may not support Resetting
  520. catch (InvalidOperationException)
  521. {
  522. }
  523. catch (NotImplementedException)
  524. {
  525. }
  526. catch (NotSupportedException)
  527. {
  528. }
  529. }
  530. //************************************************************
  531. //** Loop through the enumerator.
  532. //************************************************************
  533. bool valueExsists = true;
  534. bool autoDetectType = true;
  535. do
  536. {
  537. // Move to the next item
  538. valueExsists = enumerator.MoveNext();
  539. // Loop through all series
  540. foreach(Series series in seriesList)
  541. {
  542. if(series.XValueMember.Length > 0 || series.YValueMembers.Length > 0)
  543. {
  544. //************************************************************
  545. //** Check and convert fields names.
  546. //************************************************************
  547. // Convert comma separated field names string to array of names
  548. string[] yFieldNames = null;
  549. if(series.YValueMembers.Length > 0)
  550. {
  551. yFieldNames = series.YValueMembers.Replace(",,", "\n").Split(',');
  552. for(int index = 0; index < yFieldNames.Length; index++)
  553. {
  554. yFieldNames[index] = yFieldNames[index].Replace("\n", ",").Trim();
  555. }
  556. }
  557. // Double check that a string object is not provided for data binding
  558. if(dataSource is string)
  559. {
  560. throw (new ArgumentException(SR.ExceptionDataBindYValuesToString, "dataSource"));
  561. }
  562. // Check number of fields
  563. if(yFieldNames == null || yFieldNames.GetLength(0) > series.YValuesPerPoint)
  564. {
  565. throw(new ArgumentOutOfRangeException("dataSource", SR.ExceptionDataPointYValuesCountMismatch(series.YValuesPerPoint.ToString(System.Globalization.CultureInfo.InvariantCulture) ) ) );
  566. }
  567. //************************************************************
  568. //** Create new data point.
  569. //************************************************************
  570. if(valueExsists)
  571. {
  572. // Auto detect values type
  573. if(autoDetectType)
  574. {
  575. autoDetectType = false;
  576. // Make sure Y field is not empty
  577. string yField = yFieldNames[0];
  578. int fieldIndex = 1;
  579. while(yField.Length == 0 && fieldIndex < yFieldNames.Length)
  580. {
  581. yField = yFieldNames[fieldIndex++];
  582. }
  583. DataPointCollection.AutoDetectValuesType(series, enumerator, series.XValueMember.Trim(), enumerator, yField);
  584. }
  585. // Create new point
  586. DataPoint newDataPoint = new DataPoint(series);
  587. bool emptyValues = false;
  588. bool xValueIsNull = false;
  589. //************************************************************
  590. //** Get new point X and Y values.
  591. //************************************************************
  592. object[] yValuesObj = new object[yFieldNames.Length];
  593. object xValueObj = null;
  594. // Set X to the value provided or use sequence numbers starting with 1
  595. if(series.XValueMember.Length > 0)
  596. {
  597. xValueObj = DataPointCollection.ConvertEnumerationItem(enumerator.Current, series.XValueMember.Trim());
  598. if(xValueObj is System.DBNull || xValueObj == null)
  599. {
  600. xValueIsNull = true;
  601. emptyValues = true;
  602. xValueObj = 0.0;
  603. }
  604. }
  605. if(yFieldNames.Length == 0)
  606. {
  607. yValuesObj[0] = DataPointCollection.ConvertEnumerationItem(enumerator.Current, null);
  608. if(yValuesObj[0] is System.DBNull || yValuesObj[0] == null)
  609. {
  610. emptyValues = true;
  611. yValuesObj[0] = 0.0;
  612. }
  613. }
  614. else
  615. {
  616. for(int i = 0; i < yFieldNames.Length; i++)
  617. {
  618. if(yFieldNames[i].Length > 0)
  619. {
  620. yValuesObj[i] = DataPointCollection.ConvertEnumerationItem(enumerator.Current, yFieldNames[i]);
  621. if(yValuesObj[i] is System.DBNull || yValuesObj[i] == null)
  622. {
  623. emptyValues = true;
  624. yValuesObj[i] = 0.0;
  625. }
  626. }
  627. else
  628. {
  629. yValuesObj[i] = (((Series)seriesList[0]).IsYValueDateTime()) ? DateTime.Now.Date.ToOADate() : 0.0;
  630. }
  631. }
  632. }
  633. // Add data point if X value is not Null
  634. if(!xValueIsNull)
  635. {
  636. if(emptyValues)
  637. {
  638. if(xValueObj != null)
  639. {
  640. newDataPoint.SetValueXY(xValueObj, yValuesObj);
  641. }
  642. else
  643. {
  644. newDataPoint.SetValueXY(0, yValuesObj);
  645. }
  646. series.Points.DataPointInit(ref newDataPoint);
  647. newDataPoint.IsEmpty = true;
  648. series.Points.Add(newDataPoint);
  649. }
  650. else
  651. {
  652. if(xValueObj != null)
  653. {
  654. newDataPoint.SetValueXY(xValueObj, yValuesObj);
  655. }
  656. else
  657. {
  658. newDataPoint.SetValueXY(0, yValuesObj);
  659. }
  660. series.Points.DataPointInit(ref newDataPoint);
  661. series.Points.Add(newDataPoint);
  662. }
  663. }
  664. if (this.Common.Chart.IsDesignMode())
  665. {
  666. series["TempDesignData"] = "true";
  667. }
  668. }
  669. }
  670. }
  671. } while(valueExsists);
  672. }
  673. }
  674. /// <summary>
  675. /// Aligns data points using their axis labels.
  676. /// </summary>
  677. /// <param name="sortAxisLabels">Indicates if points should be sorted by axis labels.</param>
  678. /// <param name="sortingOrder">Sorting pointSortOrder.</param>
  679. internal void AlignDataPointsByAxisLabel(bool sortAxisLabels, PointSortOrder sortingOrder)
  680. {
  681. // Find series which are attached to the same X axis in the same chart area
  682. foreach(ChartArea chartArea in this.ChartAreas)
  683. {
  684. // Check if chart area is visible
  685. if(chartArea.Visible)
  686. {
  687. // Create series list for primary and secondary X axis
  688. ArrayList chartAreaSeriesPrimary = new ArrayList();
  689. ArrayList chartAreaSeriesSecondary = new ArrayList();
  690. foreach(Series series in this.Common.Chart.Series)
  691. {
  692. // Check if series belongs to the chart area
  693. if (series.ChartArea == chartArea.Name)
  694. {
  695. if(series.XSubAxisName.Length == 0)
  696. {
  697. if(series.XAxisType == AxisType.Primary)
  698. {
  699. chartAreaSeriesPrimary.Add(series);
  700. }
  701. else
  702. {
  703. chartAreaSeriesSecondary.Add(series);
  704. }
  705. }
  706. }
  707. }
  708. // Align series
  709. AlignDataPointsByAxisLabel(chartAreaSeriesPrimary, sortAxisLabels, sortingOrder);
  710. AlignDataPointsByAxisLabel(chartAreaSeriesSecondary, sortAxisLabels, sortingOrder);
  711. }
  712. }
  713. }
  714. /// <summary>
  715. /// Aligns data points using their axis labels.
  716. /// </summary>
  717. /// <param name="seriesList">List of series to align.</param>
  718. /// <param name="sortAxisLabels">Indicates if points should be sorted by axis labels.</param>
  719. /// <param name="sortingOrder">Sorting order.</param>
  720. internal void AlignDataPointsByAxisLabel(
  721. ArrayList seriesList,
  722. bool sortAxisLabels,
  723. PointSortOrder sortingOrder)
  724. {
  725. // List is empty
  726. if(seriesList.Count == 0)
  727. {
  728. return;
  729. }
  730. // Collect information about all points in all series
  731. bool indexedX = true;
  732. bool uniqueAxisLabels = true;
  733. ArrayList axisLabels = new ArrayList();
  734. foreach(Series series in seriesList)
  735. {
  736. ArrayList seriesAxisLabels = new ArrayList();
  737. foreach(DataPoint point in series.Points)
  738. {
  739. // Check if series has indexed X values
  740. if(!series.IsXValueIndexed && point.XValue != 0.0)
  741. {
  742. indexedX = false;
  743. break;
  744. }
  745. // Add axis label to the list and make sure it's non-empty and unique
  746. if(point.AxisLabel.Length == 0)
  747. {
  748. uniqueAxisLabels = false;
  749. break;
  750. }
  751. else if(seriesAxisLabels.Contains(point.AxisLabel))
  752. {
  753. uniqueAxisLabels = false;
  754. break;
  755. }
  756. else if(!axisLabels.Contains(point.AxisLabel))
  757. {
  758. axisLabels.Add(point.AxisLabel);
  759. }
  760. seriesAxisLabels.Add(point.AxisLabel);
  761. }
  762. }
  763. // Sort axis labels
  764. if(sortAxisLabels)
  765. {
  766. axisLabels.Sort();
  767. if(sortingOrder == PointSortOrder.Descending)
  768. {
  769. axisLabels.Reverse();
  770. }
  771. }
  772. // All series must be indexed
  773. if(!indexedX)
  774. {
  775. throw (new InvalidOperationException(SR.ExceptionChartDataPointsAlignmentFaild));
  776. }
  777. // AxisLabel can't be empty or duplicated
  778. if(!uniqueAxisLabels)
  779. {
  780. throw (new InvalidOperationException(SR.ExceptionChartDataPointsAlignmentFaildAxisLabelsInvalid));
  781. }
  782. // Assign unique X values for data points in all series with same axis LabelStyle
  783. if(indexedX && uniqueAxisLabels)
  784. {
  785. foreach(Series series in seriesList)
  786. {
  787. foreach(DataPoint point in series.Points)
  788. {
  789. point.XValue = axisLabels.IndexOf(point.AxisLabel) + 1;
  790. }
  791. // Sort points by X value
  792. series.Sort(PointSortOrder.Ascending, "X");
  793. }
  794. // Make sure ther are no missing points
  795. foreach(Series series in seriesList)
  796. {
  797. series.IsXValueIndexed = true;
  798. for(int index = 0; index < axisLabels.Count; index++)
  799. {
  800. if(index >= series.Points.Count ||
  801. series.Points[index].XValue != index + 1)
  802. {
  803. DataPoint newPoint = new DataPoint(series);
  804. newPoint.AxisLabel = (string)axisLabels[index];
  805. newPoint.XValue = index + 1;
  806. newPoint.YValues[0] = 0.0;
  807. newPoint.IsEmpty = true;
  808. series.Points.Insert(index, newPoint);
  809. }
  810. }
  811. }
  812. }
  813. }
  814. /// <summary>
  815. /// Data bind chart to the table. Series will be automatically added to the chart depending on
  816. /// the number of unique values in the seriesGroupByField column of the data source.
  817. /// Data source can be the Ole(SQL)DataReader, DataView, DataSet, DataTable or DataRow.
  818. /// </summary>
  819. /// <param name="dataSource">Data source.</param>
  820. /// <param name="seriesGroupByField">Name of the field used to group data into series.</param>
  821. /// <param name="xField">Name of the field for X values.</param>
  822. /// <param name="yFields">Comma separated name(s) of the field(s) for Y value(s).</param>
  823. /// <param name="otherFields">Other point properties binding rule in format: PointProperty=Field[{Format}] [,PointProperty=Field[{Format}]]. For example: "Tooltip=Price{C1},Url=WebSiteName".</param>
  824. /// <param name="sort">Indicates that series should be sorted by group field.</param>
  825. /// <param name="sortingOrder">Series sorting order by group field.</param>
  826. internal void DataBindCrossTab(
  827. IEnumerable dataSource,
  828. string seriesGroupByField,
  829. string xField,
  830. string yFields,
  831. string otherFields,
  832. bool sort,
  833. PointSortOrder sortingOrder)
  834. {
  835. // Check arguments
  836. if (dataSource == null)
  837. throw (new ArgumentNullException("dataSource", SR.ExceptionDataPointInsertionNoDataSource));
  838. if (dataSource is string)
  839. throw (new ArgumentException(SR.ExceptionDataBindSeriesToString, "dataSource"));
  840. if (String.IsNullOrEmpty(yFields))
  841. throw (new ArgumentException(SR.ExceptionChartDataPointsInsertionFailedYValuesEmpty, "yFields"));
  842. if (String.IsNullOrEmpty(seriesGroupByField))
  843. throw (new ArgumentException(SR.ExceptionDataBindSeriesGroupByParameterIsEmpty, "seriesGroupByField"));
  844. // List of series and group by field values
  845. ArrayList seriesList = new ArrayList();
  846. ArrayList groupByValueList = new ArrayList();
  847. // Convert comma separated Y values field names string to array of names
  848. string[] yFieldNames = null;
  849. if(yFields != null)
  850. {
  851. yFieldNames = yFields.Replace(",,", "\n").Split(',');
  852. for(int index = 0; index < yFieldNames.Length; index++)
  853. {
  854. yFieldNames[index] = yFieldNames[index].Replace("\n", ",");
  855. }
  856. }
  857. // Convert other fields/properties names to two arrays of names
  858. string[] otherAttributeNames = null;
  859. string[] otherFieldNames = null;
  860. string[] otherValueFormat = null;
  861. DataPointCollection.ParsePointFieldsParameter(
  862. otherFields,
  863. ref otherAttributeNames,
  864. ref otherFieldNames,
  865. ref otherValueFormat);
  866. // Get and reset enumerator
  867. IEnumerator enumerator = DataPointCollection.GetDataSourceEnumerator(dataSource);
  868. if(enumerator.GetType() != typeof(System.Data.Common.DbEnumerator))
  869. {
  870. try
  871. {
  872. enumerator.Reset();
  873. }
  874. // Some enumerators may not support Resetting
  875. catch (NotSupportedException)
  876. {
  877. }
  878. catch (NotImplementedException)
  879. {
  880. }
  881. catch (InvalidOperationException)
  882. {
  883. }
  884. }
  885. // Add data points
  886. bool valueExsist = true;
  887. object[] yValuesObj = new object[yFieldNames.Length];
  888. object xValueObj = null;
  889. bool autoDetectType = true;
  890. do
  891. {
  892. // Move to the next objects in the enumerations
  893. if(valueExsist)
  894. {
  895. valueExsist = enumerator.MoveNext();
  896. }
  897. // Create and initialize data point
  898. if(valueExsist)
  899. {
  900. // Get value of the group by field
  901. object groupObj = DataPointCollection.ConvertEnumerationItem(
  902. enumerator.Current,
  903. seriesGroupByField);
  904. // Check series group by field and create new series if required
  905. Series series = null;
  906. int seriesIndex = groupByValueList.IndexOf(groupObj);
  907. if(seriesIndex >= 0)
  908. {
  909. // Select existing series from the list
  910. series = (Series)seriesList[seriesIndex];
  911. }
  912. else
  913. {
  914. // Create new series
  915. series = new Series();
  916. series.YValuesPerPoint = yFieldNames.GetLength(0);
  917. // If not the first series in the list copy some properties
  918. if(seriesList.Count > 0)
  919. {
  920. series.XValueType = ((Series)seriesList[0]).XValueType;
  921. series.autoXValueType = ((Series)seriesList[0]).autoXValueType;
  922. series.YValueType = ((Series)seriesList[0]).YValueType;
  923. series.autoYValueType = ((Series)seriesList[0]).autoYValueType;
  924. }
  925. // Try to set series name based on grouping vlaue
  926. string groupObjStr = groupObj as string;
  927. if(groupObjStr != null)
  928. {
  929. series.Name = groupObjStr;
  930. }
  931. else
  932. {
  933. series.Name = seriesGroupByField + " - " + groupObj.ToString();
  934. }
  935. // Add series and group value into the lists
  936. groupByValueList.Add(groupObj);
  937. seriesList.Add(series);
  938. }
  939. // Auto detect valu(s) type
  940. if(autoDetectType)
  941. {
  942. autoDetectType = false;
  943. DataPointCollection.AutoDetectValuesType(series, enumerator, xField, enumerator, yFieldNames[0]);
  944. }
  945. // Create new data point
  946. DataPoint newDataPoint = new DataPoint(series);
  947. bool emptyValues = false;
  948. // Set X to the value provided
  949. if(xField.Length > 0)
  950. {
  951. xValueObj = DataPointCollection.ConvertEnumerationItem(enumerator.Current, xField);
  952. if( DataPointCollection.IsEmptyValue(xValueObj) )
  953. {
  954. emptyValues = true;
  955. xValueObj = 0.0;
  956. }
  957. }
  958. // Set Y values
  959. if(yFieldNames.Length == 0)
  960. {
  961. yValuesObj[0] = DataPointCollection.ConvertEnumerationItem(enumerator.Current, null);
  962. if( DataPointCollection.IsEmptyValue(yValuesObj[0]) )
  963. {
  964. emptyValues = true;
  965. yValuesObj[0] = 0.0;
  966. }
  967. }
  968. else
  969. {
  970. for(int i = 0; i < yFieldNames.Length; i++)
  971. {
  972. yValuesObj[i] = DataPointCollection.ConvertEnumerationItem(enumerator.Current, yFieldNames[i]);
  973. if( DataPointCollection.IsEmptyValue(yValuesObj[i] ) )
  974. {
  975. emptyValues = true;
  976. yValuesObj[i] = 0.0;
  977. }
  978. }
  979. }
  980. // Set other values
  981. if(otherAttributeNames != null &&
  982. otherAttributeNames.Length > 0)
  983. {
  984. for(int i = 0; i < otherFieldNames.Length; i++)
  985. {
  986. // Get object by field name
  987. object obj = DataPointCollection.ConvertEnumerationItem(enumerator.Current, otherFieldNames[i]);
  988. if( !DataPointCollection.IsEmptyValue( obj ) )
  989. {
  990. newDataPoint.SetPointCustomProperty(
  991. obj,
  992. otherAttributeNames[i],
  993. otherValueFormat[i]);
  994. }
  995. }
  996. }
  997. // IsEmpty value was detected
  998. if(emptyValues)
  999. {
  1000. if(xValueObj != null)
  1001. {
  1002. newDataPoint.SetValueXY(xValueObj, yValuesObj);
  1003. }
  1004. else
  1005. {
  1006. newDataPoint.SetValueXY(0, yValuesObj);
  1007. }
  1008. DataPointCollection.DataPointInit(series, ref newDataPoint);
  1009. newDataPoint.IsEmpty = true;
  1010. series.Points.Add(newDataPoint);
  1011. }
  1012. else
  1013. {
  1014. if(xValueObj != null)
  1015. {
  1016. newDataPoint.SetValueXY(xValueObj, yValuesObj);
  1017. }
  1018. else
  1019. {
  1020. newDataPoint.SetValueXY(0, yValuesObj);
  1021. }
  1022. DataPointCollection.DataPointInit(series, ref newDataPoint);
  1023. series.Points.Add(newDataPoint);
  1024. }
  1025. }
  1026. } while(valueExsist);
  1027. // Sort series usig values of group by field
  1028. if(sort)
  1029. {
  1030. // Duplicate current list
  1031. ArrayList oldList = (ArrayList)groupByValueList.Clone();
  1032. // Sort list
  1033. groupByValueList.Sort();
  1034. if(sortingOrder == PointSortOrder.Descending)
  1035. {
  1036. groupByValueList.Reverse();
  1037. }
  1038. // Change order of series in collection
  1039. ArrayList sortedSeriesList = new ArrayList();
  1040. foreach(object obj in groupByValueList)
  1041. {
  1042. sortedSeriesList.Add(seriesList[oldList.IndexOf(obj)]);
  1043. }
  1044. seriesList = sortedSeriesList;
  1045. }
  1046. // Add all series from the list into the series collection
  1047. foreach(Series series in seriesList)
  1048. {
  1049. this.Common.Chart.Series.Add(series);
  1050. }
  1051. }
  1052. /// <summary>
  1053. /// Automatically creates and binds series to specified data table.
  1054. /// Each column of the table becomes a Y value in a separate series.
  1055. /// Series X value field may also be provided.
  1056. /// </summary>
  1057. /// <param name="dataSource">Data source.</param>
  1058. /// <param name="xField">Name of the field for series X values.</param>
  1059. internal void DataBindTable(
  1060. IEnumerable dataSource,
  1061. string xField)
  1062. {
  1063. // Check arguments
  1064. if (dataSource == null)
  1065. throw new ArgumentNullException("dataSource");
  1066. // Get list of member names from the data source
  1067. ArrayList dataSourceFields = GetDataSourceMemberNames(dataSource, true);
  1068. // Remove X value field if it's there
  1069. if (xField != null && xField.Length > 0)
  1070. {
  1071. int index = -1;
  1072. for (int i = 0; i < dataSourceFields.Count; i++)
  1073. {
  1074. if ( String.Equals((string)dataSourceFields[i], xField, StringComparison.OrdinalIgnoreCase ) )
  1075. {
  1076. index = i;
  1077. break;
  1078. }
  1079. }
  1080. if (index >= 0)
  1081. {
  1082. dataSourceFields.RemoveAt(index);
  1083. }
  1084. else
  1085. {
  1086. // Check if field name passed as index
  1087. bool parseSucceed = int.TryParse(xField, NumberStyles.Any, CultureInfo.InvariantCulture, out index);
  1088. if (parseSucceed && index >= 0 && index < dataSourceFields.Count)
  1089. {
  1090. dataSourceFields.RemoveAt(index);
  1091. }
  1092. }
  1093. }
  1094. // Get number of series
  1095. int seriesNumber = dataSourceFields.Count;
  1096. if (seriesNumber > 0)
  1097. {
  1098. // Create as many series as fields in the data source
  1099. ArrayList seriesList = new ArrayList();
  1100. int index = 0;
  1101. foreach (string fieldName in dataSourceFields)
  1102. {
  1103. Series series = new Series(fieldName);
  1104. // Set binding properties
  1105. series.YValueMembers = fieldName;
  1106. series.XValueMember = xField;
  1107. // Add to list
  1108. seriesList.Add(series);
  1109. ++index;
  1110. }
  1111. // Data bind series
  1112. this.DataBind(dataSource, seriesList);
  1113. // Add all series from the list into the series collection
  1114. foreach (Series series in seriesList)
  1115. {
  1116. // Clear binding properties
  1117. series.YValueMembers = String.Empty;
  1118. series.XValueMember = String.Empty;
  1119. // Add series into the list
  1120. this.Common.Chart.Series.Add(series);
  1121. }
  1122. }
  1123. }
  1124. #endregion // Data Binding
  1125. #endregion
  1126. }
  1127. /// <summary>
  1128. /// ChartPicture class represents chart content like legends, titles,
  1129. /// chart areas and series. It provides methods for positioning and
  1130. /// drawing all chart elements.
  1131. /// </summary>
  1132. internal class ChartPicture : ChartElement, IServiceProvider
  1133. {
  1134. #region Fields
  1135. /// <summary>
  1136. /// Indicates that chart exceptions should be suppressed.
  1137. /// </summary>
  1138. private bool _suppressExceptions = false;
  1139. // Chart Graphic object
  1140. internal ChartGraphics ChartGraph { get; set; }
  1141. // Private data members, which store properties values
  1142. private GradientStyle _backGradientStyle = GradientStyle.None;
  1143. private Color _backSecondaryColor = Color.Empty;
  1144. private Color _backColor = Color.White;
  1145. private string _backImage = "";
  1146. private ChartImageWrapMode _backImageWrapMode = ChartImageWrapMode.Tile;
  1147. private Color _backImageTransparentColor = Color.Empty;
  1148. private ChartImageAlignmentStyle _backImageAlign = ChartImageAlignmentStyle.TopLeft;
  1149. private Color _borderColor = Color.White;
  1150. private int _borderWidth = 1;
  1151. private ChartDashStyle _borderDashStyle = ChartDashStyle.NotSet;
  1152. private ChartHatchStyle _backHatchStyle = ChartHatchStyle.None;
  1153. private AntiAliasingStyles _antiAliasing = AntiAliasingStyles.All;
  1154. private TextAntiAliasingQuality _textAntiAliasingQuality = TextAntiAliasingQuality.High;
  1155. private bool _isSoftShadows = true;
  1156. private int _width = 300;
  1157. private int _height = 300;
  1158. private DataManipulator _dataManipulator = new DataManipulator();
  1159. internal HotRegionsList hotRegionsList = null;
  1160. private BorderSkin _borderSkin = null;
  1161. // Chart areas collection
  1162. private ChartAreaCollection _chartAreas = null;
  1163. // Chart legend collection
  1164. private LegendCollection _legends = null;
  1165. // Chart title collection
  1166. private TitleCollection _titles = null;
  1167. // Chart annotation collection
  1168. private AnnotationCollection _annotations = null;
  1169. // Annotation smart labels class
  1170. internal AnnotationSmartLabel annotationSmartLabel = new AnnotationSmartLabel();
  1171. // Chart picture events
  1172. internal event EventHandler<ChartPaintEventArgs> BeforePaint;
  1173. internal event EventHandler<ChartPaintEventArgs> AfterPaint;
  1174. // Chart title position rectangle
  1175. private RectangleF _titlePosition = RectangleF.Empty;
  1176. // Element spacing size
  1177. internal const float elementSpacing = 3F;
  1178. // Maximum size of the font in percentage
  1179. internal const float maxTitleSize = 15F;
  1180. // Printing indicator
  1181. internal bool isPrinting = false;
  1182. // Indicates chart selection mode
  1183. internal bool isSelectionMode = false;
  1184. private FontCache _fontCache = new FontCache();
  1185. // Position of the chart 3D border
  1186. private RectangleF _chartBorderPosition = RectangleF.Empty;
  1187. // Saving As Image indicator
  1188. internal bool isSavingAsImage = false;
  1189. // Indicates that chart background is restored from the double buffer
  1190. // prior to drawing top level objects like annotations, cursors and selection.
  1191. internal bool backgroundRestored = false;
  1192. // Buffered image of non-top level chart elements
  1193. internal Bitmap nonTopLevelChartBuffer = null;
  1194. #endregion
  1195. #region Constructors
  1196. /// <summary>
  1197. /// Constructor.
  1198. /// </summary>
  1199. /// <param name="container">Service container</param>
  1200. public ChartPicture(IServiceContainer container)
  1201. {
  1202. if(container == null)
  1203. {
  1204. throw(new ArgumentNullException(SR.ExceptionInvalidServiceContainer));
  1205. }
  1206. // Create and set Common Elements
  1207. Common = new CommonElements(container);
  1208. ChartGraph= new ChartGraphics(Common);
  1209. hotRegionsList = new HotRegionsList(Common);
  1210. // Create border properties class
  1211. _borderSkin = new BorderSkin(this);
  1212. // Create a collection of chart areas
  1213. _chartAreas = new ChartAreaCollection(this);
  1214. // Create a collection of legends
  1215. _legends = new LegendCollection(this);
  1216. // Create a collection of titles
  1217. _titles = new TitleCollection(this);
  1218. // Create a collection of annotations
  1219. _annotations = new AnnotationCollection(this);
  1220. // Set Common elements for data manipulator
  1221. _dataManipulator.Common = Common;
  1222. }
  1223. /// <summary>
  1224. /// Returns Chart service object
  1225. /// </summary>
  1226. /// <param name="serviceType">Service AxisName</param>
  1227. /// <returns>Chart picture</returns>
  1228. [EditorBrowsableAttribute(EditorBrowsableState.Never)]
  1229. object IServiceProvider.GetService(Type serviceType)
  1230. {
  1231. if(serviceType == typeof(ChartPicture))
  1232. {
  1233. return this;
  1234. }
  1235. throw (new ArgumentException( SR.ExceptionChartPictureUnsupportedType( serviceType.ToString() ) ) );
  1236. }
  1237. #endregion
  1238. #region Painting and selection methods
  1239. /// <summary>
  1240. /// Performs empty painting.
  1241. /// </summary>
  1242. internal void PaintOffScreen()
  1243. {
  1244. // Check chart size
  1245. // NOTE: Fixes issue #4733
  1246. if (this.Width <= 0 || this.Height <= 0)
  1247. {
  1248. return;
  1249. }
  1250. // Set process Mode to hot regions
  1251. this.Common.HotRegionsList.ProcessChartMode |= ProcessMode.HotRegions;
  1252. this.Common.HotRegionsList.hitTestCalled = true;
  1253. // Enable selection mode
  1254. this.isSelectionMode = true;
  1255. // Hot Region list does not exist. Create the list.
  1256. //this.common.HotRegionsList.List = new ArrayList();
  1257. this.Common.HotRegionsList.Clear();
  1258. // Create a new bitmap
  1259. Bitmap image = new Bitmap(Math.Max(1,Width), Math.Max(1,Height));
  1260. // Creates a new Graphics object from the
  1261. // specified Image object.
  1262. IGraphics offScreen = new FastReport.GdiGraphics(image);
  1263. // Connect Graphics object with Chart Graphics object
  1264. ChartGraph.Graphics = offScreen;
  1265. // Remember the previous dirty flag
  1266. bool oldDirtyFlag = this.Common.Chart.dirtyFlag;
  1267. Paint(ChartGraph.Graphics, false);
  1268. image.Dispose();
  1269. // Restore the previous dirty flag
  1270. this.Common.Chart.dirtyFlag = oldDirtyFlag;
  1271. // Disable selection mode
  1272. this.isSelectionMode = false;
  1273. // Set process Mode to hot regions
  1274. this.Common.HotRegionsList.ProcessChartMode |= ProcessMode.HotRegions;
  1275. }
  1276. /// <summary>
  1277. /// Gets text rendering quality.
  1278. /// </summary>
  1279. /// <returns>Text rendering quality.</returns>
  1280. internal TextRenderingHint GetTextRenderingHint()
  1281. {
  1282. TextRenderingHint result = TextRenderingHint.SingleBitPerPixelGridFit;
  1283. if( (this.AntiAliasing & AntiAliasingStyles.Text) == AntiAliasingStyles.Text )
  1284. {
  1285. result = TextRenderingHint.ClearTypeGridFit;
  1286. if(this.TextAntiAliasingQuality == TextAntiAliasingQuality.Normal)
  1287. {
  1288. result = TextRenderingHint.AntiAlias;
  1289. }
  1290. else if(this.TextAntiAliasingQuality == TextAntiAliasingQuality.SystemDefault)
  1291. {
  1292. result = TextRenderingHint.SystemDefault;
  1293. }
  1294. }
  1295. else
  1296. {
  1297. result = TextRenderingHint.SingleBitPerPixelGridFit;
  1298. }
  1299. return result;
  1300. }
  1301. internal bool GetBorderSkinVisibility()
  1302. {
  1303. return _borderSkin.SkinStyle != BorderSkinStyle.None && this.Width > 20 && this.Height > 20;
  1304. }
  1305. /// <summary>
  1306. /// This function paints a chart.
  1307. /// </summary>
  1308. /// <param name="graph">The graph provides drawing object to the display device. A Graphics object is associated with a specific device context.</param>
  1309. /// <param name="paintTopLevelElementOnly">Indicates that only chart top level elements like cursors, selection or annotation objects must be redrawn.</param>
  1310. [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "3#svg")]
  1311. internal void Paint(
  1312. IGraphics graph,
  1313. bool paintTopLevelElementOnly )
  1314. {
  1315. // Reset restored and saved backgound flags
  1316. this.backgroundRestored = false;
  1317. // Reset Annotation Smart Labels
  1318. this.annotationSmartLabel.Reset();
  1319. // Do not draw the control if size is less than 5 pixel
  1320. if (this.Width < 5 || this.Height < 5)
  1321. {
  1322. return;
  1323. }
  1324. bool resetHotRegionList = false;
  1325. if(
  1326. this.Common.HotRegionsList.hitTestCalled
  1327. || IsToolTipsEnabled()
  1328. )
  1329. {
  1330. Common.HotRegionsList.ProcessChartMode = ProcessMode.HotRegions | ProcessMode.Paint;
  1331. this.Common.HotRegionsList.hitTestCalled = false;
  1332. // Clear list of hot regions
  1333. if(paintTopLevelElementOnly)
  1334. {
  1335. // If repainting only top level elements (annotations) -
  1336. // clear top level objects hot regions only
  1337. for(int index = 0; index < this.Common.HotRegionsList.List.Count; index++)
  1338. {
  1339. HotRegion region = (HotRegion)this.Common.HotRegionsList.List[index];
  1340. if(region.Type == ChartElementType.Annotation)
  1341. {
  1342. this.Common.HotRegionsList.List.RemoveAt(index);
  1343. --index;
  1344. }
  1345. }
  1346. }
  1347. else
  1348. {
  1349. // If repainting whole chart - clear all hot regions
  1350. resetHotRegionList = true;
  1351. }
  1352. }
  1353. else
  1354. {
  1355. Common.HotRegionsList.ProcessChartMode = ProcessMode.Paint;
  1356. // If repainting whole chart - clear all hot regions
  1357. resetHotRegionList = true;
  1358. }
  1359. // Reset hot region list
  1360. if(resetHotRegionList)
  1361. {
  1362. this.Common.HotRegionsList.Clear();
  1363. }
  1364. // Check if control was data bound
  1365. ChartImage chartImage = this as ChartImage;
  1366. if(chartImage != null && !chartImage.boundToDataSource)
  1367. {
  1368. if(this.Common != null && this.Common.Chart != null && !this.Common.Chart.IsDesignMode())
  1369. {
  1370. this.Common.Chart.DataBind();
  1371. }
  1372. }
  1373. // Connect Graphics object with Chart Graphics object
  1374. ChartGraph.Graphics = graph;
  1375. Common.graph = ChartGraph;
  1376. // Set anti alias mode
  1377. ChartGraph.AntiAliasing = _antiAliasing;
  1378. ChartGraph.softShadows = _isSoftShadows;
  1379. ChartGraph.TextRenderingHint = GetTextRenderingHint();
  1380. try
  1381. {
  1382. // Check if only chart area cursors and annotations must be redrawn
  1383. if(!paintTopLevelElementOnly)
  1384. {
  1385. // Fire Before Paint event
  1386. OnBeforePaint(new ChartPaintEventArgs(this.Chart, this.ChartGraph, this.Common, new ElementPosition(0, 0, 100, 100)));
  1387. // Flag indicates that resize method should be called
  1388. // after adjusting the intervals in 3D charts
  1389. bool resizeAfterIntervalAdjusting = false;
  1390. // RecalculateAxesScale paint chart areas
  1391. foreach (ChartArea area in _chartAreas )
  1392. {
  1393. // Check if area is visible
  1394. if(area.Visible)
  1395. {
  1396. area.Set3DAnglesAndReverseMode();
  1397. area.SetTempValues();
  1398. area.ReCalcInternal();
  1399. // Resize should be called the second time
  1400. if( area.Area3DStyle.Enable3D && !area.chartAreaIsCurcular)
  1401. {
  1402. resizeAfterIntervalAdjusting = true;
  1403. }
  1404. }
  1405. }
  1406. // Call Customize event
  1407. this.Common.Chart.CallOnCustomize();
  1408. // Resize picture
  1409. Resize(ChartGraph, resizeAfterIntervalAdjusting);
  1410. // This code is introduce because labels has to
  1411. // be changed when scene is rotated.
  1412. bool intervalReCalculated = false;
  1413. foreach (ChartArea area in _chartAreas )
  1414. {
  1415. if( area.Area3DStyle.Enable3D &&
  1416. !area.chartAreaIsCurcular
  1417. && area.Visible
  1418. )
  1419. {
  1420. // Make correction for interval in 3D space
  1421. intervalReCalculated = true;
  1422. area.Estimate3DInterval( ChartGraph );
  1423. area.ReCalcInternal();
  1424. }
  1425. }
  1426. // Resize chart areas after updating 3D interval
  1427. if(resizeAfterIntervalAdjusting)
  1428. {
  1429. // NOTE: Fixes issue #6808.
  1430. // In 3D chart area interval will be changed to compenstae for the axis rotation angle.
  1431. // This will cause all standard labels to be changed. We need to call the customize event
  1432. // the second time to give user a chance to modify those labels.
  1433. if (intervalReCalculated)
  1434. {
  1435. // Call Customize event
  1436. this.Common.Chart.CallOnCustomize();
  1437. }
  1438. // Resize chart elements
  1439. Resize(ChartGraph);
  1440. }
  1441. //***********************************************************************
  1442. //** Draw chart 3D border
  1443. //***********************************************************************
  1444. if (GetBorderSkinVisibility())
  1445. {
  1446. // Fill rectangle with page color
  1447. ChartGraph.FillRectangleAbs( new RectangleF( 0, 0, Width-1 , Height-1 ),
  1448. _borderSkin.PageColor,
  1449. ChartHatchStyle.None,
  1450. "",
  1451. ChartImageWrapMode.Tile,
  1452. Color.Empty,
  1453. ChartImageAlignmentStyle.Center,
  1454. GradientStyle.None,
  1455. Color.Empty,
  1456. _borderSkin.PageColor,
  1457. 1,
  1458. ChartDashStyle.Solid,
  1459. PenAlignment.Inset );
  1460. // Draw 3D border
  1461. ChartGraph.Draw3DBorderAbs(
  1462. _borderSkin,
  1463. this._chartBorderPosition,
  1464. BackColor,
  1465. BackHatchStyle,
  1466. BackImage,
  1467. BackImageWrapMode,
  1468. BackImageTransparentColor,
  1469. BackImageAlignment,
  1470. BackGradientStyle,
  1471. BackSecondaryColor,
  1472. BorderColor,
  1473. BorderWidth,
  1474. BorderDashStyle);
  1475. }
  1476. // Paint Background
  1477. else
  1478. {
  1479. ChartGraph.FillRectangleAbs( new RectangleF( 0, 0, Width-1 , Height-1 ),
  1480. BackColor,
  1481. BackHatchStyle,
  1482. BackImage,
  1483. BackImageWrapMode,
  1484. BackImageTransparentColor,
  1485. BackImageAlignment,
  1486. BackGradientStyle,
  1487. BackSecondaryColor,
  1488. BorderColor,
  1489. BorderWidth,
  1490. BorderDashStyle,
  1491. PenAlignment.Inset );
  1492. }
  1493. // Call BackPaint event
  1494. this.Chart.CallOnPrePaint(new ChartPaintEventArgs(this.Chart, this.ChartGraph, this.Common, new ElementPosition(0, 0, 100, 100)));
  1495. // Call paint function for each chart area.
  1496. foreach (ChartArea area in _chartAreas )
  1497. {
  1498. // Check if area is visible
  1499. if(area.Visible)
  1500. {
  1501. area.Paint(ChartGraph);
  1502. }
  1503. }
  1504. // This code is introduced because of GetPointsInterval method,
  1505. // which is very time consuming. There is no reason to calculate
  1506. // interval after painting.
  1507. foreach (ChartArea area in _chartAreas )
  1508. {
  1509. // Reset interval data
  1510. area.intervalData = double.NaN;
  1511. }
  1512. // Draw Legends
  1513. foreach(Legend legendCurrent in this.Legends)
  1514. {
  1515. legendCurrent.Paint(ChartGraph);
  1516. }
  1517. // Draw chart titles from the collection
  1518. foreach(Title titleCurrent in this.Titles)
  1519. {
  1520. titleCurrent.Paint(ChartGraph);
  1521. }
  1522. // Call Paint event
  1523. this.Chart.CallOnPostPaint(new ChartPaintEventArgs(this.Chart, this.ChartGraph, this.Common, new ElementPosition(0, 0, 100, 100)));
  1524. }
  1525. // Draw annotation objects
  1526. this.Annotations.Paint(ChartGraph, paintTopLevelElementOnly);
  1527. // Draw chart areas cursors in all areas.
  1528. // Only if not in selection
  1529. if(!this.isSelectionMode)
  1530. {
  1531. foreach (ChartArea area in _chartAreas )
  1532. {
  1533. // Check if area is visible
  1534. if(area.Visible)
  1535. {
  1536. area.PaintCursors(ChartGraph, paintTopLevelElementOnly);
  1537. }
  1538. }
  1539. }
  1540. // Return default values
  1541. foreach (ChartArea area in _chartAreas )
  1542. {
  1543. // Check if area is visible
  1544. if(area.Visible)
  1545. {
  1546. area.Restore3DAnglesAndReverseMode();
  1547. area.GetTempValues();
  1548. }
  1549. }
  1550. }
  1551. catch(System.Exception)
  1552. {
  1553. throw;
  1554. }
  1555. finally
  1556. {
  1557. // Fire After Paint event
  1558. OnAfterPaint(new ChartPaintEventArgs(this.Chart, this.ChartGraph, this.Common, new ElementPosition(0, 0, 100, 100)));
  1559. // Restore temp values for each chart area
  1560. foreach (ChartArea area in _chartAreas )
  1561. {
  1562. // Check if area is visible
  1563. if(area.Visible)
  1564. {
  1565. area.Restore3DAnglesAndReverseMode();
  1566. area.GetTempValues();
  1567. }
  1568. }
  1569. }
  1570. }
  1571. /// <summary>
  1572. /// Invoke before paint delegates.
  1573. /// </summary>
  1574. /// <param name="e">Event arguments.</param>
  1575. protected virtual void OnBeforePaint(ChartPaintEventArgs e)
  1576. {
  1577. if (BeforePaint != null)
  1578. {
  1579. //Invokes the delegates.
  1580. BeforePaint(this, e);
  1581. }
  1582. }
  1583. /// <summary>
  1584. /// Invoke after paint delegates.
  1585. /// </summary>
  1586. /// <param name="e">Event arguments.</param>
  1587. protected virtual void OnAfterPaint(ChartPaintEventArgs e)
  1588. {
  1589. if (AfterPaint != null)
  1590. {
  1591. //Invokes the delegates.
  1592. AfterPaint(this, e);
  1593. }
  1594. }
  1595. internal override void Invalidate()
  1596. {
  1597. base.Invalidate();
  1598. if (Chart!=null)
  1599. Chart.Invalidate();
  1600. }
  1601. #endregion
  1602. #region Resizing methods
  1603. /// <summary>
  1604. /// Resize the chart picture.
  1605. /// </summary>
  1606. /// <param name="chartGraph">Chart graphics.</param>
  1607. public void Resize(ChartGraphics chartGraph)
  1608. {
  1609. Resize(chartGraph, false);
  1610. }
  1611. /// <summary>
  1612. /// Resize the chart picture.
  1613. /// </summary>
  1614. /// <param name="chartGraph">Chart graphics.</param>
  1615. /// <param name="calcAreaPositionOnly">Indicates that only chart area position is calculated.</param>
  1616. public void Resize(ChartGraphics chartGraph, bool calcAreaPositionOnly)
  1617. {
  1618. // Set the chart size for Common elements
  1619. Common.Width = _width;
  1620. Common.Height = _height;
  1621. // Set the chart size for Chart graphics
  1622. chartGraph.SetPictureSize( _width, _height );
  1623. // Initialize chart area(s) rectangle
  1624. RectangleF chartAreasRectangle = new RectangleF(0, 0, _width - 1, _height - 1);
  1625. chartAreasRectangle = chartGraph.GetRelativeRectangle(chartAreasRectangle);
  1626. //******************************************************
  1627. //** Get the 3D border interface
  1628. //******************************************************
  1629. _titlePosition = RectangleF.Empty;
  1630. IBorderType border3D = null;
  1631. bool titleInBorder = false;
  1632. if(_borderSkin.SkinStyle != BorderSkinStyle.None)
  1633. {
  1634. // Set border size
  1635. this._chartBorderPosition = chartGraph.GetAbsoluteRectangle(chartAreasRectangle);
  1636. // Get border interface
  1637. border3D = Common.BorderTypeRegistry.GetBorderType(_borderSkin.SkinStyle.ToString());
  1638. if(border3D != null)
  1639. {
  1640. border3D.Resolution = 96f;// chartGraph.Graphics.DpiX;
  1641. // Check if title should be displayed in the border
  1642. titleInBorder = border3D.GetTitlePositionInBorder() != RectangleF.Empty;
  1643. _titlePosition = chartGraph.GetRelativeRectangle(border3D.GetTitlePositionInBorder());
  1644. _titlePosition.Width = chartAreasRectangle.Width - _titlePosition.Width;
  1645. // Adjust are position to the border size
  1646. border3D.AdjustAreasPosition(chartGraph, ref chartAreasRectangle);
  1647. }
  1648. }
  1649. //******************************************************
  1650. //** Calculate position of all titles in the collection
  1651. //******************************************************
  1652. RectangleF frameTitlePosition = RectangleF.Empty;
  1653. if(titleInBorder)
  1654. {
  1655. frameTitlePosition = new RectangleF(_titlePosition.Location, _titlePosition.Size);
  1656. }
  1657. foreach(Title title in this.Titles)
  1658. {
  1659. if (title.DockedToChartArea == Constants.NotSetValue &&
  1660. title.Position.Auto &&
  1661. title.Visible)
  1662. {
  1663. title.CalcTitlePosition(chartGraph, ref chartAreasRectangle, ref frameTitlePosition, elementSpacing);
  1664. }
  1665. }
  1666. //******************************************************
  1667. //** Calculate position of all legends in the collection
  1668. //******************************************************
  1669. this.Legends.CalcLegendPosition(chartGraph, ref chartAreasRectangle, elementSpacing);
  1670. //******************************************************
  1671. //** Calculate position of the chart area(s)
  1672. //******************************************************
  1673. chartAreasRectangle.Width -= elementSpacing;
  1674. chartAreasRectangle.Height -= elementSpacing;
  1675. RectangleF areaPosition = new RectangleF();
  1676. // Get number of chart areas that requeres automatic positioning
  1677. int areaNumber = 0;
  1678. foreach (ChartArea area in _chartAreas )
  1679. {
  1680. // Check if area is visible
  1681. if(area.Visible)
  1682. {
  1683. if(area.Position.Auto)
  1684. {
  1685. ++areaNumber;
  1686. }
  1687. }
  1688. }
  1689. // Calculate how many columns & rows of areas we going to have
  1690. int areaColumns = (int)Math.Floor(Math.Sqrt(areaNumber));
  1691. if(areaColumns < 1)
  1692. {
  1693. areaColumns = 1;
  1694. }
  1695. int areaRows = (int)Math.Ceiling(((float)areaNumber) / ((float)areaColumns));
  1696. // Set position for all areas
  1697. int column = 0;
  1698. int row = 0;
  1699. foreach (ChartArea area in _chartAreas )
  1700. {
  1701. // Check if area is visible
  1702. if(area.Visible)
  1703. {
  1704. if(area.Position.Auto)
  1705. {
  1706. // Calculate area position
  1707. areaPosition.Width = chartAreasRectangle.Width / areaColumns - elementSpacing;
  1708. areaPosition.Height = chartAreasRectangle.Height / areaRows - elementSpacing;
  1709. areaPosition.X = chartAreasRectangle.X + column * (chartAreasRectangle.Width / areaColumns) + elementSpacing;
  1710. areaPosition.Y = chartAreasRectangle.Y + row * (chartAreasRectangle.Height / areaRows) + elementSpacing;
  1711. // Calculate position of all titles in the collection docked outside of the chart area
  1712. TitleCollection.CalcOutsideTitlePosition(this, chartGraph, area, ref areaPosition, elementSpacing);
  1713. // Calculate position of the legend if it's docked outside of the chart area
  1714. this.Legends.CalcOutsideLegendPosition(chartGraph, area, ref areaPosition, elementSpacing);
  1715. // Set area position without changing the Auto flag
  1716. area.Position.SetPositionNoAuto(areaPosition.X, areaPosition.Y, areaPosition.Width, areaPosition.Height);
  1717. // Go to next area
  1718. ++row;
  1719. if(row >= areaRows)
  1720. {
  1721. row = 0;
  1722. ++column;
  1723. }
  1724. }
  1725. else
  1726. {
  1727. RectangleF rect = area.Position.ToRectangleF();
  1728. // Calculate position of all titles in the collection docked outside of the chart area
  1729. TitleCollection.CalcOutsideTitlePosition(this, chartGraph, area, ref rect, elementSpacing);
  1730. // Calculate position of the legend if it's docked outside of the chart area
  1731. this.Legends.CalcOutsideLegendPosition(chartGraph, area, ref rect, elementSpacing);
  1732. }
  1733. }
  1734. }
  1735. //******************************************************
  1736. //** Align chart areas Position if required
  1737. //******************************************************
  1738. AlignChartAreasPosition();
  1739. //********************************************************
  1740. //** Check if only chart area position must be calculated.
  1741. //********************************************************
  1742. if(!calcAreaPositionOnly)
  1743. {
  1744. //******************************************************
  1745. //** Call Resize function for each chart area.
  1746. //******************************************************
  1747. foreach (ChartArea area in _chartAreas )
  1748. {
  1749. // Check if area is visible
  1750. if(area.Visible)
  1751. {
  1752. area.Resize(chartGraph);
  1753. }
  1754. }
  1755. //******************************************************
  1756. //** Align chart areas InnerPlotPosition if required
  1757. //******************************************************
  1758. AlignChartAreas(AreaAlignmentStyles.PlotPosition);
  1759. //******************************************************
  1760. //** Calculate position of the legend if it's inside
  1761. //** chart plotting area
  1762. //******************************************************
  1763. // Calculate position of all titles in the collection docked outside of the chart area
  1764. TitleCollection.CalcInsideTitlePosition(this, chartGraph, elementSpacing);
  1765. this.Legends.CalcInsideLegendPosition(chartGraph, elementSpacing);
  1766. }
  1767. }
  1768. /// <summary>
  1769. /// Minimum and maximum do not have to be calculated
  1770. /// from data series every time. It is very time
  1771. /// consuming. Minimum and maximum are buffered
  1772. /// and only when this flags are set Minimum and
  1773. /// Maximum are refreshed from data.
  1774. /// </summary>
  1775. internal void ResetMinMaxFromData()
  1776. {
  1777. if (_chartAreas != null)
  1778. {
  1779. // Call ResetMinMaxFromData function for each chart area.
  1780. foreach (ChartArea area in _chartAreas)
  1781. {
  1782. // Check if area is visible
  1783. if (area.Visible)
  1784. {
  1785. area.ResetMinMaxFromData();
  1786. }
  1787. }
  1788. }
  1789. }
  1790. /// <summary>
  1791. /// RecalculateAxesScale the chart picture.
  1792. /// </summary>
  1793. public void Recalculate()
  1794. {
  1795. // Call ReCalc function for each chart area.
  1796. foreach (ChartArea area in _chartAreas )
  1797. {
  1798. // Check if area is visible
  1799. if(area.Visible)
  1800. {
  1801. area.ReCalcInternal();
  1802. }
  1803. }
  1804. }
  1805. #endregion
  1806. #region Chart picture properties
  1807. // VSTS 96787-Text Direction (RTL/LTR)
  1808. /// <summary>
  1809. /// Gets or sets the RightToLeft type.
  1810. /// </summary>
  1811. [
  1812. DefaultValue(RightToLeft.No)
  1813. ]
  1814. public RightToLeft RightToLeft
  1815. {
  1816. get
  1817. {
  1818. return this.Common.Chart.RightToLeft;
  1819. }
  1820. set
  1821. {
  1822. this.Common.Chart.RightToLeft = value;
  1823. }
  1824. }
  1825. /// <summary>
  1826. /// Indicates that non-critical chart exceptions will be suppressed.
  1827. /// </summary>
  1828. [
  1829. SRCategory("CategoryAttributeMisc"),
  1830. DefaultValue(false),
  1831. SRDescription("DescriptionAttributeSuppressExceptions"),
  1832. ]
  1833. internal bool SuppressExceptions
  1834. {
  1835. set
  1836. {
  1837. _suppressExceptions = value;
  1838. }
  1839. get
  1840. {
  1841. return _suppressExceptions;
  1842. }
  1843. }
  1844. /// <summary>
  1845. /// Chart border skin style.
  1846. /// </summary>
  1847. [
  1848. SRCategory("CategoryAttributeAppearance"),
  1849. Bindable(true),
  1850. DefaultValue(BorderSkinStyle.None),
  1851. SRDescription("DescriptionAttributeBorderSkin"),
  1852. ]
  1853. public BorderSkin BorderSkin
  1854. {
  1855. get
  1856. {
  1857. return _borderSkin;
  1858. }
  1859. set
  1860. {
  1861. _borderSkin = value;
  1862. }
  1863. }
  1864. /// <summary>
  1865. /// Reference to chart area collection
  1866. /// </summary>
  1867. [
  1868. SRCategory("CategoryAttributeAppearance"),
  1869. Bindable(true),
  1870. SRDescription("DescriptionAttributeChartAreas"),
  1871. #if DESIGNER
  1872. Editor(typeof(ChartCollectionEditor), typeof(UITypeEditor))
  1873. #endif
  1874. ]
  1875. public ChartAreaCollection ChartAreas
  1876. {
  1877. get
  1878. {
  1879. return _chartAreas;
  1880. }
  1881. }
  1882. /// <summary>
  1883. /// Chart legend collection.
  1884. /// </summary>
  1885. [
  1886. SRCategory("CategoryAttributeChart"),
  1887. SRDescription("DescriptionAttributeLegends"),
  1888. #if DESIGNER
  1889. Editor(typeof(LegendCellCollectionEditor), typeof(UITypeEditor))
  1890. #endif
  1891. ]
  1892. public LegendCollection Legends
  1893. {
  1894. get
  1895. {
  1896. return _legends;
  1897. }
  1898. }
  1899. /// <summary>
  1900. /// Chart title collection.
  1901. /// </summary>
  1902. [
  1903. SRCategory("CategoryAttributeCharttitle"),
  1904. SRDescription("DescriptionAttributeTitles"),
  1905. #if DESIGNER
  1906. Editor(typeof(ChartCollectionEditor), typeof(UITypeEditor))
  1907. #endif
  1908. ]
  1909. public TitleCollection Titles
  1910. {
  1911. get
  1912. {
  1913. return _titles;
  1914. }
  1915. }
  1916. /// <summary>
  1917. /// Chart annotation collection.
  1918. /// </summary>
  1919. [
  1920. SRCategory("CategoryAttributeChart"),
  1921. SRDescription("DescriptionAttributeAnnotations3"),
  1922. #if DESIGNER
  1923. Editor(typeof(AnnotationCollectionEditor), (typeof(UITypeEditor)))
  1924. #endif
  1925. ]
  1926. public AnnotationCollection Annotations
  1927. {
  1928. get
  1929. {
  1930. return _annotations;
  1931. }
  1932. }
  1933. /// <summary>
  1934. /// Background color for the Chart
  1935. /// </summary>
  1936. [
  1937. SRCategory("CategoryAttributeAppearance"),
  1938. Bindable(true),
  1939. DefaultValue(typeof(Color), "White"),
  1940. SRDescription("DescriptionAttributeBackColor"),
  1941. TypeConverter(typeof(ColorConverter)),
  1942. #if DESIGNER
  1943. Editor(typeof(ChartColorEditor), typeof(UITypeEditor))
  1944. #endif
  1945. ]
  1946. public Color BackColor
  1947. {
  1948. get
  1949. {
  1950. return _backColor;
  1951. }
  1952. set
  1953. {
  1954. _backColor = value;
  1955. }
  1956. }
  1957. /// <summary>
  1958. /// Border color for the Chart
  1959. /// </summary>
  1960. [
  1961. SRCategory("CategoryAttributeAppearance"),
  1962. Bindable(true),
  1963. DefaultValue(typeof(Color), "White"),
  1964. SRDescription("DescriptionAttributeBorderColor"),
  1965. TypeConverter(typeof(ColorConverter)),
  1966. #if DESIGNER
  1967. Editor(typeof(ChartColorEditor), typeof(UITypeEditor))
  1968. #endif
  1969. ]
  1970. public Color BorderColor
  1971. {
  1972. get
  1973. {
  1974. return _borderColor;
  1975. }
  1976. set
  1977. {
  1978. _borderColor = value;
  1979. }
  1980. }
  1981. /// <summary>
  1982. /// Chart width
  1983. /// </summary>
  1984. [
  1985. SRCategory("CategoryAttributeAppearance"),
  1986. Bindable(true),
  1987. DefaultValue(300),
  1988. SRDescription("DescriptionAttributeWidth"),
  1989. ]
  1990. public int Width
  1991. {
  1992. get
  1993. {
  1994. return _width;
  1995. }
  1996. set
  1997. {
  1998. this.InspectChartDimensions(value, this.Height);
  1999. _width = value;
  2000. Common.Width = _width;
  2001. }
  2002. }
  2003. /// <summary>
  2004. /// Series Data Manipulator
  2005. /// </summary>
  2006. [
  2007. SRCategory("CategoryAttributeData"),
  2008. SRDescription("DescriptionAttributeDataManipulator"),
  2009. Browsable(false),
  2010. DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden),
  2011. SerializationVisibilityAttribute(SerializationVisibility.Hidden)
  2012. ]
  2013. public DataManipulator DataManipulator
  2014. {
  2015. get
  2016. {
  2017. return _dataManipulator;
  2018. }
  2019. }
  2020. /// <summary>
  2021. /// Chart height
  2022. /// </summary>
  2023. [
  2024. SRCategory("CategoryAttributeAppearance"),
  2025. Bindable(true),
  2026. DefaultValue(300),
  2027. SRDescription("DescriptionAttributeHeight3"),
  2028. ]
  2029. public int Height
  2030. {
  2031. get
  2032. {
  2033. return _height;
  2034. }
  2035. set
  2036. {
  2037. this.InspectChartDimensions(this.Width, value);
  2038. _height = value;
  2039. Common.Height = value;
  2040. }
  2041. }
  2042. /// <summary>
  2043. /// Back Hatch style
  2044. /// </summary>
  2045. [
  2046. SRCategory("CategoryAttributeAppearance"),
  2047. Bindable(true),
  2048. DefaultValue(ChartHatchStyle.None),
  2049. SRDescription("DescriptionAttributeBackHatchStyle"),
  2050. #if DESIGNER
  2051. Editor(typeof(HatchStyleEditor), typeof(UITypeEditor))
  2052. #endif
  2053. ]
  2054. public ChartHatchStyle BackHatchStyle
  2055. {
  2056. get
  2057. {
  2058. return _backHatchStyle;
  2059. }
  2060. set
  2061. {
  2062. _backHatchStyle = value;
  2063. }
  2064. }
  2065. /// <summary>
  2066. /// Chart area background image
  2067. /// </summary>
  2068. [
  2069. SRCategory("CategoryAttributeAppearance"),
  2070. Bindable(true),
  2071. DefaultValue(""),
  2072. SRDescription("DescriptionAttributeBackImage"),
  2073. #if DESIGNER
  2074. Editor(typeof(ImageValueEditor), (typeof(UITypeEditor))),
  2075. #endif
  2076. NotifyParentPropertyAttribute(true)
  2077. ]
  2078. public string BackImage
  2079. {
  2080. get
  2081. {
  2082. return _backImage;
  2083. }
  2084. set
  2085. {
  2086. _backImage = value;
  2087. }
  2088. }
  2089. /// <summary>
  2090. /// Chart area background image drawing mode.
  2091. /// </summary>
  2092. [
  2093. SRCategory("CategoryAttributeAppearance"),
  2094. Bindable(true),
  2095. DefaultValue(ChartImageWrapMode.Tile),
  2096. NotifyParentPropertyAttribute(true),
  2097. SRDescription("DescriptionAttributeImageWrapMode"),
  2098. ]
  2099. public ChartImageWrapMode BackImageWrapMode
  2100. {
  2101. get
  2102. {
  2103. return _backImageWrapMode;
  2104. }
  2105. set
  2106. {
  2107. _backImageWrapMode = value;
  2108. }
  2109. }
  2110. /// <summary>
  2111. /// Background image transparent color.
  2112. /// </summary>
  2113. [
  2114. SRCategory("CategoryAttributeAppearance"),
  2115. Bindable(true),
  2116. DefaultValue(typeof(Color), ""),
  2117. NotifyParentPropertyAttribute(true),
  2118. SRDescription("DescriptionAttributeImageTransparentColor"),
  2119. TypeConverter(typeof(ColorConverter)),
  2120. #if DESIGNER
  2121. Editor(typeof(ChartColorEditor), typeof(UITypeEditor))
  2122. #endif
  2123. ]
  2124. public Color BackImageTransparentColor
  2125. {
  2126. get
  2127. {
  2128. return _backImageTransparentColor;
  2129. }
  2130. set
  2131. {
  2132. _backImageTransparentColor = value;
  2133. }
  2134. }
  2135. /// <summary>
  2136. /// Background image alignment used by ClampUnscale drawing mode.
  2137. /// </summary>
  2138. [
  2139. SRCategory("CategoryAttributeAppearance"),
  2140. Bindable(true),
  2141. DefaultValue(ChartImageAlignmentStyle.TopLeft),
  2142. NotifyParentPropertyAttribute(true),
  2143. SRDescription("DescriptionAttributeBackImageAlign"),
  2144. ]
  2145. public ChartImageAlignmentStyle BackImageAlignment
  2146. {
  2147. get
  2148. {
  2149. return _backImageAlign;
  2150. }
  2151. set
  2152. {
  2153. _backImageAlign = value;
  2154. }
  2155. }
  2156. /// <summary>
  2157. /// Indicates that smoothing is applied while drawing shadows.
  2158. /// </summary>
  2159. [
  2160. SRCategory("CategoryAttributeImage"),
  2161. Bindable(true),
  2162. DefaultValue(true),
  2163. SRDescription("DescriptionAttributeSoftShadows3"),
  2164. ]
  2165. public bool IsSoftShadows
  2166. {
  2167. get
  2168. {
  2169. return _isSoftShadows;
  2170. }
  2171. set
  2172. {
  2173. _isSoftShadows = value;
  2174. }
  2175. }
  2176. /// <summary>
  2177. /// Specifies whether smoothing (antialiasing) is applied while drawing chart.
  2178. /// </summary>
  2179. [
  2180. SRCategory("CategoryAttributeImage"),
  2181. Bindable(true),
  2182. DefaultValue(typeof(AntiAliasingStyles), "All"),
  2183. SRDescription("DescriptionAttributeAntiAlias"),
  2184. ]
  2185. public AntiAliasingStyles AntiAliasing
  2186. {
  2187. get
  2188. {
  2189. return _antiAliasing;
  2190. }
  2191. set
  2192. {
  2193. _antiAliasing = value;
  2194. }
  2195. }
  2196. /// <summary>
  2197. /// Specifies the quality of text antialiasing.
  2198. /// </summary>
  2199. [
  2200. SRCategory("CategoryAttributeImage"),
  2201. Bindable(true),
  2202. DefaultValue(typeof(TextAntiAliasingQuality), "High"),
  2203. SRDescription("DescriptionAttributeTextAntiAliasingQuality"),
  2204. ]
  2205. public TextAntiAliasingQuality TextAntiAliasingQuality
  2206. {
  2207. get
  2208. {
  2209. return _textAntiAliasingQuality;
  2210. }
  2211. set
  2212. {
  2213. _textAntiAliasingQuality = value;
  2214. }
  2215. }
  2216. /// <summary>
  2217. /// A type for the background gradient
  2218. /// </summary>
  2219. [
  2220. SRCategory("CategoryAttributeAppearance"),
  2221. Bindable(true),
  2222. DefaultValue(GradientStyle.None),
  2223. SRDescription("DescriptionAttributeBackGradientStyle"),
  2224. #if DESIGNER
  2225. Editor(typeof(GradientEditor), typeof(UITypeEditor))
  2226. #endif
  2227. ]
  2228. public GradientStyle BackGradientStyle
  2229. {
  2230. get
  2231. {
  2232. return _backGradientStyle;
  2233. }
  2234. set
  2235. {
  2236. _backGradientStyle = value;
  2237. }
  2238. }
  2239. /// <summary>
  2240. /// The second color which is used for a gradient
  2241. /// </summary>
  2242. [
  2243. SRCategory("CategoryAttributeAppearance"),
  2244. Bindable(true),
  2245. DefaultValue(typeof(Color), ""),
  2246. SRDescription("DescriptionAttributeBackSecondaryColor"),
  2247. TypeConverter(typeof(ColorConverter)),
  2248. #if DESIGNER
  2249. Editor(typeof(ChartColorEditor), typeof(UITypeEditor))
  2250. #endif
  2251. ]
  2252. public Color BackSecondaryColor
  2253. {
  2254. get
  2255. {
  2256. return _backSecondaryColor;
  2257. }
  2258. set
  2259. {
  2260. _backSecondaryColor = value;
  2261. }
  2262. }
  2263. /// <summary>
  2264. /// The width of the border line
  2265. /// </summary>
  2266. [
  2267. SRCategory("CategoryAttributeAppearance"),
  2268. Bindable(true),
  2269. DefaultValue(1),
  2270. SRDescription("DescriptionAttributeChart_BorderlineWidth"),
  2271. ]
  2272. public int BorderWidth
  2273. {
  2274. get
  2275. {
  2276. return _borderWidth;
  2277. }
  2278. set
  2279. {
  2280. if(value < 0)
  2281. {
  2282. throw(new ArgumentOutOfRangeException("value", SR.ExceptionChartBorderIsNegative));
  2283. }
  2284. _borderWidth = value;
  2285. }
  2286. }
  2287. /// <summary>
  2288. /// The style of the border line
  2289. /// </summary>
  2290. [
  2291. SRCategory("CategoryAttributeAppearance"),
  2292. Bindable(true),
  2293. DefaultValue(ChartDashStyle.NotSet),
  2294. SRDescription("DescriptionAttributeBorderDashStyle"),
  2295. ]
  2296. public ChartDashStyle BorderDashStyle
  2297. {
  2298. get
  2299. {
  2300. return _borderDashStyle;
  2301. }
  2302. set
  2303. {
  2304. _borderDashStyle = value;
  2305. }
  2306. }
  2307. /// <summary>
  2308. /// Gets the font cache.
  2309. /// </summary>
  2310. /// <value>The font cache.</value>
  2311. internal FontCache FontCache
  2312. {
  2313. get { return _fontCache; }
  2314. }
  2315. #endregion
  2316. #region Chart areas alignment methods
  2317. /// <summary>
  2318. /// Checks if any of the chart areas are aligned.
  2319. /// Also checks if the chart ares name in AlignWithChartArea property is valid.
  2320. /// </summary>
  2321. /// <returns>True if at least one area requires alignment.</returns>
  2322. private bool IsAreasAlignmentRequired()
  2323. {
  2324. bool alignmentRequired = false;
  2325. // Loop through all chart areas
  2326. foreach(ChartArea area in this.ChartAreas)
  2327. {
  2328. // Check if chart area is visible
  2329. if(area.Visible)
  2330. {
  2331. // Check if area is aligned
  2332. if (area.AlignWithChartArea != Constants.NotSetValue)
  2333. {
  2334. alignmentRequired = true;
  2335. // Check the chart area used for alignment
  2336. if (this._chartAreas.IndexOf(area.AlignWithChartArea)<0)
  2337. {
  2338. throw (new InvalidOperationException(SR.ExceptionChartAreaNameReferenceInvalid(area.Name, area.AlignWithChartArea)));
  2339. }
  2340. }
  2341. }
  2342. }
  2343. return alignmentRequired;
  2344. }
  2345. /// <summary>
  2346. /// Creates a list of the aligned chart areas.
  2347. /// </summary>
  2348. /// <param name="masterArea">Master chart area.</param>
  2349. /// <param name="type">Alignment type.</param>
  2350. /// <param name="orientation">Vertical or Horizontal orientation.</param>
  2351. /// <returns>List of areas that area aligned to the master area.</returns>
  2352. private ArrayList GetAlignedAreasGroup(ChartArea masterArea, AreaAlignmentStyles type, AreaAlignmentOrientations orientation)
  2353. {
  2354. ArrayList areaList = new ArrayList();
  2355. // Loop throught the chart areas and get the ones aligned with specified master area
  2356. foreach(ChartArea area in this.ChartAreas)
  2357. {
  2358. // Check if chart area is visible
  2359. if(area.Visible)
  2360. {
  2361. if(area.Name != masterArea.Name &&
  2362. area.AlignWithChartArea == masterArea.Name &&
  2363. (area.AlignmentStyle & type) == type &&
  2364. (area.AlignmentOrientation & orientation) == orientation )
  2365. {
  2366. // Add client area into the list
  2367. areaList.Add(area);
  2368. }
  2369. }
  2370. }
  2371. // If list is not empty insert "master" area in the beginning
  2372. if(areaList.Count > 0)
  2373. {
  2374. areaList.Insert(0, masterArea);
  2375. }
  2376. return areaList;
  2377. }
  2378. /// <summary>
  2379. /// Performs specified type of alignment for the chart areas.
  2380. /// </summary>
  2381. /// <param name="type">Alignment type required.</param>
  2382. internal void AlignChartAreas(AreaAlignmentStyles type)
  2383. {
  2384. // Check if alignment required
  2385. if(IsAreasAlignmentRequired())
  2386. {
  2387. // Loop through all chart areas
  2388. foreach(ChartArea area in this.ChartAreas)
  2389. {
  2390. // Check if chart area is visible
  2391. if(area.Visible)
  2392. {
  2393. // Get vertical areas alignment group using current area as a master
  2394. ArrayList alignGroup = GetAlignedAreasGroup(
  2395. area,
  2396. type,
  2397. AreaAlignmentOrientations.Vertical);
  2398. // Align each area in the group
  2399. if(alignGroup.Count > 0)
  2400. {
  2401. AlignChartAreasPlotPosition(alignGroup, AreaAlignmentOrientations.Vertical);
  2402. }
  2403. // Get horizontal areas alignment group using current area as a master
  2404. alignGroup = GetAlignedAreasGroup(
  2405. area,
  2406. type,
  2407. AreaAlignmentOrientations.Horizontal);
  2408. // Align each area in the group
  2409. if(alignGroup.Count > 0)
  2410. {
  2411. AlignChartAreasPlotPosition(alignGroup, AreaAlignmentOrientations.Horizontal);
  2412. }
  2413. }
  2414. }
  2415. }
  2416. }
  2417. /// <summary>
  2418. /// Align inner plot position of the chart areas in the group.
  2419. /// </summary>
  2420. /// <param name="areasGroup">List of areas in the group.</param>
  2421. /// <param name="orientation">Group orientation.</param>
  2422. private void AlignChartAreasPlotPosition(ArrayList areasGroup, AreaAlignmentOrientations orientation)
  2423. {
  2424. //****************************************************************
  2425. //** Find the smalles size of the inner plot
  2426. //****************************************************************
  2427. RectangleF areaPlotPosition = ((ChartArea)areasGroup[0]).PlotAreaPosition.ToRectangleF();
  2428. foreach(ChartArea area in areasGroup)
  2429. {
  2430. if(area.PlotAreaPosition.X > areaPlotPosition.X)
  2431. {
  2432. areaPlotPosition.X += area.PlotAreaPosition.X - areaPlotPosition.X;
  2433. areaPlotPosition.Width -= area.PlotAreaPosition.X - areaPlotPosition.X;
  2434. }
  2435. if(area.PlotAreaPosition.Y > areaPlotPosition.Y)
  2436. {
  2437. areaPlotPosition.Y += area.PlotAreaPosition.Y - areaPlotPosition.Y;
  2438. areaPlotPosition.Height -= area.PlotAreaPosition.Y - areaPlotPosition.Y;
  2439. }
  2440. if(area.PlotAreaPosition.Right < areaPlotPosition.Right)
  2441. {
  2442. areaPlotPosition.Width -= areaPlotPosition.Right - area.PlotAreaPosition.Right;
  2443. if(areaPlotPosition.Width < 5)
  2444. {
  2445. areaPlotPosition.Width = 5;
  2446. }
  2447. }
  2448. if(area.PlotAreaPosition.Bottom < areaPlotPosition.Bottom)
  2449. {
  2450. areaPlotPosition.Height -= areaPlotPosition.Bottom - area.PlotAreaPosition.Bottom;
  2451. if(areaPlotPosition.Height < 5)
  2452. {
  2453. areaPlotPosition.Height = 5;
  2454. }
  2455. }
  2456. }
  2457. //****************************************************************
  2458. //** Align inner plot position for all areas
  2459. //****************************************************************
  2460. foreach(ChartArea area in areasGroup)
  2461. {
  2462. // Get curretn plot position of the area
  2463. RectangleF rect = area.PlotAreaPosition.ToRectangleF();
  2464. // Adjust area position
  2465. if( (orientation & AreaAlignmentOrientations.Vertical) == AreaAlignmentOrientations.Vertical)
  2466. {
  2467. rect.X = areaPlotPosition.X;
  2468. rect.Width = areaPlotPosition.Width;
  2469. }
  2470. if( (orientation & AreaAlignmentOrientations.Horizontal) == AreaAlignmentOrientations.Horizontal)
  2471. {
  2472. rect.Y = areaPlotPosition.Y;
  2473. rect.Height = areaPlotPosition.Height;
  2474. }
  2475. // Set new plot position in coordinates relative to chart picture
  2476. area.PlotAreaPosition.SetPositionNoAuto(rect.X, rect.Y, rect.Width, rect.Height);
  2477. // Set new plot position in coordinates relative to chart area position
  2478. rect.X = (rect.X - area.Position.X) / area.Position.Width * 100f;
  2479. rect.Y = (rect.Y - area.Position.Y) / area.Position.Height * 100f;
  2480. rect.Width = rect.Width / area.Position.Width * 100f;
  2481. rect.Height = rect.Height / area.Position.Height * 100f;
  2482. area.InnerPlotPosition.SetPositionNoAuto(rect.X, rect.Y, rect.Width, rect.Height);
  2483. if( (orientation & AreaAlignmentOrientations.Vertical) == AreaAlignmentOrientations.Vertical)
  2484. {
  2485. area.AxisX2.AdjustLabelFontAtSecondPass(ChartGraph, area.InnerPlotPosition.Auto);
  2486. area.AxisX.AdjustLabelFontAtSecondPass(ChartGraph, area.InnerPlotPosition.Auto);
  2487. }
  2488. if( (orientation & AreaAlignmentOrientations.Horizontal) == AreaAlignmentOrientations.Horizontal)
  2489. {
  2490. area.AxisY2.AdjustLabelFontAtSecondPass(ChartGraph, area.InnerPlotPosition.Auto);
  2491. area.AxisY.AdjustLabelFontAtSecondPass(ChartGraph, area.InnerPlotPosition.Auto);
  2492. }
  2493. }
  2494. }
  2495. /// <summary>
  2496. /// Aligns positions of the chart areas.
  2497. /// </summary>
  2498. private void AlignChartAreasPosition()
  2499. {
  2500. // Check if alignment required
  2501. if(IsAreasAlignmentRequired())
  2502. {
  2503. // Loop through all chart areas
  2504. foreach(ChartArea area in this.ChartAreas)
  2505. {
  2506. // Check if chart area is visible
  2507. if(area.Visible)
  2508. {
  2509. // Check if area is alignd by Position to any other area
  2510. if (area.AlignWithChartArea != Constants.NotSetValue && (area.AlignmentStyle & AreaAlignmentStyles.Position) == AreaAlignmentStyles.Position)
  2511. {
  2512. // Get current area position
  2513. RectangleF areaPosition = area.Position.ToRectangleF();
  2514. // Get master chart area
  2515. ChartArea masterArea = this.ChartAreas[area.AlignWithChartArea];
  2516. // Vertical alignment
  2517. if((area.AlignmentOrientation & AreaAlignmentOrientations.Vertical) == AreaAlignmentOrientations.Vertical)
  2518. {
  2519. // Align area position
  2520. areaPosition.X = masterArea.Position.X;
  2521. areaPosition.Width = masterArea.Position.Width;
  2522. }
  2523. // Horizontal alignment
  2524. if((area.AlignmentOrientation & AreaAlignmentOrientations.Horizontal) == AreaAlignmentOrientations.Horizontal)
  2525. {
  2526. // Align area position
  2527. areaPosition.Y = masterArea.Position.Y;
  2528. areaPosition.Height = masterArea.Position.Height;
  2529. }
  2530. // Set new position
  2531. area.Position.SetPositionNoAuto(areaPosition.X, areaPosition.Y, areaPosition.Width, areaPosition.Height);
  2532. }
  2533. }
  2534. }
  2535. }
  2536. }
  2537. /// <summary>
  2538. /// Align chart areas cursor.
  2539. /// </summary>
  2540. /// <param name="changedArea">Changed chart area.</param>
  2541. /// <param name="orientation">Orientation of the changed cursor.</param>
  2542. /// <param name="selectionChanged">AxisName of change cursor or selection.</param>
  2543. internal void AlignChartAreasCursor(ChartArea changedArea, AreaAlignmentOrientations orientation, bool selectionChanged)
  2544. {
  2545. // Check if alignment required
  2546. if(IsAreasAlignmentRequired())
  2547. {
  2548. // Loop through all chart areas
  2549. foreach(ChartArea area in this.ChartAreas)
  2550. {
  2551. // Check if chart area is visible
  2552. if(area.Visible)
  2553. {
  2554. // Get vertical areas alignment group using current area as a master
  2555. ArrayList alignGroup = GetAlignedAreasGroup(
  2556. area,
  2557. AreaAlignmentStyles.Cursor,
  2558. orientation);
  2559. // Align each area in the group if it contains changed area
  2560. if(alignGroup.Contains(changedArea))
  2561. {
  2562. // Set cursor position for all areas in the group
  2563. foreach(ChartArea groupArea in alignGroup)
  2564. {
  2565. groupArea.alignmentInProcess = true;
  2566. if(orientation == AreaAlignmentOrientations.Vertical)
  2567. {
  2568. if(selectionChanged)
  2569. {
  2570. groupArea.CursorX.SelectionStart = changedArea.CursorX.SelectionStart;
  2571. groupArea.CursorX.SelectionEnd = changedArea.CursorX.SelectionEnd;
  2572. }
  2573. else
  2574. {
  2575. groupArea.CursorX.Position = changedArea.CursorX.Position;
  2576. }
  2577. }
  2578. if(orientation == AreaAlignmentOrientations.Horizontal)
  2579. {
  2580. if(selectionChanged)
  2581. {
  2582. groupArea.CursorY.SelectionStart = changedArea.CursorY.SelectionStart;
  2583. groupArea.CursorY.SelectionEnd = changedArea.CursorY.SelectionEnd;
  2584. }
  2585. else
  2586. {
  2587. groupArea.CursorY.Position = changedArea.CursorY.Position;
  2588. }
  2589. }
  2590. groupArea.alignmentInProcess = false;
  2591. }
  2592. }
  2593. }
  2594. }
  2595. }
  2596. }
  2597. /// <summary>
  2598. /// One of the chart areas was zoomed by the user.
  2599. /// </summary>
  2600. /// <param name="changedArea">Changed chart area.</param>
  2601. /// <param name="orientation">Orientation of the changed scaleView.</param>
  2602. /// <param name="disposeBufferBitmap">Area double fuffer image must be disposed.</param>
  2603. internal void AlignChartAreasZoomed(ChartArea changedArea, AreaAlignmentOrientations orientation, bool disposeBufferBitmap)
  2604. {
  2605. // Check if alignment required
  2606. if(IsAreasAlignmentRequired())
  2607. {
  2608. // Loop through all chart areas
  2609. foreach(ChartArea area in this.ChartAreas)
  2610. {
  2611. // Check if chart area is visible
  2612. if(area.Visible)
  2613. {
  2614. // Get vertical areas alignment group using current area as a master
  2615. ArrayList alignGroup = GetAlignedAreasGroup(
  2616. area,
  2617. AreaAlignmentStyles.AxesView,
  2618. orientation);
  2619. // Align each area in the group if it contains changed area
  2620. if(alignGroup.Contains(changedArea))
  2621. {
  2622. // Set cursor position for all areas in the group
  2623. foreach(ChartArea groupArea in alignGroup)
  2624. {
  2625. // Clear image buffer
  2626. if(groupArea.areaBufferBitmap != null && disposeBufferBitmap)
  2627. {
  2628. groupArea.areaBufferBitmap.Dispose();
  2629. groupArea.areaBufferBitmap = null;
  2630. }
  2631. if(orientation == AreaAlignmentOrientations.Vertical)
  2632. {
  2633. groupArea.CursorX.SelectionStart = double.NaN;
  2634. groupArea.CursorX.SelectionEnd = double.NaN;
  2635. }
  2636. if(orientation == AreaAlignmentOrientations.Horizontal)
  2637. {
  2638. groupArea.CursorY.SelectionStart = double.NaN;
  2639. groupArea.CursorY.SelectionEnd = double.NaN;
  2640. }
  2641. }
  2642. }
  2643. }
  2644. }
  2645. }
  2646. }
  2647. /// <summary>
  2648. /// Align chart areas axes views.
  2649. /// </summary>
  2650. /// <param name="changedArea">Changed chart area.</param>
  2651. /// <param name="orientation">Orientation of the changed scaleView.</param>
  2652. internal void AlignChartAreasAxesView(ChartArea changedArea, AreaAlignmentOrientations orientation)
  2653. {
  2654. // Check if alignment required
  2655. if(IsAreasAlignmentRequired())
  2656. {
  2657. // Loop through all chart areas
  2658. foreach(ChartArea area in this.ChartAreas)
  2659. {
  2660. // Check if chart area is visible
  2661. if(area.Visible)
  2662. {
  2663. // Get vertical areas alignment group using current area as a master
  2664. ArrayList alignGroup = GetAlignedAreasGroup(
  2665. area,
  2666. AreaAlignmentStyles.AxesView,
  2667. orientation);
  2668. // Align each area in the group if it contains changed area
  2669. if(alignGroup.Contains(changedArea))
  2670. {
  2671. // Set cursor position for all areas in the group
  2672. foreach(ChartArea groupArea in alignGroup)
  2673. {
  2674. groupArea.alignmentInProcess = true;
  2675. if(orientation == AreaAlignmentOrientations.Vertical)
  2676. {
  2677. groupArea.AxisX.ScaleView.Position = changedArea.AxisX.ScaleView.Position;
  2678. groupArea.AxisX.ScaleView.Size = changedArea.AxisX.ScaleView.Size;
  2679. groupArea.AxisX.ScaleView.SizeType = changedArea.AxisX.ScaleView.SizeType;
  2680. groupArea.AxisX2.ScaleView.Position = changedArea.AxisX2.ScaleView.Position;
  2681. groupArea.AxisX2.ScaleView.Size = changedArea.AxisX2.ScaleView.Size;
  2682. groupArea.AxisX2.ScaleView.SizeType = changedArea.AxisX2.ScaleView.SizeType;
  2683. }
  2684. if(orientation == AreaAlignmentOrientations.Horizontal)
  2685. {
  2686. groupArea.AxisY.ScaleView.Position = changedArea.AxisY.ScaleView.Position;
  2687. groupArea.AxisY.ScaleView.Size = changedArea.AxisY.ScaleView.Size;
  2688. groupArea.AxisY.ScaleView.SizeType = changedArea.AxisY.ScaleView.SizeType;
  2689. groupArea.AxisY2.ScaleView.Position = changedArea.AxisY2.ScaleView.Position;
  2690. groupArea.AxisY2.ScaleView.Size = changedArea.AxisY2.ScaleView.Size;
  2691. groupArea.AxisY2.ScaleView.SizeType = changedArea.AxisY2.ScaleView.SizeType;
  2692. }
  2693. groupArea.alignmentInProcess = false;
  2694. }
  2695. }
  2696. }
  2697. }
  2698. }
  2699. }
  2700. #endregion
  2701. #region Helper methods
  2702. /// <summary>
  2703. /// Inspects the chart dimensions.
  2704. /// </summary>
  2705. /// <param name="width">The width.</param>
  2706. /// <param name="height">The height.</param>
  2707. internal void InspectChartDimensions(int width, int height)
  2708. {
  2709. if (this.Chart.IsDesignMode() && ((width * height) > (100 * 1024 *1024)))
  2710. {
  2711. throw new ArgumentException(SR.ExceptionChartOutOfLimits);
  2712. }
  2713. if (width < 0)
  2714. {
  2715. throw new ArgumentException(SR.ExceptionValueMustBeGreaterThan("Width", "0px"));
  2716. }
  2717. if (height < 0)
  2718. {
  2719. throw new ArgumentException(SR.ExceptionValueMustBeGreaterThan("Height", "0px"));
  2720. }
  2721. }
  2722. /// <summary>
  2723. /// Loads chart appearance template from file.
  2724. /// </summary>
  2725. /// <param name="name">Template file name to load from.</param>
  2726. public void LoadTemplate(string name)
  2727. {
  2728. // Check arguments
  2729. if (name == null)
  2730. throw new ArgumentNullException("name");
  2731. // Load template data into the stream
  2732. Stream stream = new FileStream(name, FileMode.Open, FileAccess.Read);
  2733. // Load template from stream
  2734. LoadTemplate(stream);
  2735. // Close tempate stream
  2736. stream.Close();
  2737. }
  2738. /// <summary>
  2739. /// Loads chart appearance template from stream.
  2740. /// </summary>
  2741. /// <param name="stream">Template stream to load from.</param>
  2742. public void LoadTemplate(Stream stream)
  2743. {
  2744. // Check arguments
  2745. if (stream == null)
  2746. throw new ArgumentNullException("stream");
  2747. ChartSerializer serializer = (ChartSerializer)this.Common.container.GetService(typeof(ChartSerializer));
  2748. if (serializer != null)
  2749. {
  2750. // Save previous serializer properties
  2751. string oldSerializableContent = serializer.SerializableContent;
  2752. string oldNonSerializableContent = serializer.NonSerializableContent;
  2753. SerializationFormat oldFormat = serializer.Format;
  2754. bool oldIgnoreUnknownXmlAttributes = serializer.IsUnknownAttributeIgnored;
  2755. bool oldTemplateMode = serializer.IsTemplateMode;
  2756. // Set serializer properties
  2757. serializer.Content = SerializationContents.Appearance;
  2758. serializer.SerializableContent += ",Chart.Titles,Chart.Annotations," +
  2759. "Chart.Legends,Legend.CellColumns,Legend.CustomItems,LegendItem.Cells," +
  2760. "Chart.Series,Series.*Style," +
  2761. "Chart.ChartAreas,ChartArea.Axis*," +
  2762. "Axis.*Grid,Axis.*TickMark, Axis.*Style," +
  2763. "Axis.StripLines, Axis.CustomLabels";
  2764. serializer.Format = SerializationFormat.Xml;
  2765. serializer.IsUnknownAttributeIgnored = true;
  2766. serializer.IsTemplateMode = true;
  2767. try
  2768. {
  2769. // Load template
  2770. serializer.Load(stream);
  2771. }
  2772. catch (Exception ex)
  2773. {
  2774. throw (new InvalidOperationException(ex.Message));
  2775. }
  2776. finally
  2777. {
  2778. // Restore previous serializer properties
  2779. serializer.SerializableContent = oldSerializableContent;
  2780. serializer.NonSerializableContent = oldNonSerializableContent;
  2781. serializer.Format = oldFormat;
  2782. serializer.IsUnknownAttributeIgnored = oldIgnoreUnknownXmlAttributes;
  2783. serializer.IsTemplateMode = oldTemplateMode;
  2784. }
  2785. }
  2786. }
  2787. /// <summary>
  2788. /// Returns the default title from Titles collection.
  2789. /// </summary>
  2790. /// <param name="create">Create title if it doesn't exists.</param>
  2791. /// <returns>Default title.</returns>
  2792. internal Title GetDefaultTitle(bool create)
  2793. {
  2794. // Check if default title exists
  2795. Title defaultTitle = null;
  2796. foreach(Title title in this.Titles)
  2797. {
  2798. if(title.Name == "Default Title")
  2799. {
  2800. defaultTitle = title;
  2801. }
  2802. }
  2803. // Create new default title
  2804. if(defaultTitle == null && create)
  2805. {
  2806. defaultTitle = new Title();
  2807. defaultTitle.Name = "Default Title";
  2808. this.Titles.Insert(0, defaultTitle);
  2809. }
  2810. return defaultTitle;
  2811. }
  2812. /// <summary>
  2813. /// Checks if tooltips are enabled
  2814. /// </summary>
  2815. /// <returns>true if tooltips enabled</returns>
  2816. private bool IsToolTipsEnabled()
  2817. {
  2818. // Data series loop
  2819. foreach( Series series in Common.DataManager.Series )
  2820. {
  2821. // Check series tooltips
  2822. if( series.ToolTip.Length > 0)
  2823. {
  2824. // ToolTips enabled
  2825. return true;
  2826. }
  2827. // Check series tooltips
  2828. if( series.LegendToolTip.Length > 0 ||
  2829. series.LabelToolTip.Length > 0)
  2830. {
  2831. // ToolTips enabled
  2832. return true;
  2833. }
  2834. // Check point tooltips only for "non-Fast" chart types
  2835. if( !series.IsFastChartType() )
  2836. {
  2837. // Data point loop
  2838. foreach( DataPoint point in series.Points )
  2839. {
  2840. // ToolTip empty
  2841. if( point.ToolTip.Length > 0)
  2842. {
  2843. // ToolTips enabled
  2844. return true;
  2845. }
  2846. // ToolTip empty
  2847. if( point.LegendToolTip.Length > 0 ||
  2848. point.LabelToolTip.Length > 0)
  2849. {
  2850. // ToolTips enabled
  2851. return true;
  2852. }
  2853. }
  2854. }
  2855. }
  2856. // Legend items loop
  2857. foreach( Legend legend in Legends )
  2858. {
  2859. foreach( LegendItem legendItem in legend.CustomItems )
  2860. {
  2861. // ToolTip empty
  2862. if( legendItem.ToolTip.Length > 0 )
  2863. {
  2864. return true;
  2865. }
  2866. }
  2867. }
  2868. // Title items loop
  2869. foreach( Title title in Titles )
  2870. {
  2871. // ToolTip empty
  2872. if( title.ToolTip.Length > 0 )
  2873. {
  2874. return true;
  2875. }
  2876. }
  2877. return false;
  2878. }
  2879. #endregion
  2880. #region IDisposable Members
  2881. /// <summary>
  2882. /// Releases unmanaged and - optionally - managed resources
  2883. /// </summary>
  2884. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  2885. protected override void Dispose(bool disposing)
  2886. {
  2887. if (disposing)
  2888. {
  2889. // Dispose managed resources
  2890. if (ChartGraph != null)
  2891. {
  2892. ChartGraph.Dispose();
  2893. ChartGraph = null;
  2894. }
  2895. if (_legends != null)
  2896. {
  2897. _legends.Dispose();
  2898. _legends = null;
  2899. }
  2900. if (_titles != null)
  2901. {
  2902. _titles.Dispose();
  2903. _titles = null;
  2904. }
  2905. if (_chartAreas != null)
  2906. {
  2907. _chartAreas.Dispose();
  2908. _chartAreas = null;
  2909. }
  2910. if (_annotations != null)
  2911. {
  2912. _annotations.Dispose();
  2913. _annotations = null;
  2914. }
  2915. if (hotRegionsList != null)
  2916. {
  2917. hotRegionsList.Dispose();
  2918. hotRegionsList = null;
  2919. }
  2920. if (_fontCache != null)
  2921. {
  2922. _fontCache.Dispose();
  2923. _fontCache = null;
  2924. }
  2925. if (_borderSkin != null)
  2926. {
  2927. _borderSkin.Dispose();
  2928. _borderSkin = null;
  2929. }
  2930. if (nonTopLevelChartBuffer != null)
  2931. {
  2932. nonTopLevelChartBuffer.Dispose();
  2933. nonTopLevelChartBuffer = null;
  2934. }
  2935. }
  2936. base.Dispose(disposing);
  2937. }
  2938. #endregion
  2939. }
  2940. /// <summary>
  2941. /// Event arguments of Chart paint event.
  2942. /// </summary>
  2943. public class ChartPaintEventArgs : EventArgs
  2944. {
  2945. #region Fields
  2946. // Private fields
  2947. private object _chartElement = null;
  2948. private ChartGraphics _chartGraph = null;
  2949. private CommonElements _common = null;
  2950. private Chart _chart = null;
  2951. private ElementPosition _position = null;
  2952. #endregion
  2953. #region Properties
  2954. /// <summary>
  2955. /// Gets the chart element of the event.
  2956. /// </summary>
  2957. /// <value>The chart element.</value>
  2958. public object ChartElement
  2959. {
  2960. get
  2961. {
  2962. return _chartElement;
  2963. }
  2964. }
  2965. /// <summary>
  2966. /// Gets the ChartGraphics object of the event.
  2967. /// </summary>
  2968. public ChartGraphics ChartGraphics
  2969. {
  2970. get
  2971. {
  2972. return _chartGraph;
  2973. }
  2974. }
  2975. /// <summary>
  2976. /// Chart Common elements.
  2977. /// </summary>
  2978. internal CommonElements CommonElements
  2979. {
  2980. get
  2981. {
  2982. return _common;
  2983. }
  2984. }
  2985. /// <summary>
  2986. /// Chart element position in relative coordinates of the event.
  2987. /// </summary>
  2988. public ElementPosition Position
  2989. {
  2990. get
  2991. {
  2992. return _position;
  2993. }
  2994. }
  2995. /// <summary>
  2996. /// Chart object of the event.
  2997. /// </summary>
  2998. public Chart Chart
  2999. {
  3000. get
  3001. {
  3002. if (_chart == null && _common != null)
  3003. {
  3004. _chart = _common.Chart;
  3005. }
  3006. return _chart;
  3007. }
  3008. }
  3009. #endregion
  3010. #region Methods
  3011. /// <summary>
  3012. /// Default constructor is not accessible
  3013. /// </summary>
  3014. private ChartPaintEventArgs()
  3015. {
  3016. }
  3017. /// <summary>
  3018. /// Paint event arguments constructor.
  3019. /// </summary>
  3020. /// <param name="chartElement">Chart element.</param>
  3021. /// <param name="chartGraph">Chart graphics.</param>
  3022. /// <param name="common">Common elements.</param>
  3023. /// <param name="position">Position.</param>
  3024. internal ChartPaintEventArgs(object chartElement, ChartGraphics chartGraph, CommonElements common, ElementPosition position)
  3025. {
  3026. this._chartElement = chartElement;
  3027. this._chartGraph = chartGraph;
  3028. this._common = common;
  3029. this._position = position;
  3030. }
  3031. #endregion
  3032. }
  3033. /// <summary>
  3034. /// Event arguments of localized numbers formatting event.
  3035. /// </summary>
  3036. public class FormatNumberEventArgs : EventArgs
  3037. {
  3038. #region Fields
  3039. // Private fields
  3040. private double _value;
  3041. private string _format;
  3042. private string _localizedValue;
  3043. private ChartValueType _valueType = ChartValueType.Auto;
  3044. private object _senderTag;
  3045. private ChartElementType _elementType = ChartElementType.Nothing;
  3046. #endregion
  3047. #region Properties
  3048. /// <summary>
  3049. /// Value to be formatted.
  3050. /// </summary>
  3051. public double Value
  3052. {
  3053. get { return this._value; }
  3054. }
  3055. /// <summary>
  3056. /// Localized text.
  3057. /// </summary>
  3058. public string LocalizedValue
  3059. {
  3060. get { return _localizedValue; }
  3061. set { _localizedValue = value; }
  3062. }
  3063. /// <summary>
  3064. /// Format string.
  3065. /// </summary>
  3066. public string Format
  3067. {
  3068. get { return _format; }
  3069. }
  3070. /// <summary>
  3071. /// Value type.
  3072. /// </summary>
  3073. public ChartValueType ValueType
  3074. {
  3075. get { return _valueType; }
  3076. }
  3077. /// <summary>
  3078. /// The sender object of the event.
  3079. /// </summary>
  3080. public object SenderTag
  3081. {
  3082. get { return _senderTag; }
  3083. }
  3084. /// <summary>
  3085. /// Chart element type.
  3086. /// </summary>
  3087. public ChartElementType ElementType
  3088. {
  3089. get { return _elementType; }
  3090. }
  3091. #endregion
  3092. #region Methods
  3093. /// <summary>
  3094. /// Default constructor is not accessible
  3095. /// </summary>
  3096. private FormatNumberEventArgs()
  3097. {
  3098. }
  3099. /// <summary>
  3100. /// Object constructor.
  3101. /// </summary>
  3102. /// <param name="value">Value to be formatted.</param>
  3103. /// <param name="format">Format string.</param>
  3104. /// <param name="valueType">Value type..</param>
  3105. /// <param name="localizedValue">Localized value.</param>
  3106. /// <param name="senderTag">Chart element object tag.</param>
  3107. /// <param name="elementType">Chart element type.</param>
  3108. internal FormatNumberEventArgs(double value, string format, ChartValueType valueType, string localizedValue, object senderTag, ChartElementType elementType)
  3109. {
  3110. this._value = value;
  3111. this._format = format;
  3112. this._valueType = valueType;
  3113. this._localizedValue = localizedValue;
  3114. this._senderTag = senderTag;
  3115. this._elementType = elementType;
  3116. }
  3117. #endregion
  3118. }
  3119. #region FontCache
  3120. /// <summary>
  3121. /// Font cache class helps ChartElements to reuse the Font instances
  3122. /// </summary>
  3123. internal class FontCache : IDisposable
  3124. {
  3125. #region Static
  3126. // Default font family name
  3127. private static string _defaultFamilyName;
  3128. /// <summary>
  3129. /// Gets the default font family name.
  3130. /// </summary>
  3131. /// <value>The default font family name.</value>
  3132. public static string DefaultFamilyName
  3133. {
  3134. get
  3135. {
  3136. if (_defaultFamilyName == null)
  3137. {
  3138. // Find the "Microsoft Sans Serif" font
  3139. foreach (FontFamily fontFamily in FontFamily.Families)
  3140. {
  3141. if (fontFamily.Name == "Microsoft Sans Serif")
  3142. {
  3143. _defaultFamilyName = fontFamily.Name;
  3144. break;
  3145. }
  3146. }
  3147. // Not found - use the default Sans Serif font
  3148. if (_defaultFamilyName == null)
  3149. {
  3150. _defaultFamilyName = FontFamily.GenericSansSerif.Name;
  3151. }
  3152. }
  3153. return _defaultFamilyName;
  3154. }
  3155. }
  3156. #endregion
  3157. #region Fields
  3158. // Cached fonts dictionary
  3159. private Dictionary<KeyInfo, Font> _fontCache = new Dictionary<KeyInfo, Font>(new KeyInfo.EqualityComparer());
  3160. #endregion // Fields
  3161. #region Properties
  3162. /// <summary>
  3163. /// Gets the default font.
  3164. /// </summary>
  3165. /// <value>The default font.</value>
  3166. public Font DefaultFont
  3167. {
  3168. get { return this.GetFont(DefaultFamilyName, 8); }
  3169. }
  3170. /// <summary>
  3171. /// Gets the default font.
  3172. /// </summary>
  3173. /// <value>The default font.</value>
  3174. public Font DefaultBoldFont
  3175. {
  3176. get { return this.GetFont(DefaultFamilyName, 8, FontStyle.Bold); }
  3177. }
  3178. #endregion
  3179. #region Methods
  3180. /// <summary>
  3181. /// Gets the font.
  3182. /// </summary>
  3183. /// <param name="familyName">Name of the family.</param>
  3184. /// <param name="size">The size.</param>
  3185. /// <returns>Font instance</returns>
  3186. public Font GetFont(string familyName, int size)
  3187. {
  3188. KeyInfo key = new KeyInfo(familyName, size);
  3189. if (!this._fontCache.ContainsKey(key))
  3190. {
  3191. this._fontCache.Add(key, new Font(familyName, size));
  3192. }
  3193. return this._fontCache[key];
  3194. }
  3195. /// <summary>
  3196. /// Gets the font.
  3197. /// </summary>
  3198. /// <param name="familyName">Name of the family.</param>
  3199. /// <param name="size">The size.</param>
  3200. /// <param name="style">The style.</param>
  3201. /// <returns>Font instance</returns>
  3202. public Font GetFont(string familyName, float size, FontStyle style)
  3203. {
  3204. KeyInfo key = new KeyInfo(familyName, size, style);
  3205. if (!this._fontCache.ContainsKey(key))
  3206. {
  3207. this._fontCache.Add(key, new Font(familyName, size, style));
  3208. }
  3209. return this._fontCache[key];
  3210. }
  3211. /// <summary>
  3212. /// Gets the font.
  3213. /// </summary>
  3214. /// <param name="family">The family.</param>
  3215. /// <param name="size">The size.</param>
  3216. /// <param name="style">The style.</param>
  3217. /// <returns>Font instance</returns>
  3218. public Font GetFont(FontFamily family, float size, FontStyle style)
  3219. {
  3220. KeyInfo key = new KeyInfo(family, size, style);
  3221. if (!this._fontCache.ContainsKey(key))
  3222. {
  3223. this._fontCache.Add(key, new Font(family, size, style));
  3224. }
  3225. return this._fontCache[key];
  3226. }
  3227. /// <summary>
  3228. /// Gets the font.
  3229. /// </summary>
  3230. /// <param name="family">The family.</param>
  3231. /// <param name="size">The size.</param>
  3232. /// <param name="style">The style.</param>
  3233. /// <param name="unit">The unit.</param>
  3234. /// <returns>Font instance</returns>
  3235. public Font GetFont(FontFamily family, float size, FontStyle style, GraphicsUnit unit)
  3236. {
  3237. KeyInfo key = new KeyInfo(family, size, style, unit);
  3238. if (!this._fontCache.ContainsKey(key))
  3239. {
  3240. this._fontCache.Add(key, new Font(family, size, style, unit));
  3241. }
  3242. return this._fontCache[key];
  3243. }
  3244. #endregion
  3245. #region IDisposable Members
  3246. /// <summary>
  3247. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  3248. /// </summary>
  3249. public void Dispose()
  3250. {
  3251. foreach (Font font in _fontCache.Values)
  3252. {
  3253. font.Dispose();
  3254. }
  3255. _fontCache.Clear();
  3256. GC.SuppressFinalize(this);
  3257. }
  3258. #endregion
  3259. #region FontKeyInfo struct
  3260. /// <summary>
  3261. /// Font key info
  3262. /// </summary>
  3263. private class KeyInfo
  3264. {
  3265. string _familyName;
  3266. float _size = 8;
  3267. GraphicsUnit _unit = GraphicsUnit.Point;
  3268. FontStyle _style = FontStyle.Regular;
  3269. int _gdiCharSet = 1;
  3270. /// <summary>
  3271. /// Initializes a new instance of the <see cref="KeyInfo"/> class.
  3272. /// </summary>
  3273. /// <param name="familyName">Name of the family.</param>
  3274. /// <param name="size">The size.</param>
  3275. public KeyInfo(string familyName, float size)
  3276. {
  3277. this._familyName = familyName;
  3278. this._size = size;
  3279. }
  3280. /// <summary>
  3281. /// Initializes a new instance of the <see cref="KeyInfo"/> class.
  3282. /// </summary>
  3283. /// <param name="familyName">Name of the family.</param>
  3284. /// <param name="size">The size.</param>
  3285. /// <param name="style">The style.</param>
  3286. public KeyInfo(string familyName, float size, FontStyle style)
  3287. {
  3288. this._familyName = familyName;
  3289. this._size = size;
  3290. this._style = style;
  3291. }
  3292. /// <summary>
  3293. /// Initializes a new instance of the <see cref="KeyInfo"/> class.
  3294. /// </summary>
  3295. /// <param name="family">The family.</param>
  3296. /// <param name="size">The size.</param>
  3297. /// <param name="style">The style.</param>
  3298. public KeyInfo(FontFamily family, float size, FontStyle style)
  3299. {
  3300. this._familyName = family.ToString();
  3301. this._size = size;
  3302. this._style = style;
  3303. }
  3304. /// <summary>
  3305. /// Initializes a new instance of the <see cref="KeyInfo"/> class.
  3306. /// </summary>
  3307. /// <param name="family">The family.</param>
  3308. /// <param name="size">The size.</param>
  3309. /// <param name="style">The style.</param>
  3310. /// <param name="unit">The unit.</param>
  3311. public KeyInfo(FontFamily family, float size, FontStyle style, GraphicsUnit unit)
  3312. {
  3313. this._familyName = family.ToString();
  3314. this._size = size;
  3315. this._style = style;
  3316. this._unit = unit;
  3317. }
  3318. #region IEquatable<FontKeyInfo> Members
  3319. /// <summary>
  3320. /// KeyInfo equality comparer
  3321. /// </summary>
  3322. internal class EqualityComparer : IEqualityComparer<KeyInfo>
  3323. {
  3324. /// <summary>
  3325. /// Determines whether the specified objects are equal.
  3326. /// </summary>
  3327. /// <param name="x">The first object of type <paramref name="x"/> to compare.</param>
  3328. /// <param name="y">The second object of type <paramref name="y"/> to compare.</param>
  3329. /// <returns>
  3330. /// true if the specified objects are equal; otherwise, false.
  3331. /// </returns>
  3332. public bool Equals(KeyInfo x, KeyInfo y)
  3333. {
  3334. return
  3335. x._size == y._size &&
  3336. x._familyName == y._familyName &&
  3337. x._unit == y._unit &&
  3338. x._style == y._style &&
  3339. x._gdiCharSet == y._gdiCharSet;
  3340. }
  3341. /// <summary>
  3342. /// Returns a hash code for the specified object.
  3343. /// </summary>
  3344. /// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param>
  3345. /// <returns>A hash code for the specified object.</returns>
  3346. /// <exception cref="T:System.ArgumentNullException">The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
  3347. public int GetHashCode(KeyInfo obj)
  3348. {
  3349. return obj._familyName.GetHashCode() ^ obj._size.GetHashCode();
  3350. }
  3351. }
  3352. #endregion
  3353. }
  3354. #endregion
  3355. }
  3356. #endregion
  3357. }