Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4954 lines
137 KiB

  1. #include <windows.h>
  2. #include <windowsx.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <io.h>
  6. #include <hlink.h>
  7. #include <dispex.h>
  8. #include "mshtml.h"
  9. #include "msxml.h"
  10. #include <winnls.h>
  11. #include "atlbase.h" // USES_CONVERSION
  12. #include "dbg.h"
  13. #include "..\inc\cstr.h"
  14. #include "macros.h"
  15. #include <comdef.h>
  16. //You may derive a class from CComModule and use it if you want to override
  17. //something, but do not change the name of _Module
  18. extern CComModule _Module;
  19. #include <atlcom.h>
  20. #include <map>
  21. #include <list>
  22. #include <vector>
  23. #include "mmcdebug.h"
  24. #include "mmcerror.h"
  25. #include "..\inc\xmlbase.h"
  26. #include "countof.h"
  27. #include <commctrl.h>
  28. #include "picon.h"
  29. #include "base64.h"
  30. #include "strings.h"
  31. #include "autoptr.h"
  32. #include <shlobj.h>
  33. #include "zlib.h"
  34. #include "xmlicon.h"
  35. //############################################################################
  36. //############################################################################
  37. //
  38. // The safer string handling routines
  39. //
  40. //############################################################################
  41. //############################################################################
  42. #include <strsafe.h>
  43. SC ScEncodeBinary(CComBSTR& bstrResult, const CXMLBinary& binSrc);
  44. SC ScDecodeBinary(const CComBSTR& bstrSource, CXMLBinary *pBinResult);
  45. SC ScSaveXMLDocumentToString(CXMLDocument& xmlDocument, std::wstring& strResult);
  46. // Traces
  47. #ifdef DBG
  48. CTraceTag tagXMLCompression(TEXT("Console Files"), TEXT("Compression"));
  49. #endif
  50. //############################################################################
  51. //############################################################################
  52. //
  53. // helper classes used in this file
  54. //
  55. //############################################################################
  56. //############################################################################
  57. /*+-------------------------------------------------------------------------*
  58. * class CXMLBinaryValue
  59. *
  60. * PURPOSE: Persists the contents of XMLValue on binary storage
  61. * It's a simle wrapper needed to inform CPersistor about
  62. * values wish to be persisted on Binary storage
  63. * [see comment "CONCEPT OF BINARY STORAGE" in "xmbase.h"]
  64. *
  65. *+-------------------------------------------------------------------------*/
  66. class CXMLBinaryValue : public CXMLObject
  67. {
  68. CXMLValue m_xval;
  69. public:
  70. CXMLBinaryValue(CXMLValue xval) : m_xval(xval) {}
  71. virtual LPCTSTR GetXMLType() { return m_xval.GetTypeName(); }
  72. virtual void Persist(CPersistor &persistor)
  73. {
  74. persistor.PersistContents (m_xval);
  75. }
  76. virtual bool UsesBinaryStorage() { return true; }
  77. };
  78. //############################################################################
  79. //############################################################################
  80. //
  81. // Implementation of class CXMLElementCollection
  82. //
  83. //############################################################################
  84. //############################################################################
  85. /***************************************************************************\
  86. *
  87. * METHOD: CXMLElementCollection::get_count
  88. *
  89. * PURPOSE: // returns count of elements in the collection
  90. *
  91. * PARAMETERS:
  92. * long *plLength [out] - count of the elements
  93. *
  94. * RETURNS:
  95. * void
  96. *
  97. \***************************************************************************/
  98. void
  99. CXMLElementCollection::get_count(long *plCount)
  100. {
  101. DECLARE_SC(sc, TEXT("CXMLElementCollection::get_count"));
  102. // check if we have the interface pointer to forward the call
  103. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  104. if (sc)
  105. sc.Throw();
  106. sc = m_sp->get_length(plCount);
  107. if (sc)
  108. sc.Throw();
  109. }
  110. /***************************************************************************\
  111. *
  112. * METHOD: CXMLElementCollection::item
  113. *
  114. * PURPOSE: wraps item method from IXMLDOMNodeList
  115. *
  116. * PARAMETERS:
  117. * VARIANT Var1 [in] parameter #1
  118. * VARIANT Var2 [in] parameter #2
  119. * CXMLElement *pElem [out] resulting element
  120. *
  121. * RETURNS:
  122. * void
  123. *
  124. \***************************************************************************/
  125. void
  126. CXMLElementCollection::item(LONG lIndex, CXMLElement *pElem)
  127. {
  128. DECLARE_SC(sc, TEXT("CXMLElementCollection::item"));
  129. // check params
  130. sc = ScCheckPointers(pElem);
  131. if (sc)
  132. sc.Throw();
  133. // init ret val
  134. *pElem = CXMLElement();
  135. // check if we have the interface pointer to forward the call
  136. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  137. if (sc)
  138. sc.Throw();
  139. CComPtr<IXMLDOMNode> spNode;
  140. sc = m_sp->get_item(lIndex , &spNode);
  141. if(sc)
  142. sc.Throw();
  143. // return the object
  144. *pElem = CXMLElement(spNode);
  145. }
  146. //############################################################################
  147. //############################################################################
  148. //
  149. // Implementation of class CXMLElement
  150. //
  151. //############################################################################
  152. //############################################################################
  153. /***************************************************************************\
  154. *
  155. * METHOD: CXMLElement::get_tagName
  156. *
  157. * PURPOSE: returns tag name of the element
  158. *
  159. * PARAMETERS:
  160. * CStr &strTagName [out] element's name
  161. *
  162. * RETURNS:
  163. * void
  164. *
  165. \***************************************************************************/
  166. void
  167. CXMLElement::get_tagName(CStr &strTagName)
  168. {
  169. DECLARE_SC(sc, TEXT("CXMLElement::get_tagName"));
  170. USES_CONVERSION;
  171. // get the element
  172. CComQIPtr<IXMLDOMElement> spEl;
  173. spEl = m_sp;
  174. // check if we have the interface pointer to forward the call
  175. sc = ScCheckPointers(spEl, E_NOINTERFACE);
  176. if (sc)
  177. sc.Throw();
  178. CComBSTR bstr;
  179. sc = spEl->get_tagName(&bstr);
  180. if(sc)
  181. sc.Throw();
  182. strTagName=OLE2T(bstr);
  183. }
  184. /***************************************************************************\
  185. *
  186. * METHOD: CXMLElement::get_parent
  187. *
  188. * PURPOSE: returns parent element
  189. *
  190. * PARAMETERS:
  191. * CXMLElement * pParent - [out] parent element
  192. *
  193. * RETURNS:
  194. * void
  195. *
  196. \***************************************************************************/
  197. void
  198. CXMLElement::get_parent(CXMLElement * pParent)
  199. {
  200. DECLARE_SC(sc, TEXT("CXMLElement::get_parent"));
  201. // parameter check
  202. sc = ScCheckPointers(pParent);
  203. if (sc)
  204. sc.Throw();
  205. // init return value
  206. *pParent = CXMLElement();
  207. // check if we have the interface pointer to forward the call
  208. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  209. if (sc)
  210. sc.Throw();
  211. CComPtr<IXMLDOMNode> spParent;
  212. sc = m_sp->get_parentNode(&spParent);
  213. if(sc)
  214. sc.Throw();
  215. *pParent = CXMLElement(spParent);
  216. }
  217. /***************************************************************************\
  218. *
  219. * METHOD: CXMLElement::setAttribute
  220. *
  221. * PURPOSE: assigns attribute to the element
  222. *
  223. * PARAMETERS:
  224. * const CStr &strPropertyName - attribute name
  225. * const CComBSTR &bstrPropertyValue - attribute value
  226. *
  227. * RETURNS:
  228. * void
  229. *
  230. \***************************************************************************/
  231. void
  232. CXMLElement::setAttribute(const CStr &strPropertyName, const CComBSTR &bstrPropertyValue)
  233. {
  234. DECLARE_SC(sc, TEXT("CXMLElement::setAttribute"));
  235. // get the element
  236. CComQIPtr<IXMLDOMElement> spEl;
  237. spEl = m_sp;
  238. // check if we have the interface pointer to forward the call
  239. sc = ScCheckPointers(spEl, E_NOINTERFACE);
  240. if (sc)
  241. sc.Throw();
  242. CComBSTR bstrPropertyName (strPropertyName);
  243. CComVariant varPropertyValue(bstrPropertyValue);
  244. sc = spEl->setAttribute(bstrPropertyName, varPropertyValue);
  245. if(sc)
  246. sc.Throw();
  247. }
  248. /***************************************************************************\
  249. *
  250. * METHOD: CXMLElement::getAttribute
  251. *
  252. * PURPOSE: gets attribute from element
  253. *
  254. * PARAMETERS:
  255. * const CStr &strPropertyName - [in] attribute name
  256. * CComBSTR &bstrPropertyValue - [out] attribute value
  257. *
  258. * RETURNS:
  259. * void
  260. *
  261. \***************************************************************************/
  262. bool
  263. CXMLElement::getAttribute(const CStr &strPropertyName, CComBSTR &bstrPropertyValue)
  264. {
  265. DECLARE_SC(sc, TEXT("CXMLElement::getAttribute"));
  266. // get the element
  267. CComQIPtr<IXMLDOMElement> spEl;
  268. spEl = m_sp;
  269. // check if we have the interface pointer to forward the call
  270. sc = ScCheckPointers(spEl, E_NOINTERFACE);
  271. if (sc)
  272. sc.Throw();
  273. CComBSTR bstrPropertyName (strPropertyName);
  274. CComVariant varPropertyValue;
  275. sc = spEl->getAttribute(bstrPropertyName, &varPropertyValue);
  276. if(sc) // no resuls cannot be read either
  277. sc.Throw();
  278. if (sc.ToHr() == S_FALSE)
  279. return false;
  280. // check if we've got the expected value type
  281. if ( varPropertyValue.vt != VT_BSTR )
  282. sc.Throw( E_UNEXPECTED );
  283. bstrPropertyValue = varPropertyValue.bstrVal;
  284. return true;
  285. }
  286. /***************************************************************************\
  287. *
  288. * METHOD: CXMLElement::removeAttribute
  289. *
  290. * PURPOSE: removes attribute from the elament
  291. *
  292. * PARAMETERS:
  293. * const CStr &strPropertyName - [in] atrtibute name
  294. *
  295. * RETURNS:
  296. * void
  297. *
  298. \***************************************************************************/
  299. void
  300. CXMLElement::removeAttribute(const CStr &strPropertyName)
  301. {
  302. DECLARE_SC(sc, TEXT("CXMLElement::removeAttribute"));
  303. // get the element
  304. CComQIPtr<IXMLDOMElement> spEl;
  305. spEl = m_sp;
  306. // check if we have the interface pointer to forward the call
  307. sc = ScCheckPointers(spEl, E_NOINTERFACE);
  308. if (sc)
  309. sc.Throw();
  310. CComBSTR bstrPropertyName (strPropertyName);
  311. sc = spEl->removeAttribute(bstrPropertyName);
  312. if(sc)
  313. sc.Throw();
  314. }
  315. /***************************************************************************\
  316. *
  317. * METHOD: CXMLElement::get_children
  318. *
  319. * PURPOSE: returns collection of children which belong to element
  320. *
  321. * PARAMETERS:
  322. * CXMLElementCollection *pChildren - [out] collection
  323. *
  324. * RETURNS:
  325. * void
  326. *
  327. \***************************************************************************/
  328. void
  329. CXMLElement::get_children(CXMLElementCollection *pChildren)
  330. {
  331. DECLARE_SC(sc, TEXT("CXMLElement::get_children"));
  332. sc = ScCheckPointers(pChildren);
  333. if (sc)
  334. sc.Throw();
  335. // init ret value
  336. *pChildren = CXMLElementCollection();
  337. // check if we have the interface pointer to forward the call
  338. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  339. if (sc)
  340. sc.Throw();
  341. CComPtr<IXMLDOMNodeList> spChildren;
  342. sc = m_sp->get_childNodes(&spChildren);
  343. if(sc)
  344. sc.Throw();
  345. // return the object
  346. *pChildren = CXMLElementCollection(spChildren);
  347. }
  348. /***************************************************************************\
  349. *
  350. * METHOD: CXMLElement::get_type
  351. *
  352. * PURPOSE: returns the type of the element
  353. *
  354. * PARAMETERS:
  355. * long *plType - [out] element's type
  356. *
  357. * RETURNS:
  358. * void
  359. *
  360. \***************************************************************************/
  361. void
  362. CXMLElement::get_type(DOMNodeType *pType)
  363. {
  364. DECLARE_SC(sc, TEXT("CXMLElement::get_type"));
  365. // check if we have the interface pointer to forward the call
  366. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  367. if (sc)
  368. sc.Throw();
  369. sc = m_sp->get_nodeType(pType);
  370. if(sc)
  371. sc.Throw();
  372. }
  373. /***************************************************************************\
  374. *
  375. * METHOD: CXMLElement::get_text
  376. *
  377. * PURPOSE: retrieves contents of the text element
  378. * NOTE: it only works for text elements!
  379. *
  380. * PARAMETERS:
  381. * CComBSTR &bstrContent - storage for resulting string
  382. *
  383. * RETURNS:
  384. * void
  385. *
  386. \***************************************************************************/
  387. void
  388. CXMLElement::get_text(CComBSTR &bstrContent)
  389. {
  390. DECLARE_SC(sc, TEXT("CXMLElement::get_text"));
  391. // check if we have the interface pointer to forward the call
  392. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  393. if (sc)
  394. sc.Throw();
  395. bstrContent.Empty();
  396. sc = m_sp->get_text(&bstrContent);
  397. if(sc)
  398. sc.Throw();
  399. }
  400. /***************************************************************************\
  401. *
  402. * METHOD: CXMLElement::addChild
  403. *
  404. * PURPOSE: adds the new child element to current element
  405. *
  406. * PARAMETERS:
  407. * CXMLElement& rChildElem [in] element to become a child
  408. * long lIndex [in] index for new element
  409. *
  410. * RETURNS:
  411. * void
  412. *
  413. \***************************************************************************/
  414. void
  415. CXMLElement::addChild(CXMLElement& rChildElem)
  416. {
  417. DECLARE_SC(sc, TEXT("CXMLElement::addChild"));
  418. // check if we have the interface pointer to forward the call
  419. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  420. if (sc)
  421. sc.Throw();
  422. CComPtr<IXMLDOMNode> spCreated;
  423. sc = m_sp->appendChild(rChildElem.m_sp, &spCreated);
  424. if(sc)
  425. sc.Throw();
  426. rChildElem.m_sp = spCreated;
  427. }
  428. /***************************************************************************\
  429. *
  430. * METHOD: CXMLElement::removeChild
  431. *
  432. * PURPOSE: removes child element
  433. *
  434. * PARAMETERS:
  435. * CXMLElement& rChildElem - [in] child to remove
  436. *
  437. * RETURNS:
  438. * void
  439. *
  440. \***************************************************************************/
  441. void
  442. CXMLElement::removeChild(CXMLElement& rChildElem)
  443. {
  444. DECLARE_SC(sc, TEXT("CXMLElement::removeChild"));
  445. // check if we have the interface pointer to forward the call
  446. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  447. if (sc)
  448. sc.Throw();
  449. CComPtr<IXMLDOMNode> spRemoved;
  450. sc = m_sp->removeChild(rChildElem.m_sp, &spRemoved);
  451. if(sc)
  452. sc.Throw();
  453. rChildElem.m_sp = spRemoved;
  454. }
  455. /***************************************************************************\
  456. *
  457. * METHOD: CXMLElement::GetTextIndent
  458. *
  459. * PURPOSE: returns indentation for the child element \ closing tag
  460. * Indentation is calulated by element depth in the tree
  461. *
  462. * PARAMETERS:
  463. * CComBSTR& bstrIndent [out] string conatining required indent
  464. * bool bForAChild [in] if the indent is for a child
  465. *
  466. * RETURNS:
  467. * SC - result code
  468. *
  469. \***************************************************************************/
  470. bool CXMLElement::GetTextIndent(CComBSTR& bstrIndent, bool bForAChild)
  471. {
  472. DECLARE_SC(sc, TEXT("CXMLElement::GetTextIndent"));
  473. const size_t nIdentStep = 2;
  474. // check if we have the interface pointer to forward the call
  475. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  476. if (sc)
  477. sc.Throw();
  478. // initialize the result
  479. bstrIndent.Empty();
  480. CComPtr<IXMLDOMNode> spNext;
  481. CComPtr<IXMLDOMNode> spParent;
  482. // calculate node depth
  483. int nNodeDepth = 0;
  484. spNext = m_sp;
  485. while ( S_OK == spNext->get_parentNode(&spParent) && spParent != NULL)
  486. {
  487. ++nNodeDepth;
  488. spNext = spParent;
  489. spParent.Release();
  490. }
  491. // no indent for topmost things
  492. if (nNodeDepth < 1)
  493. return false;
  494. // do not count root node - not ours
  495. --nNodeDepth;
  496. // child is indented more
  497. if (bForAChild)
  498. ++nNodeDepth;
  499. if (bForAChild)
  500. {
  501. // it may already have indent for the closing tag (if its' not the first element)
  502. // than we just need a little increase
  503. // see if the we have child elements added;
  504. CXMLElementCollection colChildren;
  505. get_children(&colChildren);
  506. // count all elements
  507. long nChildren = 0;
  508. if (!colChildren.IsNull())
  509. colChildren.get_count(&nChildren);
  510. // we will have at least 2 for normal elements
  511. // since the indent (text element) will be added prior to the first one
  512. if (nChildren > 1)
  513. {
  514. bstrIndent = std::wstring( nIdentStep, ' ' ).c_str();
  515. return true;
  516. }
  517. }
  518. std::wstring strResult(nIdentStep * (nNodeDepth) + 1/*for new line*/, ' ');
  519. // new line for each (1st) new item
  520. strResult[0] = '\n';
  521. bstrIndent = strResult.c_str();
  522. return true;
  523. }
  524. /***************************************************************************\
  525. *
  526. * METHOD: CXMLElement::replaceChild
  527. *
  528. * PURPOSE: replaces the element with the new on
  529. *
  530. * PARAMETERS:
  531. * CXMLElement& rNewChildElem [in] new element
  532. * CXMLElement& rOldChildElem [in/out] old element
  533. *
  534. * RETURNS:
  535. * void
  536. *
  537. \***************************************************************************/
  538. void CXMLElement::replaceChild(CXMLElement& rNewChildElem, CXMLElement& rOldChildElem)
  539. {
  540. DECLARE_SC(sc, TEXT("CXMLElement::replaceChild"));
  541. // check if we have the interface pointer to forward the call
  542. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  543. if (sc)
  544. sc.Throw();
  545. // forward to MSXML
  546. CComPtr<IXMLDOMNode> spRemoved;
  547. sc = m_sp->replaceChild(rNewChildElem.m_sp, rOldChildElem.m_sp, &spRemoved);
  548. if (sc)
  549. sc.Throw();
  550. rOldChildElem = CXMLElement(spRemoved);
  551. }
  552. /***************************************************************************\
  553. *
  554. * METHOD: CXMLElement::getNextSibling
  555. *
  556. * PURPOSE: returns sibling to this element
  557. *
  558. * PARAMETERS:
  559. * CXMLElement * pNext [out] sibling element
  560. *
  561. * RETURNS:
  562. * SC - result code
  563. *
  564. \***************************************************************************/
  565. void CXMLElement::getNextSibling(CXMLElement * pNext)
  566. {
  567. DECLARE_SC(sc, TEXT("CXMLElement::getNextSibling"));
  568. // parameter check;
  569. sc = ScCheckPointers(pNext);
  570. if (sc)
  571. sc.Throw();
  572. // initialization
  573. *pNext = CXMLElement();
  574. // check if we have the interface pointer to forward the call
  575. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  576. if (sc)
  577. sc.Throw();
  578. // forward to MSXML
  579. CComPtr<IXMLDOMNode> spNext;
  580. sc = m_sp->get_nextSibling(&spNext);
  581. if (sc)
  582. sc.Throw();
  583. *pNext = CXMLElement(spNext);
  584. }
  585. /***************************************************************************\
  586. *
  587. * METHOD: CXMLElement::getChildrenByName
  588. *
  589. * PURPOSE: returns children by specified name
  590. *
  591. * PARAMETERS:
  592. * LPTCSTR szTagName - [in] tag name
  593. * CXMLElementCollection *pChildren - [out] collection
  594. *
  595. * RETURNS:
  596. * void
  597. *
  598. \***************************************************************************/
  599. void CXMLElement::getChildrenByName(LPCTSTR szTagName, CXMLElementCollection *pChildren)
  600. {
  601. DECLARE_SC(sc, TEXT("CXMLElement::getChildrenByName"));
  602. sc = ScCheckPointers(pChildren);
  603. if (sc)
  604. sc.Throw();
  605. // init ret value
  606. *pChildren = CXMLElementCollection();
  607. // check if we have the interface pointer to forward the call
  608. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  609. if (sc)
  610. sc.Throw();
  611. CComPtr<IXMLDOMNodeList> spChildren;
  612. sc = m_sp->selectNodes(CComBSTR(szTagName), &spChildren);
  613. if(sc)
  614. sc.Throw();
  615. // return the object
  616. *pChildren = CXMLElementCollection(spChildren);
  617. }
  618. /*+-------------------------------------------------------------------------*
  619. *
  620. * CXMLElement::put_text
  621. *
  622. * PURPOSE: Per IXMLDOMNode
  623. *
  624. * PARAMETERS:
  625. * BSTR bstrValue :
  626. *
  627. * RETURNS:
  628. * void
  629. *
  630. *+-------------------------------------------------------------------------*/
  631. void
  632. CXMLElement::put_text(BSTR bstrValue)
  633. {
  634. DECLARE_SC(sc, TEXT("CXMLElement::put_text"));
  635. // check if we have the interface pointer to forward the call
  636. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  637. if (sc)
  638. sc.Throw();
  639. sc = m_sp->put_text(bstrValue);
  640. if(sc)
  641. sc.Throw();
  642. }
  643. //############################################################################
  644. //############################################################################
  645. //
  646. // Implementation of class CXMLDocument
  647. //
  648. // These are documented in the Platform SDK.
  649. //############################################################################
  650. //############################################################################
  651. /***************************************************************************\
  652. *
  653. * METHOD: CXMLDocument::get_root
  654. *
  655. * PURPOSE: returns root element of the document
  656. *
  657. * PARAMETERS:
  658. * CXMLElement *pElem
  659. *
  660. * RETURNS:
  661. * void
  662. *
  663. \***************************************************************************/
  664. void
  665. CXMLDocument::get_root(CXMLElement *pElem)
  666. {
  667. DECLARE_SC(sc, TEXT("CXMLDocument::get_root"));
  668. // parameter check
  669. sc = ScCheckPointers(pElem);
  670. if (sc)
  671. sc.Throw();
  672. // init ret value
  673. *pElem = CXMLElement();
  674. // check if we have the interface pointer to forward the call
  675. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  676. if (sc)
  677. sc.Throw();
  678. CComPtr<IXMLDOMElement> spElem;
  679. sc = m_sp->get_documentElement(&spElem);
  680. if(sc)
  681. sc.Throw();
  682. *pElem = CXMLElement(spElem);
  683. }
  684. /***************************************************************************\
  685. *
  686. * METHOD: CXMLDocument::createElement
  687. *
  688. * PURPOSE: creates new element in XML document
  689. *
  690. * PARAMETERS:
  691. * NODE_TYPE type - type of the element requested
  692. * CIXMLElement *pElem - resulting element
  693. *
  694. * RETURNS:
  695. * void
  696. *
  697. \***************************************************************************/
  698. void
  699. CXMLDocument::createElement(DOMNodeType type, BSTR bstrTag, CXMLElement *pElem)
  700. {
  701. DECLARE_SC(sc, TEXT("CXMLDocument::createElement"));
  702. // parameter check
  703. sc = ScCheckPointers(pElem);
  704. if (sc)
  705. sc.Throw();
  706. // init ret val
  707. *pElem = CXMLElement();
  708. // check if we have the interface pointer to forward the call
  709. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  710. if (sc)
  711. sc.Throw();
  712. if (type == NODE_ELEMENT)
  713. {
  714. CComPtr<IXMLDOMElement> spElem;
  715. sc = m_sp->createElement(bstrTag, &spElem);
  716. if(sc)
  717. sc.Throw();
  718. *pElem = CXMLElement(spElem);
  719. }
  720. else if (type == NODE_TEXT)
  721. {
  722. CComPtr<IXMLDOMText> spText;
  723. sc = m_sp->createTextNode(bstrTag, &spText);
  724. if(sc)
  725. sc.Throw();
  726. *pElem = CXMLElement(spText);
  727. }
  728. else
  729. {
  730. sc.Throw(E_UNEXPECTED);
  731. }
  732. }
  733. /***************************************************************************\
  734. *
  735. * METHOD: CXMLDocument::CreateBinaryStorage
  736. *
  737. * PURPOSE: Creates XML element to be used for subsequent persist operations
  738. * the object informs Persistor if it wants to be saved as binary data.
  739. * If so, only reference will be saved in original place of the object
  740. *
  741. * PARAMETERS:
  742. * const CStr &strElementType - type of the element
  743. * LPCTSTR szElementName - name of the element
  744. *
  745. * RETURNS:
  746. *
  747. \***************************************************************************/
  748. void
  749. CXMLDocument::CreateBinaryStorage()
  750. {
  751. DECLARE_SC(sc, TEXT("CXMLDocument::CreateBinaryStorage"));
  752. // check if it is attachment is not a doubled
  753. if (!m_XMLElemBinaryStorage.IsNull())
  754. sc.Throw(E_UNEXPECTED);
  755. CXMLElement elemRoot;
  756. get_root(&elemRoot);
  757. // create persistor on parent element
  758. CPersistor persistorParent(*this, elemRoot);
  759. persistorParent.SetLoading(false);
  760. CPersistor persistorStor(persistorParent, XML_TAG_BINARY_STORAGE, NULL);
  761. m_XMLElemBinaryStorage = persistorStor.GetCurrentElement();
  762. }
  763. /***************************************************************************\
  764. *
  765. * METHOD: CXMLDocument::LocateBinaryStorage
  766. *
  767. * PURPOSE: Locates XML element to be used for subsequent persist operations
  768. * the object informs Persistor if it wants to be saved as binary data.
  769. * If so, only reference will be saved in original place of the object
  770. *
  771. * PARAMETERS:
  772. * const CStr &strElementType - type of the element
  773. * LPCTSTR szElementName - name of the element
  774. *
  775. * RETURNS:
  776. *
  777. \***************************************************************************/
  778. void
  779. CXMLDocument::LocateBinaryStorage()
  780. {
  781. DECLARE_SC(sc, TEXT("CXMLDocument::LocateBinaryStorage"));
  782. // check if it is attachment is not a doubled
  783. if (!m_XMLElemBinaryStorage.IsNull())
  784. sc.Throw(E_UNEXPECTED);
  785. CXMLElement elemRoot;
  786. get_root(&elemRoot);
  787. // create persistor on parent element
  788. CPersistor persistorParent(*this, elemRoot);
  789. persistorParent.SetLoading(true);
  790. CPersistor persistorStor(persistorParent, XML_TAG_BINARY_STORAGE, NULL);
  791. // find the element
  792. m_XMLElemBinaryStorage = persistorStor.GetCurrentElement();
  793. }
  794. /***************************************************************************\
  795. *
  796. * METHOD: CXMLDocument::CommitBinaryStorage
  797. *
  798. * PURPOSE: makes binary storage the last element in the collection
  799. *
  800. * PARAMETERS:
  801. *
  802. * RETURNS:
  803. *
  804. \***************************************************************************/
  805. void
  806. CXMLDocument::CommitBinaryStorage()
  807. {
  808. DECLARE_SC(sc, TEXT("CXMLDocument::CommitBinaryStorage"));
  809. if (m_XMLElemBinaryStorage.IsNull())
  810. sc.Throw(E_UNEXPECTED);
  811. CXMLElement elemRoot;
  812. get_root(&elemRoot);
  813. // get the next siblings
  814. CXMLElement elNext;
  815. m_XMLElemBinaryStorage.getNextSibling(&elNext);
  816. // drag itself and the next element (indent text) to the end
  817. elemRoot.removeChild(m_XMLElemBinaryStorage); // remove element
  818. // the element was padded to have proper indentation - need to remove it
  819. DOMNodeType elType = NODE_INVALID;
  820. while (!elNext.IsNull() && (elNext.get_type(&elType), elType == NODE_TEXT))
  821. {
  822. CXMLElement elNext2;
  823. elNext.getNextSibling(&elNext2);
  824. elemRoot.removeChild(elNext); // remove element (that was just an indent)
  825. elNext = elNext2;
  826. }
  827. // create persistor on parent element
  828. CPersistor persistorParent(*this, elemRoot);
  829. persistorParent.SetLoading(false);
  830. // create the new binary storage
  831. CPersistor persistorStor(persistorParent, XML_TAG_BINARY_STORAGE, NULL);
  832. // replace the current element with the one which hass all the binary storage
  833. elemRoot.replaceChild(m_XMLElemBinaryStorage, persistorStor.GetCurrentElement());
  834. m_XMLElemBinaryStorage = NULL;
  835. }
  836. /***************************************************************************\
  837. *
  838. * METHOD: CXMLDocument::ScCoCreate
  839. *
  840. * PURPOSE: (co)creates new xml document. puts charset and version
  841. *
  842. * PARAMETERS:
  843. * LPCTSTR lpstrCharSet - charset (NULL - use default)
  844. * CXMLDocument& doc - created document
  845. *
  846. * RETURNS:
  847. * SC - result code
  848. *
  849. \***************************************************************************/
  850. SC CXMLDocument::ScCoCreate(bool bPutHeader)
  851. {
  852. DECLARE_SC(sc, TEXT("CXMLDocument::ScCoCreate"));
  853. // cannot use this on co-created doc!
  854. if (m_sp)
  855. return sc = E_UNEXPECTED;
  856. // Create an empty XML document
  857. sc = ::CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER,
  858. IID_IXMLDOMDocument, (void**)&m_sp);
  859. if(sc)
  860. return sc;
  861. m_sp->put_preserveWhiteSpace(-1);
  862. try
  863. {
  864. CXMLElement elemDoc = m_sp;
  865. // put the document version
  866. if (bPutHeader)
  867. {
  868. // valid document must have a top element - add the dummy one
  869. WCHAR szVersion[] = L"<?xml version=\"1.0\"?>\n<DUMMY/>";
  870. // load
  871. sc = ScLoad(szVersion);
  872. if (sc)
  873. return sc;
  874. // we can now strip the dummy el.
  875. CXMLElement elemRoot;
  876. get_root(&elemRoot);
  877. elemDoc.removeChild(elemRoot);
  878. if (sc)
  879. return sc;
  880. }
  881. }
  882. catch(SC sc_thrown)
  883. {
  884. return sc = sc_thrown;
  885. }
  886. return sc;
  887. }
  888. /***************************************************************************\
  889. *
  890. * METHOD: CXMLDocument::ScLoad
  891. *
  892. * PURPOSE: lods XML document from given IStream
  893. *
  894. * PARAMETERS:
  895. * IStream *pStream [in] - stream to load from
  896. * bool bSilentOnErrors [in] - do not trace if open fails
  897. *
  898. * RETURNS:
  899. * SC - result code
  900. *
  901. \***************************************************************************/
  902. SC CXMLDocument::ScLoad(IStream *pStream, bool bSilentOnErrors /*= false*/ )
  903. {
  904. DECLARE_SC(sc, TEXT("CXMLDocument::ScLoad"));
  905. // check params
  906. sc = ScCheckPointers(pStream);
  907. if (sc)
  908. return sc;
  909. // get the interface
  910. IPersistStreamInitPtr spPersistStream = m_sp;
  911. sc = ScCheckPointers(spPersistStream, E_UNEXPECTED);
  912. if (sc)
  913. return sc;
  914. // load (do not trace the error - it may be that the old console
  915. // is attempted to load - mmc will revert to old format after this failure)
  916. SC sc_no_trace = spPersistStream->Load(pStream);
  917. if ( sc_no_trace )
  918. {
  919. if ( !bSilentOnErrors )
  920. sc = sc_no_trace;
  921. return sc_no_trace;
  922. }
  923. return sc;
  924. }
  925. /***************************************************************************\
  926. *
  927. * METHOD: CXMLDocument::ScLoad
  928. *
  929. * PURPOSE: lods XML document from given string
  930. *
  931. * PARAMETERS:
  932. * LPCWSTR strSource [in] - string to load from
  933. *
  934. * RETURNS:
  935. * SC - result code
  936. *
  937. \***************************************************************************/
  938. SC CXMLDocument::ScLoad(LPCWSTR strSource)
  939. {
  940. DECLARE_SC(sc, TEXT("CXMLDocument::ScLoad"));
  941. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  942. if (sc)
  943. return sc;
  944. CComBSTR bstrSource(strSource);
  945. VARIANT_BOOL bOK;
  946. sc = m_sp->loadXML(bstrSource, &bOK);
  947. if (sc)
  948. return sc;
  949. if (bOK != VARIANT_TRUE)
  950. return sc = E_FAIL;
  951. return sc;
  952. }
  953. /***************************************************************************\
  954. *
  955. * METHOD: CXMLDocument::ScSaveToFile
  956. *
  957. * PURPOSE: saves xml document to given stream
  958. *
  959. * PARAMETERS:
  960. * LPCTSTR lpcstrFileName - [in] file to save to
  961. *
  962. * RETURNS:
  963. * SC - result code
  964. *
  965. \***************************************************************************/
  966. SC CXMLDocument::ScSaveToFile(LPCTSTR lpcstrFileName)
  967. {
  968. DECLARE_SC(sc, TEXT("CXMLDocument::ScSaveToFile"));
  969. // check params
  970. sc = ScCheckPointers(lpcstrFileName);
  971. if (sc)
  972. return sc;
  973. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  974. if (sc)
  975. sc.Throw();
  976. CComVariant var(lpcstrFileName);
  977. sc = m_sp->save(var);
  978. if (sc)
  979. return sc;
  980. return sc;
  981. }
  982. /***************************************************************************\
  983. *
  984. * METHOD: CXMLDocument::ScSave
  985. *
  986. * PURPOSE: saves xml document to given string
  987. *
  988. * PARAMETERS:
  989. * CComBSTR &bstrResult - [out] string
  990. *
  991. * RETURNS:
  992. * SC - result code
  993. *
  994. \***************************************************************************/
  995. SC CXMLDocument::ScSave(CComBSTR &bstrResult)
  996. {
  997. DECLARE_SC(sc, TEXT("CXMLDocument::ScSave"));
  998. sc = ScCheckPointers(m_sp, E_NOINTERFACE);
  999. if (sc)
  1000. sc.Throw();
  1001. bstrResult.Empty();
  1002. sc = m_sp->get_xml(&bstrResult);
  1003. if (sc)
  1004. return sc;
  1005. return sc;
  1006. }
  1007. /***************************************************************************\
  1008. *
  1009. * METHOD: CXMLObject::ScSaveToString
  1010. *
  1011. * PURPOSE: saves XML object to string (in raw UNICODE or UTF-8 fromat)
  1012. *
  1013. * PARAMETERS:
  1014. * tstring *pString - resulting string
  1015. * bool bPutHeader - whether to put xml header info
  1016. *
  1017. * RETURNS:
  1018. * SC - result code
  1019. *
  1020. \***************************************************************************/
  1021. SC CXMLObject::ScSaveToString(std::wstring *pString, bool bPutHeader /*= false*/)
  1022. {
  1023. DECLARE_SC(sc, TEXT("CXMLObject::ScSaveToString"));
  1024. // check parameter
  1025. sc = ScCheckPointers(pString);
  1026. if (sc)
  1027. return sc;
  1028. //initialize output
  1029. pString->erase();
  1030. // Create an empty XML document
  1031. CXMLDocument xmlDocument;
  1032. sc = xmlDocument.ScCoCreate(bPutHeader);
  1033. if(sc)
  1034. return sc;
  1035. // persist the contents
  1036. try
  1037. {
  1038. CXMLElement elemDoc = xmlDocument;
  1039. CPersistor persistor(xmlDocument, elemDoc);
  1040. persistor.SetLoading(false);
  1041. persistor.EnableValueSplit(false); // disable split (no string table, no binary storage)
  1042. persistor.Persist(*this);
  1043. }
  1044. catch(SC sc_thrown)
  1045. {
  1046. return sc = sc_thrown;
  1047. }
  1048. // dump it to the string
  1049. sc = ScSaveXMLDocumentToString(xmlDocument, *pString);
  1050. if (sc)
  1051. return sc;
  1052. return sc;
  1053. }
  1054. /***************************************************************************\
  1055. *
  1056. * METHOD: CXMLObject::ScSaveToDocument
  1057. *
  1058. * PURPOSE: saves XML object to file as XML document
  1059. *
  1060. * PARAMETERS:
  1061. * CXMLDocument& xmlDocument - xmlDocument to save to
  1062. *
  1063. * RETURNS:
  1064. * SC - result code
  1065. *
  1066. \***************************************************************************/
  1067. SC CXMLObject::ScSaveToDocument( CXMLDocument& xmlDocument )
  1068. {
  1069. DECLARE_SC(sc, TEXT("CXMLObject::ScSaveToDocument"));
  1070. // Create an empty XML document
  1071. sc = xmlDocument.ScCoCreate(true/*bPutHeader*/);
  1072. if(sc)
  1073. return sc;
  1074. // persist the contents
  1075. try
  1076. {
  1077. CXMLElement elemDoc = xmlDocument;
  1078. CPersistor persistor(xmlDocument, elemDoc);
  1079. persistor.SetLoading(false);
  1080. persistor.Persist(*this);
  1081. }
  1082. catch(SC sc_thrown)
  1083. {
  1084. return sc = sc_thrown;
  1085. }
  1086. return sc;
  1087. }
  1088. /***************************************************************************\
  1089. *
  1090. * METHOD: CXMLObject::ScLoadFromString
  1091. *
  1092. * PURPOSE: loads XML object from data stored in string
  1093. *
  1094. * PARAMETERS:
  1095. * LPCTSTR lpcwstrSource
  1096. *
  1097. * RETURNS:
  1098. * SC - result code
  1099. *
  1100. \***************************************************************************/
  1101. SC CXMLObject::ScLoadFromString(LPCWSTR lpcwstrSource, PersistorMode mode)
  1102. {
  1103. DECLARE_SC(sc, TEXT("CXMLObject::ScLoadFromString"));
  1104. // check parameter
  1105. sc = ScCheckPointers(lpcwstrSource);
  1106. if (sc)
  1107. return sc;
  1108. // Create an empty XML document
  1109. CXMLDocument xmlDocument;
  1110. sc = xmlDocument.ScCoCreate(false/*bPutHeader*/);
  1111. if(sc)
  1112. return sc;
  1113. sc = xmlDocument.ScLoad(lpcwstrSource);
  1114. if(sc)
  1115. return sc;
  1116. // persist the contents
  1117. try
  1118. {
  1119. CPersistor persistor(xmlDocument, CXMLElement(xmlDocument));
  1120. persistor.SetLoading(true);
  1121. persistor.SetMode(mode);
  1122. persistor.Persist(*this);
  1123. }
  1124. catch(SC sc_thrown)
  1125. {
  1126. return sc = sc_thrown;
  1127. }
  1128. return sc;
  1129. }
  1130. /***************************************************************************\
  1131. *
  1132. * METHOD: CXMLObject::ScLoadFromDocument
  1133. *
  1134. * PURPOSE: loads XML object from xml document saved as file
  1135. *
  1136. * PARAMETERS:
  1137. * CXMLDocument& xmlDocument - xml document to read from
  1138. *
  1139. * RETURNS:
  1140. * SC - result code
  1141. *
  1142. \***************************************************************************/
  1143. SC CXMLObject::ScLoadFromDocument( CXMLDocument& xmlDocument )
  1144. {
  1145. DECLARE_SC(sc, TEXT("CXMLObject::ScLoadFromDocument"));
  1146. // persist the contents
  1147. try
  1148. {
  1149. CPersistor persistor(xmlDocument, CXMLElement(xmlDocument));
  1150. persistor.SetLoading(true);
  1151. persistor.Persist(*this);
  1152. }
  1153. catch(SC sc_thrown)
  1154. {
  1155. return sc = sc_thrown;
  1156. }
  1157. return sc;
  1158. }
  1159. //############################################################################
  1160. //############################################################################
  1161. //
  1162. // Implementation of class CPersistor
  1163. //
  1164. //############################################################################
  1165. //############################################################################
  1166. /***************************************************************************\
  1167. *
  1168. * METHOD: CPersistor::CommonConstruct
  1169. *
  1170. * PURPOSE: common constructor, not to be used from outside.
  1171. * provided as common place for member initialization
  1172. * all the constructors should call it prior to doing anything specific.
  1173. *
  1174. * PARAMETERS:
  1175. *
  1176. * RETURNS:
  1177. *
  1178. \***************************************************************************/
  1179. void CPersistor::CommonConstruct()
  1180. {
  1181. // smart pointers are initialized by their constructors
  1182. ASSERT (m_XMLElemCurrent.IsNull());
  1183. ASSERT (m_XMLDocument.IsNull());
  1184. m_bIsLoading = false;
  1185. m_bLockedOnChild = false;
  1186. m_dwModeFlags = persistorModeDefault; // the default mode.
  1187. }
  1188. /***************************************************************************\
  1189. *
  1190. * METHOD: CPersistor::BecomeAChildOf
  1191. *
  1192. * PURPOSE: Initialization (second part of construction) of a child persistor
  1193. * All members, inherited from the parent persistor, are initialized here
  1194. *
  1195. * PARAMETERS:
  1196. * CPersistor &persistorParent - [in] (to be) parent persistor of current persistor
  1197. * CXMLElement elem - [in] element on which current persistor is based
  1198. *
  1199. * RETURNS:
  1200. * void
  1201. *
  1202. \***************************************************************************/
  1203. void CPersistor::BecomeAChildOf(CPersistor &persistorParent, CXMLElement elem)
  1204. {
  1205. DECLARE_SC(sc, TEXT("CPersistor::BecomeAChildOf"));
  1206. // assign the element
  1207. m_XMLElemCurrent = elem;
  1208. // we do not inherit m_bLockedOnChild from parent!!!
  1209. m_bLockedOnChild = false;
  1210. // inherited members are copied here
  1211. m_XMLDocument = persistorParent.GetDocument();
  1212. m_bIsLoading = persistorParent.m_bIsLoading;
  1213. m_dwModeFlags = persistorParent.m_dwModeFlags;
  1214. }
  1215. /***************************************************************************\
  1216. *
  1217. * METHOD: CPersistor::CPersistor
  1218. *
  1219. * PURPOSE: construct a persistor from a parent persistor.
  1220. * this creates a new XML element with the given name,
  1221. * and everything persisted to the new persistor
  1222. * is persisted under this element.
  1223. *
  1224. * PARAMETERS:
  1225. * CPersistor &persistorParent - parent persistor
  1226. * const CStr &strElementType - element type [element tag in XML file]
  1227. * LPCTSTR szElementName - "Name" attribute [optional]
  1228. *
  1229. \***************************************************************************/
  1230. CPersistor::CPersistor(CPersistor &persistorParent, const CStr &strElementType, LPCTSTR szElementName /*= NULL*/)
  1231. {
  1232. // initialize using common constructor
  1233. CommonConstruct();
  1234. CXMLElement elem;
  1235. if (persistorParent.IsStoring())
  1236. elem = persistorParent.AddElement(strElementType, szElementName);
  1237. else if (persistorParent.m_bLockedOnChild)
  1238. {
  1239. // if we already have the child located - just take it from parent!
  1240. // plus recheck to see it XML document actually has such an element
  1241. elem = persistorParent.CheckCurrentElement(strElementType, szElementName);
  1242. }
  1243. else
  1244. elem = persistorParent.GetElement(strElementType, szElementName);
  1245. // construct child persistor on elem
  1246. BecomeAChildOf(persistorParent, elem);
  1247. }
  1248. /***************************************************************************\
  1249. *
  1250. * METHOD: CPersistor::CPersistor
  1251. *
  1252. * PURPOSE: creates new persistor for XML document
  1253. *
  1254. * PARAMETERS:
  1255. * IXMLDocument * pDocument - document
  1256. * CXMLElement &rElemCurrent - root element for persistor
  1257. *
  1258. \***************************************************************************/
  1259. CPersistor::CPersistor(CXMLDocument &document, CXMLElement& rElemCurrent)
  1260. {
  1261. // initialize using common constructor
  1262. CommonConstruct();
  1263. m_XMLDocument = document;
  1264. m_XMLElemCurrent = rElemCurrent;
  1265. }
  1266. /***************************************************************************\
  1267. *
  1268. * METHOD: CPersistor::CPersistor
  1269. *
  1270. * PURPOSE: Creates new persistor based on parent an supplied element
  1271. *
  1272. * PARAMETERS:
  1273. * const CPersistor &other - parent persistor
  1274. * CXMLElement &rElemCurrent - root element for persistor
  1275. * bool bLockedOnChild - if new persistor should be a fake parent
  1276. * to be used to create persistors
  1277. *
  1278. \***************************************************************************/
  1279. CPersistor::CPersistor(CPersistor &other, CXMLElement& rElemCurrent, bool bLockedOnChild /*= false*/)
  1280. {
  1281. // initialize using common constructor
  1282. CommonConstruct();
  1283. // inherit...
  1284. BecomeAChildOf(other, rElemCurrent);
  1285. // this prevents locating the element on load (assuming the persistor is on element already)
  1286. // used to load items for collections
  1287. m_bLockedOnChild = bLockedOnChild;
  1288. }
  1289. /***************************************************************************\
  1290. *
  1291. * METHOD: CPersistor::Persist
  1292. *
  1293. * PURPOSE: persists XML object
  1294. *
  1295. * PARAMETERS:
  1296. * LPCTSTR lpstrName - "Name" attribute for element [optional = NULL]
  1297. * CXMLObject & object - object to persist
  1298. *
  1299. * RETURNS:
  1300. * void
  1301. *
  1302. \***************************************************************************/
  1303. void
  1304. CPersistor::Persist(CXMLObject & object, LPCTSTR lpstrName /*= NULL*/)
  1305. {
  1306. DECLARE_SC(sc, TEXT("CPersistor::Persist"));
  1307. // persist w/o splitting if saved to string
  1308. if (!object.UsesBinaryStorage() || !FEnableValueSplit())
  1309. {
  1310. // ordinary object;
  1311. CPersistor persistorNew(*this,object.GetXMLType(),lpstrName);
  1312. object.Persist(persistorNew);
  1313. }
  1314. else
  1315. {
  1316. // this element should be split in 2 places
  1317. // see comment "CONCEPT OF BINARY STORAGE" in "xmbase.h"
  1318. CXMLElement elemBinStorage = GetDocument().GetBinaryStorage();
  1319. if (elemBinStorage.IsNull())
  1320. sc.Throw(E_UNEXPECTED);
  1321. // get elements enumeration in binaries
  1322. CXMLElementCollection colChildren;
  1323. elemBinStorage.getChildrenByName(XML_TAG_BINARY, &colChildren);
  1324. long nChildren = 0;
  1325. if (!colChildren.IsNull())
  1326. colChildren.get_count(&nChildren);
  1327. int iReffIndex = nChildren;
  1328. // save reference instead of contents
  1329. CPersistor persistorNew(*this, object.GetXMLType(), lpstrName);
  1330. persistorNew.PersistAttribute(XML_ATTR_BINARY_REF_INDEX, iReffIndex);
  1331. // persist the object
  1332. CPersistor persistorBinaries(*this, elemBinStorage);
  1333. // locate/create the element [cannot reuse constructor since we have collection here]
  1334. CXMLElement elem;
  1335. if (IsLoading())
  1336. {
  1337. // locate the element
  1338. elem = persistorBinaries.GetElement(XML_TAG_BINARY, object.GetBinaryEntryName(), iReffIndex );
  1339. }
  1340. else
  1341. {
  1342. // storing - just create sub-persistor
  1343. elem = persistorBinaries.AddElement(XML_TAG_BINARY, object.GetBinaryEntryName());
  1344. }
  1345. CPersistor persistorThisBinary(persistorBinaries, elem);
  1346. // start from new line
  1347. if (IsStoring())
  1348. {
  1349. persistorThisBinary.AddTextElement(CComBSTR(L"\n"));
  1350. }
  1351. object.Persist(persistorThisBinary);
  1352. // new line after contents
  1353. if (IsStoring())
  1354. {
  1355. CComBSTR bstrIndent;
  1356. if (persistorThisBinary.GetCurrentElement().GetTextIndent(bstrIndent, false /*bForAChild*/))
  1357. persistorThisBinary.AddTextElement(bstrIndent);
  1358. }
  1359. }
  1360. }
  1361. /***************************************************************************\
  1362. *
  1363. * METHOD: CPersistor::Persist
  1364. *
  1365. * PURPOSE: persists XML value as stand-alone object
  1366. *
  1367. * PARAMETERS:
  1368. * CXMLValue xval - value to persist
  1369. * LPCTSTR name - "Name" attribute for element [optional = NULL]
  1370. *
  1371. * RETURNS:
  1372. * void
  1373. *
  1374. \***************************************************************************/
  1375. void
  1376. CPersistor::Persist(CXMLValue xval, LPCTSTR name /*= NULL*/)
  1377. {
  1378. if (xval.UsesBinaryStorage())
  1379. {
  1380. // binary value to be saved to Binary storage.
  1381. // see comment "CONCEPT OF BINARY STORAGE" in "xmbase.h"
  1382. // wrap it into special object, which handles it and pass to Perist method
  1383. CXMLBinaryValue val(xval);
  1384. Persist(val, name);
  1385. }
  1386. else
  1387. {
  1388. // standard value, persist as ordinary element
  1389. CPersistor persistorNew(*this,xval.GetTypeName(),name);
  1390. persistorNew.PersistContents(xval);
  1391. }
  1392. }
  1393. /***************************************************************************\
  1394. *
  1395. * METHOD: CPersistor::PersistAttribute
  1396. *
  1397. * PURPOSE: Persists attribute
  1398. *
  1399. * PARAMETERS:
  1400. * LPCTSTR name - Name of attribute
  1401. * CXMLValue xval - Value of attribute
  1402. * const XMLAttributeType type - type of attribute [ required/ optional ]
  1403. *
  1404. * RETURNS:
  1405. * void
  1406. *
  1407. \***************************************************************************/
  1408. void
  1409. CPersistor::PersistAttribute(LPCTSTR name, CXMLValue xval, const XMLAttributeType type /*= attr_required*/)
  1410. {
  1411. DECLARE_SC(sc, TEXT("CPersistor::PersistAttribute"));
  1412. if(IsLoading())
  1413. {
  1414. CComBSTR bstrPropertyValue;
  1415. bool bValueSupplied = GetCurrentElement().getAttribute(name, bstrPropertyValue);
  1416. if (bValueSupplied)
  1417. {
  1418. sc = xval.ScReadFromBSTR(bstrPropertyValue);
  1419. if (sc)
  1420. sc.Throw(E_FAIL);
  1421. }
  1422. else if (type != attr_optional)
  1423. sc.Throw(E_FAIL);
  1424. }
  1425. else // IsStoring
  1426. {
  1427. CComBSTR bstr; // must be empty!
  1428. sc = xval.ScWriteToBSTR(&bstr);
  1429. if (sc)
  1430. sc.Throw();
  1431. GetCurrentElement().setAttribute(name, bstr);
  1432. }
  1433. }
  1434. /***************************************************************************\
  1435. *
  1436. * METHOD: CPersistor::PersistContents
  1437. *
  1438. * PURPOSE: perists XMLValues as a contents of xml element
  1439. * <this_element>persisted_contents</this_element>
  1440. * to be used insted of PersistAttribute where apropriate
  1441. *
  1442. * PARAMETERS:
  1443. * CXMLValue xval - value to persist as contents of the element
  1444. *
  1445. * NOTE: element cannot have both value-as-contents and sub-elements
  1446. *
  1447. * RETURNS:
  1448. * void
  1449. *
  1450. \***************************************************************************/
  1451. void
  1452. CPersistor::PersistContents(CXMLValue xval)
  1453. {
  1454. DECLARE_SC(sc, TEXT("CPersistor::PersistContents"));
  1455. if (IsStoring())
  1456. {
  1457. CComBSTR bstr; // must be empty!
  1458. sc = xval.ScWriteToBSTR(&bstr);
  1459. if (sc)
  1460. sc.Throw();
  1461. AddTextElement(bstr);
  1462. }
  1463. else
  1464. {
  1465. CComBSTR bstrPropertyValue;
  1466. GetTextElement(bstrPropertyValue);
  1467. sc = xval.ScReadFromBSTR(bstrPropertyValue);
  1468. if (sc)
  1469. sc.Throw();
  1470. }
  1471. }
  1472. /*+-------------------------------------------------------------------------*
  1473. *
  1474. * CPersistor::AddElement
  1475. *
  1476. * PURPOSE: Creates a new element below this element with the specified name.
  1477. * All persistence to the new persistor will write underneath this
  1478. * new element.
  1479. *
  1480. * PARAMETERS:
  1481. * const CStr :
  1482. * CPersistor& persistorNew :
  1483. *
  1484. * RETURNS:
  1485. * CXMLElement - created child element
  1486. *
  1487. *+-------------------------------------------------------------------------*/
  1488. CXMLElement
  1489. CPersistor::AddElement(const CStr &strElementType, LPCTSTR szElementName)
  1490. {
  1491. DECLARE_SC(sc, TEXT("CPersistor::AddElement"));
  1492. CXMLElement elem;
  1493. GetDocument().createElement(NODE_ELEMENT, CComBSTR(strElementType), &elem);
  1494. CComBSTR bstrIndent;
  1495. if (GetCurrentElement().GetTextIndent(bstrIndent, true /*bForAChild*/))
  1496. AddTextElement(bstrIndent);
  1497. GetCurrentElement().addChild(elem); // add the new element to the end.
  1498. if (szElementName)
  1499. {
  1500. CPersistor persistorNew(*this, elem);
  1501. persistorNew.SetName(szElementName);
  1502. }
  1503. // sub element was added - that means this element will have a closing tag
  1504. // add the indent for it in advance
  1505. if (GetCurrentElement().GetTextIndent(bstrIndent, false /*bForAChild*/))
  1506. AddTextElement(bstrIndent);
  1507. return elem;
  1508. }
  1509. /***************************************************************************\
  1510. *
  1511. * METHOD: CPersistor::AddTextElement
  1512. *
  1513. * PURPOSE: creates new element of type "text"
  1514. *
  1515. * PARAMETERS:
  1516. *
  1517. * RETURNS:
  1518. * CXMLElement - created child element
  1519. *
  1520. \***************************************************************************/
  1521. void
  1522. CPersistor::AddTextElement(BSTR bstrData)
  1523. {
  1524. DECLARE_SC(sc, TEXT("CPersistor::AddTextElement"));
  1525. CXMLElement elem;
  1526. GetDocument().createElement(NODE_TEXT, bstrData, &elem);
  1527. GetCurrentElement().addChild(elem); // add the new element to the end.
  1528. }
  1529. /*+-------------------------------------------------------------------------*
  1530. *
  1531. * CPersistor::GetElement
  1532. *
  1533. * PURPOSE: Retrievs child element of the current element with the specified type [and name].
  1534. * All persistence to the new persistor will read underneath this element.
  1535. *
  1536. * PARAMETERS:
  1537. * const CStr& strElementType : type name of the element
  1538. * LPCTSTR szElementName : name of the element or NULL if doesn't matter
  1539. * int iIndex : index of the element [optional = -1]
  1540. *
  1541. * RETURNS:
  1542. * CXMLElement - resulting new element
  1543. *
  1544. *+-------------------------------------------------------------------------*/
  1545. CXMLElement
  1546. CPersistor::GetElement(const CStr &strElementType, LPCTSTR szElementName, int iIndex /*= -1*/ )
  1547. {
  1548. DECLARE_SC(sc, TEXT("CPersistor::GetElement"));
  1549. CXMLElement elem;
  1550. CXMLElementCollection colChildren;
  1551. GetCurrentElement().getChildrenByName(strElementType, &colChildren);
  1552. long nChildren = 0;
  1553. if (!colChildren.IsNull())
  1554. colChildren.get_count(&nChildren);
  1555. if (nChildren == 0)
  1556. sc.Throw(E_FAIL);
  1557. long nChild = 0;
  1558. if (iIndex >= 0)
  1559. {
  1560. // limit iteration to one loop, if we have index supplied
  1561. nChild = iIndex;
  1562. nChildren = iIndex + 1;
  1563. }
  1564. for (; nChild < nChildren; nChild++)
  1565. {
  1566. CXMLElement el;
  1567. colChildren.item(nChild, &el);
  1568. if (!el.IsNull())
  1569. {
  1570. if (szElementName)
  1571. {
  1572. CPersistor temp(*this,el);
  1573. CStr strName(temp.GetName());
  1574. if (0 != strName.CompareNoCase(szElementName))
  1575. continue;
  1576. }
  1577. elem = el;
  1578. break;
  1579. }
  1580. }
  1581. if(elem.IsNull())
  1582. sc.Throw(E_FAIL);
  1583. return elem;
  1584. }
  1585. /***************************************************************************\
  1586. *
  1587. * METHOD: CPersistor::GetTextElement
  1588. *
  1589. * PURPOSE: Gets text element attached to the new element
  1590. * NOTE: returned CPersistor may have current element equal NULL -
  1591. * this should indicate to caller that the contents is empty
  1592. *
  1593. * PARAMETERS:
  1594. *
  1595. * RETURNS:
  1596. * CXMLElement - resulting new element
  1597. *
  1598. \***************************************************************************/
  1599. void
  1600. CPersistor::GetTextElement(CComBSTR &bstrData)
  1601. {
  1602. DECLARE_SC(sc, TEXT("CPersistor::GetTextElement"));
  1603. bstrData = L"";
  1604. CXMLElement elem;
  1605. CXMLElementCollection colChildren;
  1606. GetCurrentElement().get_children(&colChildren);
  1607. long nChildren = 0;
  1608. if (!colChildren.IsNull())
  1609. colChildren.get_count(&nChildren);
  1610. if (nChildren == 0)
  1611. return; // no text element means "there is no contents"
  1612. for (long nChild = 0; nChild < nChildren; nChild++)
  1613. {
  1614. CXMLElement el;
  1615. colChildren.item(nChild, &el);
  1616. if (!el.IsNull())
  1617. {
  1618. DOMNodeType lType = NODE_INVALID;
  1619. el.get_type(&lType);
  1620. if (lType == NODE_TEXT)
  1621. {
  1622. elem = el;
  1623. break;
  1624. }
  1625. }
  1626. }
  1627. if (elem.IsNull())
  1628. return;
  1629. elem.get_text(bstrData);
  1630. }
  1631. /*+-------------------------------------------------------------------------*
  1632. *
  1633. * CPersistor::HasElement
  1634. *
  1635. * PURPOSE: checks if persistor has a specified element
  1636. *
  1637. * PARAMETERS:
  1638. * const CStr& strElementType : type name of the element
  1639. * LPCTSTR szElementName : name of the element or NULL if doesn't matter
  1640. *
  1641. * RETURNS:
  1642. * bool true == requested element exist
  1643. *
  1644. *+-------------------------------------------------------------------------*/
  1645. bool
  1646. CPersistor::HasElement(const CStr &strElementType, LPCTSTR szElementName)
  1647. {
  1648. DECLARE_SC(sc, TEXT("CPersistor::HasElement"));
  1649. if(GetCurrentElement().IsNull())
  1650. sc.Throw(E_POINTER);
  1651. CXMLElementCollection colChildren;
  1652. GetCurrentElement().getChildrenByName(strElementType, &colChildren);
  1653. if (colChildren.IsNull())
  1654. return false;
  1655. long nChildren = 0;
  1656. colChildren.get_count(&nChildren);
  1657. if (nChildren == 0)
  1658. return false;
  1659. for (long nChild = 0; nChild < nChildren; nChild++)
  1660. {
  1661. CXMLElement el;
  1662. colChildren.item(nChild, &el);
  1663. if (!el.IsNull())
  1664. {
  1665. if (szElementName)
  1666. {
  1667. CPersistor temp(*this,el);
  1668. CStr strName(temp.GetName());
  1669. if (0 != strName.CompareNoCase(szElementName))
  1670. continue;
  1671. }
  1672. return true;
  1673. }
  1674. }
  1675. return false;
  1676. }
  1677. /*+-------------------------------------------------------------------------*
  1678. *
  1679. * CPersistor::CheckCurrentElement
  1680. *
  1681. * PURPOSE: Checks if current element is of specified type [and name]
  1682. * used to check collection elements
  1683. *
  1684. * PARAMETERS:
  1685. * const CStr& strElementType : type name of the element
  1686. * LPCTSTR szElementName : name of the element or NULL if doesn't matter
  1687. *
  1688. * RETURNS:
  1689. * CXMLElement - pointer to current element
  1690. *
  1691. *+-------------------------------------------------------------------------*/
  1692. CXMLElement
  1693. CPersistor::CheckCurrentElement(const CStr &strElementType, LPCTSTR szElementName)
  1694. {
  1695. DECLARE_SC(sc, TEXT("CPersistor::CheckCurrentElement"));
  1696. CXMLElement elem = GetCurrentElement();
  1697. if(elem.IsNull())
  1698. sc.Throw(E_POINTER);
  1699. CStr strTagName;
  1700. elem.get_tagName(strTagName);
  1701. if (0 != strTagName.CompareNoCase(strElementType))
  1702. sc.Throw(E_FAIL);
  1703. if (szElementName)
  1704. {
  1705. CPersistor temp(*this, elem);
  1706. CStr strName(temp.GetName());
  1707. if (0 != strName.CompareNoCase(szElementName))
  1708. sc.Throw(E_FAIL);
  1709. }
  1710. return elem;
  1711. }
  1712. void
  1713. CPersistor::SetName(const CStr &strName)
  1714. {
  1715. DECLARE_SC(sc, TEXT("CPersistor::SetName"));
  1716. CStr _strName = strName;
  1717. ASSERT(IsStoring());
  1718. PersistAttribute(XML_ATTR_NAME, _strName);
  1719. }
  1720. CStr
  1721. CPersistor::GetName()
  1722. {
  1723. DECLARE_SC(sc, TEXT("CPersistor::GetName"));
  1724. CStr _strName;
  1725. ASSERT(IsLoading());
  1726. // just return empty string if there is no name
  1727. PersistAttribute(XML_ATTR_NAME, _strName, attr_optional);
  1728. return _strName;
  1729. }
  1730. /***************************************************************************\
  1731. *
  1732. * METHOD: CPersistor::PersistString
  1733. *
  1734. * PURPOSE: persists stringtable string
  1735. *
  1736. * PARAMETERS:
  1737. * const CStr &strTag - tag name for the new element
  1738. * CStringTableStringBase &str - string to persist
  1739. * LPCTSTR lpstrName - name [optional]
  1740. *
  1741. * RETURNS:
  1742. * void
  1743. *
  1744. \***************************************************************************/
  1745. void CPersistor::PersistString(LPCTSTR lpstrName, CStringTableStringBase &str)
  1746. {
  1747. DECLARE_SC(sc, TEXT("CPersistor::PersistString"));
  1748. USES_CONVERSION;
  1749. CPersistor subPersistor(*this, XML_TAG_STRING_TABLE_STRING, lpstrName);
  1750. if (subPersistor.IsLoading())
  1751. {
  1752. str.m_id = CStringTableStringBase::eNoValue;
  1753. str.m_str.erase();
  1754. subPersistor.PersistAttribute(XML_ATTR_STRING_TABLE_STR_ID, str.m_id, attr_optional);
  1755. if (str.m_id != CStringTableStringBase::eNoValue)
  1756. {
  1757. sc = ScCheckPointers(str.m_spStringTable);
  1758. if (sc)
  1759. sc.Throw();
  1760. ULONG cch = 0;
  1761. sc = str.m_spStringTable->GetStringLength (str.m_id, &cch, NULL);
  1762. if (sc)
  1763. sc.Throw();
  1764. // allow for NULL terminator
  1765. cch++;
  1766. std::auto_ptr<WCHAR> spszText (new (std::nothrow) WCHAR[cch]);
  1767. LPWSTR pszText = spszText.get();
  1768. sc = ScCheckPointers(pszText,E_OUTOFMEMORY);
  1769. if (sc)
  1770. sc.Throw();
  1771. sc = str.m_spStringTable->GetString (str.m_id, cch, pszText, NULL, NULL);
  1772. if (sc)
  1773. sc.Throw();
  1774. str.m_str = W2T (pszText);
  1775. return;
  1776. }
  1777. std::wstring text;
  1778. subPersistor.PersistAttribute(XML_ATTR_STRING_TABLE_STR_VALUE, text, attr_optional);
  1779. str.m_str = W2CT(text.c_str());
  1780. return;
  1781. }
  1782. str.CommitToStringTable();
  1783. if (FEnableValueSplit() && str.m_id != CStringTableStringBase::eNoValue)
  1784. {
  1785. #ifdef DBG
  1786. /*
  1787. * make sure CommitToStringTable really committed
  1788. */
  1789. if (str.m_id != CStringTableStringBase::eNoValue)
  1790. {
  1791. WCHAR sz[256];
  1792. ASSERT (str.m_spStringTable != NULL);
  1793. HRESULT hr = str.m_spStringTable->GetString (str.m_id, countof(sz), sz, NULL, NULL);
  1794. ASSERT (SUCCEEDED(hr) && "Persisted a CStringTableString to a stream that's not in the string table");
  1795. }
  1796. #endif
  1797. subPersistor.PersistAttribute(XML_ATTR_STRING_TABLE_STR_ID, str.m_id);
  1798. }
  1799. else
  1800. {
  1801. if (str.m_id == CStringTableStringBase::eNoValue)
  1802. str.m_str.erase();
  1803. subPersistor.PersistAttribute(XML_ATTR_STRING_TABLE_STR_VALUE, str.m_str);
  1804. }
  1805. }
  1806. /***************************************************************************\
  1807. *
  1808. * METHOD: CPersistor::PersistAttribute
  1809. *
  1810. * PURPOSE: special method to persist bitflags
  1811. *
  1812. * PARAMETERS:
  1813. * LPCTSTR name [in] name of the flags
  1814. * CXMLBitFlags& flags [in] flags to persist
  1815. *
  1816. * RETURNS:
  1817. * void
  1818. *
  1819. \***************************************************************************/
  1820. void CPersistor::PersistAttribute(LPCTSTR name, CXMLBitFlags& flags )
  1821. {
  1822. flags.PersistMultipleAttributes(name, *this);
  1823. }
  1824. //############################################################################
  1825. //############################################################################
  1826. //
  1827. // Implementation of class XMLPoint
  1828. //
  1829. //############################################################################
  1830. //############################################################################
  1831. XMLPoint::XMLPoint(const CStr &strObjectName, POINT &point)
  1832. :m_strObjectName(strObjectName), m_point(point)
  1833. {
  1834. }
  1835. /*+-------------------------------------------------------------------------*
  1836. *
  1837. * XMLPoint::Persist
  1838. *
  1839. * PURPOSE: Persists an XMLPoint to a persistor.
  1840. *
  1841. * PARAMETERS:
  1842. * CPersistor& persistor :
  1843. *
  1844. * RETURNS:
  1845. * void
  1846. *
  1847. *+-------------------------------------------------------------------------*/
  1848. void
  1849. XMLPoint::Persist(CPersistor& persistor)
  1850. {
  1851. DECLARE_SC(sc, TEXT("XMLPoint::Persist"));
  1852. if (persistor.IsStoring())
  1853. persistor.SetName(m_strObjectName);
  1854. persistor.PersistAttribute(XML_ATTR_POINT_X, m_point.x);
  1855. persistor.PersistAttribute(XML_ATTR_POINT_Y, m_point.y);
  1856. }
  1857. //############################################################################
  1858. //############################################################################
  1859. //
  1860. // Implementation of class XMLRect
  1861. //
  1862. //############################################################################
  1863. //############################################################################
  1864. XMLRect::XMLRect(const CStr strObjectName, RECT &rect)
  1865. :m_strObjectName(strObjectName), m_rect(rect)
  1866. {
  1867. }
  1868. void
  1869. XMLRect::Persist(CPersistor& persistor)
  1870. {
  1871. DECLARE_SC(sc, TEXT("XMLRect::Persist"));
  1872. if (persistor.IsStoring())
  1873. persistor.SetName(m_strObjectName);
  1874. persistor.PersistAttribute(XML_ATTR_RECT_TOP, m_rect.top);
  1875. persistor.PersistAttribute(XML_ATTR_RECT_BOTTOM, m_rect.bottom);
  1876. persistor.PersistAttribute(XML_ATTR_RECT_LEFT, m_rect.left);
  1877. persistor.PersistAttribute(XML_ATTR_RECT_RIGHT, m_rect.right);
  1878. }
  1879. //############################################################################
  1880. //############################################################################
  1881. //
  1882. // Implementation of class CXMLValue
  1883. //
  1884. //############################################################################
  1885. //############################################################################
  1886. /***************************************************************************\
  1887. *
  1888. * METHOD: CXMLValue::GetTypeName
  1889. *
  1890. * PURPOSE: returns tag name (usually type name) to be used as element tag
  1891. * when value is persisted as element via CPersistor.Persist(val)
  1892. *
  1893. * PARAMETERS:
  1894. *
  1895. * RETURNS:
  1896. * LPCTSTR - tag name
  1897. *
  1898. \***************************************************************************/
  1899. LPCTSTR CXMLValue::GetTypeName() const
  1900. {
  1901. switch(m_type)
  1902. {
  1903. case XT_I4 : return XML_TAG_VALUE_LONG;
  1904. case XT_UI4 : return XML_TAG_VALUE_ULONG;
  1905. case XT_UI1 : return XML_TAG_VALUE_BYTE;
  1906. case XT_I2 : return XML_TAG_VALUE_SHORT;
  1907. case XT_DW : return XML_TAG_VALUE_DWORD;
  1908. case XT_BOOL : return XML_TAG_VALUE_BOOL;
  1909. case XT_CPP_BOOL : return XML_TAG_VALUE_BOOL;
  1910. case XT_UINT : return XML_TAG_VALUE_UINT;
  1911. case XT_INT : return XML_TAG_VALUE_INT;
  1912. case XT_STR : return XML_TAG_VALUE_CSTR;
  1913. case XT_WSTR : return XML_TAG_VALUE_WSTRING;
  1914. case XT_GUID : return XML_TAG_VALUE_GUID;
  1915. case XT_BINARY : return XML_TAG_VALUE_BIN_DATA;
  1916. case XT_EXTENSION: return m_val.pExtension->GetTypeName();
  1917. default: return XML_TAG_VALUE_UNKNOWN;
  1918. }
  1919. }
  1920. /***************************************************************************\
  1921. *
  1922. * METHOD: CXMLValue::ScWriteToBSTR
  1923. *
  1924. * PURPOSE: Converts an XML value to a bstring.
  1925. * internally uses WCHAR buffer on the stack for the conversion of integer
  1926. * types.
  1927. *
  1928. * PARAMETERS:
  1929. * BSTR * pbstr - [out] resulting string
  1930. *
  1931. * RETURNS:
  1932. * SC - result code
  1933. *
  1934. \***************************************************************************/
  1935. SC CXMLValue::ScWriteToBSTR (BSTR * pbstr) const
  1936. {
  1937. DECLARE_SC(sc, TEXT("CXMLValue::ScWriteToBSTR"));
  1938. // check parameter
  1939. sc = ScCheckPointers(pbstr);
  1940. if (sc)
  1941. return sc;
  1942. // initialize
  1943. *pbstr = NULL;
  1944. WCHAR szBuffer[40];
  1945. int cchBuffer = 40;
  1946. CComBSTR bstrResult;
  1947. USES_CONVERSION;
  1948. switch(m_type)
  1949. {
  1950. case XT_I4: //LONG
  1951. sc = StringCchPrintfW(szBuffer, cchBuffer, L"%d\0", *m_val.pL);
  1952. if(sc)
  1953. return sc;
  1954. bstrResult = szBuffer;
  1955. break;
  1956. case XT_UI4: //LONG
  1957. sc = StringCchPrintfW(szBuffer, cchBuffer, L"%u\0", *m_val.pUl);
  1958. if(sc)
  1959. return sc;
  1960. bstrResult = szBuffer;
  1961. break;
  1962. case XT_UI1: //BYTE
  1963. sc = StringCchPrintfW(szBuffer, cchBuffer, L"0x%02.2x\0", (int)*m_val.pByte);
  1964. if(sc)
  1965. return sc;
  1966. bstrResult = szBuffer;
  1967. break;
  1968. case XT_I2: //SHORT
  1969. sc = StringCchPrintfW(szBuffer, cchBuffer, L"%d\0", (int)*m_val.pS);
  1970. if(sc)
  1971. return sc;
  1972. bstrResult = szBuffer;
  1973. break;
  1974. case XT_DW: //DWORD
  1975. sc = StringCchPrintfW(szBuffer, cchBuffer, L"0x%04.4x\0", *m_val.pDw);
  1976. if(sc)
  1977. return sc;
  1978. bstrResult = szBuffer;
  1979. break;
  1980. case XT_BOOL://BOOL: can either print true/false
  1981. bstrResult = ( *m_val.pBOOL ? XML_VAL_BOOL_TRUE : XML_VAL_BOOL_FALSE );
  1982. break;
  1983. case XT_CPP_BOOL://bool: can either print true/false
  1984. bstrResult = ( *m_val.pbool ? XML_VAL_BOOL_TRUE : XML_VAL_BOOL_FALSE );
  1985. break;
  1986. case XT_UINT: //UINT
  1987. sc = StringCchPrintfW(szBuffer, cchBuffer, L"%u\0", *m_val.pUint);
  1988. if(sc)
  1989. return sc;
  1990. bstrResult = szBuffer;
  1991. break;
  1992. case XT_INT: //UINT
  1993. sc = StringCchPrintfW(szBuffer, cchBuffer, L"%d\0", *m_val.pInt);
  1994. if(sc)
  1995. return sc;
  1996. bstrResult = szBuffer;
  1997. break;
  1998. case XT_STR: //CStr
  1999. bstrResult = T2COLE(static_cast<LPCTSTR>(*m_val.pStr));
  2000. break;
  2001. case XT_WSTR: //wstring
  2002. bstrResult = m_val.pWStr->c_str();
  2003. break;
  2004. case XT_TSTR: //tstring
  2005. bstrResult = T2COLE(m_val.pTStr->c_str());
  2006. break;
  2007. case XT_GUID: //GUID
  2008. {
  2009. LPOLESTR sz;
  2010. StringFromCLSID(*m_val.pGuid, &sz);
  2011. bstrResult = sz;
  2012. CoTaskMemFree(sz);
  2013. }
  2014. break;
  2015. case XT_BINARY:
  2016. sc = ScEncodeBinary(bstrResult, *m_val.pXmlBinary);
  2017. if (sc)
  2018. return sc;
  2019. break;
  2020. case XT_EXTENSION:
  2021. sc = m_val.pExtension->ScWriteToBSTR (&bstrResult);
  2022. if (sc)
  2023. return sc;
  2024. break;
  2025. default:
  2026. //ASSERT(0 && "Should not come here!!");
  2027. return sc = E_NOTIMPL;
  2028. }
  2029. *pbstr = bstrResult.Detach();
  2030. return sc;
  2031. }
  2032. /***************************************************************************\
  2033. *
  2034. * METHOD: CXMLValue::ScReadFromBSTR
  2035. *
  2036. * PURPOSE: Converts a string an XML value
  2037. *
  2038. * PARAMETERS:
  2039. * const BSTR bstr - [in] string to be read
  2040. *
  2041. * RETURNS:
  2042. * SC - result code
  2043. *
  2044. \***************************************************************************/
  2045. SC CXMLValue::ScReadFromBSTR(const BSTR bstr)
  2046. {
  2047. DECLARE_SC(sc, TEXT("CXMLValue::ScReadFromBSTR"));
  2048. LPCOLESTR olestr = bstr;
  2049. if (olestr == NULL) // make sure we always have a valid pointer
  2050. olestr = L""; // in case of NULL we use own empty string
  2051. USES_CONVERSION;
  2052. switch(m_type)
  2053. {
  2054. case XT_I4: //LONG
  2055. *m_val.pL = wcstol(olestr,NULL,10);
  2056. break;
  2057. case XT_UI4: //LONG
  2058. *m_val.pUl = wcstoul(olestr,NULL,10);
  2059. break;
  2060. case XT_UI1: //BYTE
  2061. *m_val.pByte = static_cast<BYTE>(wcstol(olestr,NULL,10));
  2062. break;
  2063. case XT_I2: //SHORT
  2064. *m_val.pS = static_cast<SHORT>(wcstol(olestr,NULL,10));
  2065. break;
  2066. case XT_DW: //DWORD
  2067. *m_val.pDw = wcstoul(olestr,NULL,10);
  2068. break;
  2069. case XT_BOOL://BOOL: can either be true/false
  2070. {
  2071. *m_val.pBOOL = FALSE;
  2072. LPCWSTR pszXmlBool = T2CW(XML_VAL_BOOL_TRUE);
  2073. if (NULL != pszXmlBool)
  2074. {
  2075. *m_val.pBOOL = (0 == _wcsicmp(olestr, pszXmlBool));
  2076. }
  2077. }
  2078. break;
  2079. case XT_CPP_BOOL://bool: can either be true/false
  2080. {
  2081. *m_val.pbool = FALSE;
  2082. LPCWSTR pszXmlBool = T2CW(XML_VAL_BOOL_TRUE);
  2083. if (NULL != pszXmlBool)
  2084. {
  2085. *m_val.pbool = (0 == _wcsicmp(olestr, pszXmlBool));
  2086. }
  2087. }
  2088. break;
  2089. case XT_UINT: //UINT
  2090. *m_val.pUint = wcstoul(olestr,NULL,10);
  2091. break;
  2092. case XT_INT: //UINT
  2093. *m_val.pInt = wcstol(olestr,NULL,10);
  2094. break;
  2095. case XT_STR: //CStr
  2096. *m_val.pStr = OLE2CT(olestr);
  2097. break;
  2098. case XT_WSTR: //CString
  2099. *m_val.pWStr = olestr;
  2100. break;
  2101. case XT_TSTR: //tstring
  2102. *m_val.pTStr = OLE2CT(olestr);
  2103. break;
  2104. case XT_GUID: //GUID
  2105. sc = CLSIDFromString(const_cast<LPOLESTR>(olestr), m_val.pGuid);
  2106. if (sc)
  2107. return sc;
  2108. break;
  2109. case XT_BINARY:
  2110. sc = ScDecodeBinary(olestr, m_val.pXmlBinary);
  2111. if (sc)
  2112. return sc;
  2113. break;
  2114. case XT_EXTENSION:
  2115. sc = m_val.pExtension->ScReadFromBSTR(bstr);
  2116. if (sc)
  2117. return sc;
  2118. break;
  2119. default:
  2120. //ASSERT(0 && "Should not come here!!");
  2121. return sc = E_NOTIMPL;
  2122. }
  2123. return sc;
  2124. }
  2125. /*+-------------------------------------------------------------------------*
  2126. *
  2127. * METHOD: XMLListCollectionBase::Persist
  2128. *
  2129. * PURPOSE: implements persisting of list contents from XML file
  2130. * iterates child elements calling virtual mem. OnNewElement for each
  2131. *
  2132. * PARAMETERS:
  2133. * CPersistor& persistorNew : persistor object
  2134. *
  2135. * RETURNS:
  2136. * void
  2137. *
  2138. *+-------------------------------------------------------------------------*/
  2139. void XMLListCollectionBase::Persist(CPersistor& persistor)
  2140. {
  2141. DECLARE_SC(sc, TEXT("XMLListCollectionBase::Persist"));
  2142. ASSERT(persistor.IsLoading());
  2143. CXMLElementCollection colChildren;
  2144. persistor.GetCurrentElement().get_children(&colChildren);
  2145. if (colChildren.IsNull())
  2146. {
  2147. // no children -> we are done!
  2148. return;
  2149. }
  2150. long nChildren = 0;
  2151. colChildren.get_count(&nChildren);
  2152. for (long nChild = 0; nChild < nChildren; nChild++)
  2153. {
  2154. CXMLElement el;
  2155. colChildren.item(nChild, &el);
  2156. if (!el.IsNull())
  2157. {
  2158. DOMNodeType lType = NODE_INVALID;
  2159. el.get_type(&lType);
  2160. if (lType == NODE_ELEMENT)
  2161. {
  2162. CPersistor persistorNewLocked(persistor, el, true);
  2163. OnNewElement(persistorNewLocked);
  2164. }
  2165. }
  2166. }
  2167. }
  2168. /*+-------------------------------------------------------------------------*
  2169. *
  2170. * METHOD: XMLMapCollectionBase::Persist
  2171. *
  2172. * PURPOSE: implements persisting of map contents from XML file
  2173. * iterates child elements calling virtual mem. OnNewElement for each pair
  2174. *
  2175. * PARAMETERS:
  2176. * CPersistor& persistorNew : persistor object
  2177. *
  2178. * RETURNS:
  2179. * void
  2180. *
  2181. *+-------------------------------------------------------------------------*/
  2182. void XMLMapCollectionBase::Persist(CPersistor& persistor)
  2183. {
  2184. DECLARE_SC(sc, TEXT("XMLMapCollectionBase::Persist"));
  2185. ASSERT(persistor.IsLoading());
  2186. CXMLElementCollection colChildren;
  2187. persistor.GetCurrentElement().get_children(&colChildren);
  2188. if (colChildren.IsNull())
  2189. {
  2190. // no children -> we are done!
  2191. return;
  2192. }
  2193. long nChildren = 0;
  2194. colChildren.get_count(&nChildren);
  2195. // collect all elements of proper type
  2196. std::vector<CXMLElement> vecChilds;
  2197. for (long nChild = 0; nChild < nChildren; nChild ++)
  2198. {
  2199. CXMLElement el;
  2200. colChildren.item(nChild, &el);
  2201. if (!el.IsNull())
  2202. {
  2203. DOMNodeType lType = NODE_INVALID;
  2204. el.get_type(&lType);
  2205. if (lType == NODE_ELEMENT)
  2206. vecChilds.push_back(el);
  2207. }
  2208. }
  2209. for (nChild = 0; nChild + 1 < vecChilds.size(); nChild += 2)
  2210. {
  2211. CXMLElement el(vecChilds[nChild]);
  2212. CXMLElement el2(vecChilds[nChild+1]);
  2213. CPersistor persistorNew1(persistor, el, true);
  2214. CPersistor persistorNew2(persistor, el2, true);
  2215. OnNewElement(persistorNew1,persistorNew2);
  2216. }
  2217. }
  2218. /*+-------------------------------------------------------------------------*
  2219. *
  2220. * ScEncodeBinary
  2221. *
  2222. * PURPOSE: converts data to encoded format for xml
  2223. *
  2224. * PARAMETERS:
  2225. *
  2226. * RETURNS:
  2227. * SC - error code
  2228. *
  2229. *+-------------------------------------------------------------------------*/
  2230. static SC ScEncodeBinary(CComBSTR& bstrResult, const CXMLBinary& binSrc)
  2231. {
  2232. DECLARE_SC(sc, TEXT("ScEncodeBinary"));
  2233. // initialize
  2234. bstrResult.Empty();
  2235. // nothing if binary is zero size...
  2236. if (binSrc.GetSize() == 0)
  2237. return sc;
  2238. // line length for the binary data. maximum allowed by base64 per line is 76
  2239. const int line_len = 76;
  2240. // symbols to be placed as terminators of each line
  2241. const WCHAR line_end[] = { 0x0d, 0x0a };
  2242. DWORD dwBytesLeft = binSrc.GetSize();
  2243. // space required for encription
  2244. DWORD dwCount = (dwBytesLeft*8+5)/6;
  2245. // ... plus up to three '='
  2246. dwCount += (4 - dwCount%4) & 0x03;
  2247. // allow space for white_spaces inerted and terminating zero
  2248. dwCount += (dwCount / line_len)*countof(line_end) + 1;
  2249. BOOL bOk = SysReAllocStringLen(&bstrResult,NULL,dwCount);
  2250. if (bOk != TRUE || (LPOLESTR)bstrResult == NULL)
  2251. return sc = E_OUTOFMEMORY;
  2252. LPOLESTR pstrResult = bstrResult;
  2253. *pstrResult = 0;
  2254. if (!dwBytesLeft)
  2255. return sc; // emty seq? - we are done
  2256. const BYTE *pData = NULL;
  2257. sc = binSrc.ScLockData((const void **)&pData);
  2258. if (sc)
  2259. return sc;
  2260. sc = ScCheckPointers(pData, E_UNEXPECTED);
  2261. if(sc)
  2262. return sc;
  2263. DWORD dwCharsStored = 0;
  2264. while (dwBytesLeft)
  2265. {
  2266. base64_table::encode(pData, dwBytesLeft, pstrResult);
  2267. dwCharsStored += 4;
  2268. if (0 == (dwCharsStored % line_len) && dwBytesLeft)
  2269. for (int i = 0; i < countof(line_end); i++)
  2270. *pstrResult++ = line_end[i];
  2271. }
  2272. // terminate
  2273. *pstrResult = 0;
  2274. sc = binSrc.ScUnlockData();
  2275. if (sc)
  2276. sc.TraceAndClear();
  2277. return sc;
  2278. }
  2279. /*+-------------------------------------------------------------------------*
  2280. *
  2281. * ScDecodeBinary
  2282. *
  2283. * PURPOSE: converts encoded data back to image
  2284. *
  2285. * PARAMETERS:
  2286. *
  2287. * RETURNS:
  2288. * void
  2289. *
  2290. *+-------------------------------------------------------------------------*/
  2291. static SC ScDecodeBinary(const CComBSTR& bstrSource, CXMLBinary *pBinResult)
  2292. {
  2293. DECLARE_SC(sc, TEXT("ScDecodeBinary"));
  2294. DWORD dwCount = bstrSource.Length();
  2295. DWORD dwSize = (dwCount*6+7)/8;
  2296. sc = ScCheckPointers(pBinResult);
  2297. if (sc)
  2298. return sc;
  2299. sc = pBinResult->ScFree(); // ignore the error here
  2300. if (sc)
  2301. sc.TraceAndClear();
  2302. if (!dwSize) // no data? - good
  2303. return sc;
  2304. sc = pBinResult->ScAlloc(dwSize);
  2305. if(sc)
  2306. return sc;
  2307. CXMLBinaryLock sLock(*pBinResult);
  2308. BYTE *pData = NULL;
  2309. sc = sLock.ScLock(&pData);
  2310. if(sc)
  2311. return sc;
  2312. // recheck
  2313. sc = ScCheckPointers(pData, E_UNEXPECTED);
  2314. if (sc)
  2315. return sc;
  2316. BYTE * const pDataStart = pData;
  2317. LPOLESTR pInput = bstrSource;
  2318. while(base64_table::decode(pInput, pData));
  2319. sc = sLock.ScUnlock();
  2320. if (sc)
  2321. sc.TraceAndClear();
  2322. DWORD dwDataDecoded = pData - pDataStart;
  2323. // fix data size , if required
  2324. if (dwDataDecoded != dwSize)
  2325. {
  2326. if (dwDataDecoded == 0)
  2327. sc = pBinResult->ScFree();
  2328. else
  2329. sc = pBinResult->ScRealloc(dwDataDecoded);
  2330. if (sc)
  2331. return sc;
  2332. }
  2333. return sc;
  2334. }
  2335. /***************************************************************************\
  2336. *
  2337. * METHOD: CXML_IStorage::ScInitialize
  2338. *
  2339. * PURPOSE: Initializes object. Creates new storage if does not have one
  2340. *
  2341. * PARAMETERS:
  2342. * bool& bCreatedNewOne [out] - created new stream
  2343. *
  2344. * RETURNS:
  2345. * SC - result code.
  2346. *
  2347. \***************************************************************************/
  2348. SC CXML_IStorage::ScInitialize(bool& bCreatedNewOne)
  2349. {
  2350. DECLARE_SC(sc, TEXT("CXML_IStorage::ScInitialize"));
  2351. // short cut if initialized oalready
  2352. if (m_Storage != NULL)
  2353. {
  2354. bCreatedNewOne = false;
  2355. return sc;
  2356. }
  2357. bCreatedNewOne = true;
  2358. // create the ILockBytes
  2359. sc = CreateILockBytesOnHGlobal(NULL, TRUE, &m_LockBytes);
  2360. if(sc)
  2361. return sc;
  2362. // create the IStorage
  2363. sc = StgCreateDocfileOnILockBytes( m_LockBytes,
  2364. STGM_CREATE | STGM_SHARE_EXCLUSIVE | STGM_READWRITE,
  2365. 0, &m_Storage);
  2366. if(sc)
  2367. return sc;
  2368. return sc;
  2369. }
  2370. /***************************************************************************\
  2371. *
  2372. * METHOD: CXML_IStorage::ScInitializeFrom
  2373. *
  2374. * PURPOSE: Initializes object. copies contents from provided source
  2375. *
  2376. * PARAMETERS:
  2377. * IStorage *pSource [in] initial contents of the storage
  2378. *
  2379. * RETURNS:
  2380. * SC - result code
  2381. *
  2382. \***************************************************************************/
  2383. SC CXML_IStorage::ScInitializeFrom( IStorage *pSource )
  2384. {
  2385. DECLARE_SC(sc, TEXT("CXML_IStorage::ScInitializeFrom"));
  2386. // parameter check
  2387. sc = ScCheckPointers( pSource );
  2388. if (sc)
  2389. return sc;
  2390. // init empty
  2391. bool bCreatedNewOne = false; // not used here
  2392. sc = ScInitialize(bCreatedNewOne);
  2393. if (sc)
  2394. return sc;
  2395. ASSERT( m_Storage != NULL );
  2396. // copy contents
  2397. sc = pSource->CopyTo( 0, NULL, NULL, m_Storage );
  2398. if (sc)
  2399. return sc;
  2400. return sc;
  2401. }
  2402. /***************************************************************************\
  2403. *
  2404. * METHOD: CXML_IStorage::ScGetIStorage
  2405. *
  2406. * PURPOSE: returns pointer to maintained storage.
  2407. *
  2408. * PARAMETERS:
  2409. * IStorage **ppStorage [out] pointer to the storage
  2410. *
  2411. * RETURNS:
  2412. * SC - result code.
  2413. *
  2414. \***************************************************************************/
  2415. SC CXML_IStorage::ScGetIStorage( IStorage **ppStorage )
  2416. {
  2417. DECLARE_SC(sc, TEXT("CXML_IStorage::ScGetIStorage"));
  2418. // parameter check
  2419. sc = ScCheckPointers( ppStorage );
  2420. if (sc)
  2421. return sc;
  2422. // init out parameter
  2423. *ppStorage = NULL;
  2424. // make sure we have storage - initialize
  2425. bool bCreatedNewOne = false; // not used here
  2426. sc = ScInitialize( bCreatedNewOne );
  2427. if (sc)
  2428. return sc;
  2429. // recheck if the member is set
  2430. sc = ScCheckPointers ( m_Storage, E_UNEXPECTED );
  2431. if (sc)
  2432. return sc;
  2433. // return the pointer
  2434. *ppStorage = m_Storage;
  2435. (*ppStorage)->AddRef();
  2436. return sc;
  2437. }
  2438. /*+-------------------------------------------------------------------------*
  2439. *
  2440. * METHOD: CXML_IStorage::ScRequestSave
  2441. *
  2442. * PURPOSE: asks snapin to save using snapin's IPersistStorage
  2443. *
  2444. *+-------------------------------------------------------------------------*/
  2445. SC
  2446. CXML_IStorage::ScRequestSave( IPersistStorage * pPersistStorage )
  2447. {
  2448. DECLARE_SC(sc, TEXT("CXML_IStorage::ScRequestSave"));
  2449. bool bCreatedNewOne = false;
  2450. sc = ScInitialize( bCreatedNewOne );
  2451. if (sc)
  2452. return sc;
  2453. // recheck the pointer
  2454. sc = ScCheckPointers( m_Storage, E_UNEXPECTED );
  2455. if (sc)
  2456. return sc;
  2457. sc = pPersistStorage->Save(m_Storage, !bCreatedNewOne);
  2458. if(sc)
  2459. return sc;
  2460. sc = pPersistStorage->SaveCompleted(NULL);
  2461. // we were always passing a storage in MMC 1.2, so some of the
  2462. // snapins did not expect it to be NULL (which is correct value when
  2463. // storage does not change)
  2464. // to be able to save such snapins we need to to ignore this error
  2465. // see bug 96344
  2466. if (sc == SC(E_INVALIDARG))
  2467. {
  2468. #ifdef DBG
  2469. m_dbg_Data.TraceErr(_T("IPersistStorage::SaveCompleted"), _T("legal argument NULL passed to snapin, but error returned"));
  2470. #endif
  2471. sc = pPersistStorage->SaveCompleted(m_Storage);
  2472. }
  2473. if(sc)
  2474. return sc;
  2475. // commit the changes - this ensures everything is in HGLOBAL
  2476. sc = m_Storage->Commit( STGC_DEFAULT );
  2477. if(sc)
  2478. return sc;
  2479. #ifdef DBG
  2480. if (S_FALSE != pPersistStorage->IsDirty())
  2481. m_dbg_Data.TraceErr(_T("IPersistStorage"), _T("Reports 'IsDirty' right after 'Save'"));
  2482. #endif // #ifdef DBG
  2483. return sc;
  2484. }
  2485. /*+-------------------------------------------------------------------------*
  2486. *
  2487. * m_Storage: CXML_IStorage::Persist
  2488. *
  2489. * PURPOSE: dumps data to HGLOBAL and persists
  2490. *
  2491. *+-------------------------------------------------------------------------*/
  2492. void
  2493. CXML_IStorage::Persist(CPersistor &persistor)
  2494. {
  2495. DECLARE_SC(sc, TEXT("CXML_IStorage::Persist"));
  2496. if (persistor.IsStoring())
  2497. {
  2498. bool bCreatedNewOne = false; // not used here
  2499. sc = ScInitialize( bCreatedNewOne );
  2500. if (sc)
  2501. sc.Throw();
  2502. HANDLE hStorage = NULL;
  2503. sc = GetHGlobalFromILockBytes(m_LockBytes, &hStorage);
  2504. if(sc)
  2505. sc.Throw();
  2506. STATSTG statstg;
  2507. ZeroMemory(&statstg, sizeof(statstg));
  2508. sc = m_LockBytes->Stat(&statstg, STATFLAG_NONAME);
  2509. if (sc)
  2510. sc.Throw();
  2511. CXMLBinary binInitial;
  2512. binInitial.Attach(hStorage, statstg.cbSize.LowPart);
  2513. // persist the contents
  2514. persistor.PersistContents(binInitial);
  2515. return; // done
  2516. }
  2517. //--- Loading ---
  2518. CXMLAutoBinary binLoaded;
  2519. persistor.PersistContents(binLoaded);
  2520. // Need to recreate storage...
  2521. ASSERT(persistor.IsLoading()); // should not reallocate else!!
  2522. m_LockBytes = NULL;
  2523. ULARGE_INTEGER new_size = { binLoaded.GetSize(), 0 };
  2524. sc = CreateILockBytesOnHGlobal(binLoaded.GetHandle(), TRUE, &m_LockBytes);
  2525. if(sc)
  2526. sc.Throw();
  2527. // control transferred to ILockBytes
  2528. binLoaded.Detach();
  2529. sc = m_LockBytes->SetSize(new_size);
  2530. if(sc)
  2531. sc.Throw();
  2532. sc = StgOpenStorageOnILockBytes(m_LockBytes, NULL , STGM_SHARE_EXCLUSIVE | STGM_READWRITE,
  2533. NULL, 0, &m_Storage);
  2534. if(sc)
  2535. sc.Throw();
  2536. }
  2537. /***************************************************************************\
  2538. *
  2539. * METHOD: CXML_IStream::ScInitialize
  2540. *
  2541. * PURPOSE: initializes object. creates empty stream if does not have one
  2542. *
  2543. * PARAMETERS:
  2544. * bool& bCreatedNewOne [out] - created new stream
  2545. *
  2546. * RETURNS:
  2547. * SC - result code.
  2548. *
  2549. \***************************************************************************/
  2550. SC CXML_IStream::ScInitialize( bool& bCreatedNewOne )
  2551. {
  2552. DECLARE_SC(sc, TEXT("CXML_IStream::ScInitialize"));
  2553. if (m_Stream != NULL)
  2554. {
  2555. bCreatedNewOne = false;
  2556. return sc;
  2557. }
  2558. bCreatedNewOne = true;
  2559. sc = CreateStreamOnHGlobal( NULL, TRUE, &m_Stream);
  2560. if(sc)
  2561. return sc;
  2562. const ULARGE_INTEGER zero_size = {0,0};
  2563. sc = m_Stream->SetSize(zero_size);
  2564. if(sc)
  2565. return sc;
  2566. sc = ScSeekBeginning();
  2567. if(sc)
  2568. return sc;
  2569. return sc;
  2570. }
  2571. /***************************************************************************\
  2572. *
  2573. * METHOD: CXML_IStream::ScInitializeFrom
  2574. *
  2575. * PURPOSE: Initializes object. Copies contents from provided source
  2576. *
  2577. * PARAMETERS:
  2578. * IStream *pSource [in] initial contents of the stream
  2579. *
  2580. * RETURNS:
  2581. * SC - result code
  2582. *
  2583. \***************************************************************************/
  2584. SC CXML_IStream::ScInitializeFrom( IStream *pSource )
  2585. {
  2586. DECLARE_SC(sc, TEXT("CXML_IStream::ScInitializeFrom"));
  2587. // parameter check
  2588. sc = ScCheckPointers( pSource );
  2589. if (sc)
  2590. return sc;
  2591. // initialize empty
  2592. bool bCreatedNewOne = false; // not used here
  2593. sc = ScInitialize( bCreatedNewOne );
  2594. if (sc)
  2595. return sc;
  2596. ASSERT( m_Stream != NULL );
  2597. // reset stream pointer
  2598. sc = ScSeekBeginning();
  2599. if(sc)
  2600. return sc;
  2601. // copy contents from source
  2602. STATSTG statstg;
  2603. sc = pSource->Stat(&statstg, STATFLAG_NONAME);
  2604. if (sc)
  2605. return sc;
  2606. // copy contents
  2607. ULARGE_INTEGER cbRead;
  2608. ULARGE_INTEGER cbWritten;
  2609. sc = pSource->CopyTo( m_Stream, statstg.cbSize, &cbRead, &cbWritten );
  2610. if (sc)
  2611. return sc;
  2612. return sc;
  2613. }
  2614. /***************************************************************************\
  2615. *
  2616. * METHOD: CXML_IStream::ScSeekBeginning
  2617. *
  2618. * PURPOSE: resets stream pointer to the beginning of the stream
  2619. *
  2620. * PARAMETERS:
  2621. *
  2622. * RETURNS:
  2623. * SC - result code
  2624. *
  2625. \***************************************************************************/
  2626. SC CXML_IStream::ScSeekBeginning()
  2627. {
  2628. DECLARE_SC(sc, TEXT("CXML_IStream::ScSeekBeginning"));
  2629. LARGE_INTEGER null_offset = { 0, 0 };
  2630. sc = m_Stream->Seek(null_offset, STREAM_SEEK_SET, NULL);
  2631. if(sc)
  2632. return sc;
  2633. return sc;
  2634. }
  2635. /***************************************************************************\
  2636. *
  2637. * METHOD: CXML_IStream::ScGetIStream
  2638. *
  2639. * PURPOSE: returns the pointer to maintained stream
  2640. *
  2641. * PARAMETERS:
  2642. * IStream **ppStream
  2643. *
  2644. * RETURNS:
  2645. * SC - result code
  2646. *
  2647. \***************************************************************************/
  2648. SC CXML_IStream::ScGetIStream( IStream **ppStream )
  2649. {
  2650. DECLARE_SC(sc, TEXT("CXML_IStream::ScGetIStream"));
  2651. // parameter check
  2652. sc = ScCheckPointers( ppStream );
  2653. if (sc)
  2654. return sc;
  2655. // init out parameter
  2656. *ppStream = NULL;
  2657. bool bCreatedNewOne = false; // not used here
  2658. sc = ScInitialize( bCreatedNewOne );
  2659. if (sc)
  2660. return sc;
  2661. sc = ScSeekBeginning();
  2662. if (sc)
  2663. return sc;
  2664. // recheck if the member is set
  2665. sc = ScCheckPointers ( m_Stream, E_UNEXPECTED );
  2666. if (sc)
  2667. return sc;
  2668. *ppStream = m_Stream;
  2669. (*ppStream)->AddRef();
  2670. return sc;
  2671. }
  2672. /*+-------------------------------------------------------------------------*
  2673. *
  2674. * METHOD: CXML_IStream::Persist
  2675. *
  2676. * PURPOSE: persist data of maintained IStream
  2677. *
  2678. * NOTE: Object may point to another Stream after this method
  2679. *
  2680. *+-------------------------------------------------------------------------*/
  2681. void
  2682. CXML_IStream::Persist(CPersistor &persistor)
  2683. {
  2684. DECLARE_SC(sc, TEXT("CXML_IStream::Persist"));
  2685. if (persistor.IsStoring())
  2686. {
  2687. bool bCreatedNewOne = false; // not used here
  2688. sc = ScInitialize( bCreatedNewOne );
  2689. if (sc)
  2690. sc.Throw();
  2691. sc = ScCheckPointers(m_Stream, E_UNEXPECTED);
  2692. if (sc)
  2693. sc.Throw();
  2694. HANDLE hStream = NULL;
  2695. sc = GetHGlobalFromStream( m_Stream, &hStream );
  2696. if(sc)
  2697. sc.Throw();
  2698. STATSTG statstg;
  2699. ZeroMemory(&statstg, sizeof(statstg));
  2700. sc = m_Stream->Stat(&statstg, STATFLAG_NONAME);
  2701. if (sc)
  2702. sc.Throw();
  2703. CXMLBinary binInitial;
  2704. binInitial.Attach(hStream, statstg.cbSize.LowPart);
  2705. // persist the contents
  2706. persistor.PersistContents(binInitial);
  2707. return; // done
  2708. }
  2709. //--- Loading ---
  2710. CXMLAutoBinary binLoaded;
  2711. persistor.PersistContents(binLoaded);
  2712. // Need to recreate stream...
  2713. ULARGE_INTEGER new_size = { binLoaded.GetSize(), 0 };
  2714. sc = CreateStreamOnHGlobal(binLoaded.GetHandle(), TRUE, &m_Stream);
  2715. if(sc)
  2716. sc.Throw();
  2717. // control transferred to IStream
  2718. binLoaded.Detach();
  2719. sc = m_Stream->SetSize(new_size);
  2720. if(sc)
  2721. sc.Throw();
  2722. // reset stream pointer
  2723. sc = ScSeekBeginning();
  2724. if(sc)
  2725. sc.Throw();
  2726. }
  2727. /***************************************************************************\
  2728. | trace support helper for CHK builds
  2729. \***************************************************************************/
  2730. #ifdef DBG
  2731. void CXML_IStream::DBG_TraceNotResettingDirty(LPCSTR strIntfName)
  2732. {
  2733. USES_CONVERSION;
  2734. tstring inft = A2CT(strIntfName); // get the name of interface
  2735. inft.erase(inft.begin(), inft.begin() + strlen("struct ")); // cut the 'struct' off
  2736. m_dbg_Data.TraceErr(inft.c_str(), _T("Reports 'IsDirty' right after 'Save'"));
  2737. }
  2738. #endif
  2739. /*+-------------------------------------------------------------------------*
  2740. *
  2741. * METHOD: CXMLPersistableIcon::Persist
  2742. *
  2743. * PURPOSE: persists icon contents
  2744. *
  2745. *+-------------------------------------------------------------------------*/
  2746. void CXMLPersistableIcon::Persist(CPersistor &persistor)
  2747. {
  2748. DECLARE_SC(sc, TEXT("CXMLPersistableIcon::Persist"));
  2749. persistor.PersistAttribute(XML_ATTR_ICON_INDEX, m_Icon.m_Data.m_nIndex);
  2750. CStr strIconFile = m_Icon.m_Data.m_strIconFile.c_str();
  2751. persistor.PersistAttribute(XML_ATTR_ICON_FILE, strIconFile);
  2752. m_Icon.m_Data.m_strIconFile = strIconFile;
  2753. CXMLIcon iconLarge (XML_ATTR_CONSOLE_ICON_LARGE);
  2754. CXMLIcon iconSmall (XML_ATTR_CONSOLE_ICON_SMALL);
  2755. if (persistor.IsStoring())
  2756. {
  2757. iconLarge = m_Icon.m_icon32;
  2758. iconSmall = m_Icon.m_icon16;
  2759. }
  2760. // keep this order intact to allow icon lookup by shellext
  2761. persistor.Persist (iconLarge, XML_NAME_ICON_LARGE);
  2762. persistor.Persist (iconSmall, XML_NAME_ICON_SMALL);
  2763. if (persistor.IsLoading())
  2764. {
  2765. m_Icon.m_icon32 = iconLarge;
  2766. m_Icon.m_icon16 = iconSmall;
  2767. }
  2768. }
  2769. /*+-------------------------------------------------------------------------*
  2770. *
  2771. * FUNCTION: ScReadDataFromFile
  2772. *
  2773. * PURPOSE: reads file data to global memory
  2774. *
  2775. *+-------------------------------------------------------------------------*/
  2776. static SC ScReadDataFromFile(LPCTSTR strName, CXMLBinary *pBinResult)
  2777. {
  2778. DECLARE_SC(sc, TEXT("ScReadDataFromFile"));
  2779. // check parameter
  2780. sc = ScCheckPointers(pBinResult);
  2781. if (sc)
  2782. return sc;
  2783. HANDLE hFile = INVALID_HANDLE_VALUE;
  2784. // try to open existing file
  2785. hFile = CreateFile(strName,
  2786. GENERIC_READ,
  2787. FILE_SHARE_READ,
  2788. NULL,
  2789. OPEN_EXISTING,
  2790. FILE_ATTRIBUTE_NORMAL,
  2791. NULL
  2792. );
  2793. // check if we are unable to get to the file
  2794. if (hFile == INVALID_HANDLE_VALUE)
  2795. {
  2796. sc.FromWin32(GetLastError());
  2797. return sc;
  2798. }
  2799. // see how large the file is
  2800. ULARGE_INTEGER cbCurrSize;
  2801. cbCurrSize.LowPart = GetFileSize(hFile,&cbCurrSize.HighPart);
  2802. if (cbCurrSize.HighPart != 0 || (LONG)(cbCurrSize.LowPart) < 0) // limiting to 2GB
  2803. {
  2804. sc = E_UNEXPECTED;
  2805. goto CleanUpAndExit;
  2806. }
  2807. if (!cbCurrSize.LowPart)
  2808. {
  2809. // empty file. ok at this point
  2810. goto CleanUpAndExit;
  2811. }
  2812. sc = pBinResult->ScAlloc(cbCurrSize.LowPart);
  2813. if (sc)
  2814. goto CleanUpAndExit;
  2815. { // scoping for vars
  2816. // no the time to do some reading
  2817. DWORD dwRead = 0;
  2818. BOOL bRead = FALSE;
  2819. CXMLBinaryLock sLock(*pBinResult); // will unlock in destructor
  2820. LPVOID pData = NULL;
  2821. sc = sLock.ScLock(&pData);
  2822. if (sc)
  2823. goto CleanUpAndExit;
  2824. sc = ScCheckPointers(pData,E_OUTOFMEMORY);
  2825. if (sc)
  2826. goto CleanUpAndExit;
  2827. bRead = ReadFile(hFile,pData,cbCurrSize.LowPart,&dwRead,NULL);
  2828. if (!bRead)
  2829. {
  2830. sc.FromLastError();
  2831. goto CleanUpAndExit;
  2832. }
  2833. else if (dwRead != cbCurrSize.LowPart)
  2834. {
  2835. // something strange
  2836. sc = E_UNEXPECTED;
  2837. goto CleanUpAndExit;
  2838. }
  2839. } // scoping for vars
  2840. CleanUpAndExit:
  2841. CloseHandle(hFile);
  2842. return sc;
  2843. }
  2844. /*+-------------------------------------------------------------------------*
  2845. *
  2846. * FUNCTION: ScSaveXMLDocumentToString
  2847. *
  2848. * PURPOSE: stores contents of XML document into the string
  2849. *
  2850. *+-------------------------------------------------------------------------*/
  2851. SC ScSaveXMLDocumentToString(CXMLDocument& xmlDocument, std::wstring& strResult)
  2852. {
  2853. DECLARE_SC(sc, TEXT("ScSaveXMLDocumentToString"));
  2854. CComBSTR bstrResult;
  2855. sc = xmlDocument.ScSave(bstrResult);
  2856. if (sc)
  2857. return sc;
  2858. // allocate and copy string
  2859. strResult = bstrResult;
  2860. // now remove all the \n and \r characters
  2861. tstring::size_type pos;
  2862. while ((pos = strResult.find_first_of(L"\n\r")) != strResult.npos)
  2863. strResult.erase(pos, 1);
  2864. return sc;
  2865. }
  2866. /*+-------------------------------------------------------------------------*
  2867. * CXMLVariant::Persist
  2868. *
  2869. * Persists a CXMLVariant to/from an XML persistor.
  2870. *--------------------------------------------------------------------------*/
  2871. #define ValNamePair(x) { x, L#x }
  2872. struct VARTYPE_MAP
  2873. {
  2874. VARENUM vt;
  2875. LPCWSTR pszName;
  2876. };
  2877. void CXMLVariant::Persist (CPersistor &persistor)
  2878. {
  2879. DECLARE_SC (sc, _T("CXMLVariant::Persist"));
  2880. static const VARTYPE_MAP TypeMap[] =
  2881. {
  2882. ValNamePair (VT_EMPTY),
  2883. ValNamePair (VT_NULL),
  2884. ValNamePair (VT_I2),
  2885. ValNamePair (VT_I4),
  2886. ValNamePair (VT_R4),
  2887. ValNamePair (VT_R8),
  2888. ValNamePair (VT_CY),
  2889. ValNamePair (VT_DATE),
  2890. ValNamePair (VT_BSTR),
  2891. ValNamePair (VT_ERROR),
  2892. // ValNamePair (VT_BOOL), VT_BOOL is handled as a special case
  2893. ValNamePair (VT_DECIMAL),
  2894. ValNamePair (VT_I1),
  2895. ValNamePair (VT_UI1),
  2896. ValNamePair (VT_UI2),
  2897. ValNamePair (VT_UI4),
  2898. ValNamePair (VT_INT),
  2899. ValNamePair (VT_UINT),
  2900. };
  2901. std::wstring strValue, strType;
  2902. /*
  2903. * storing?
  2904. */
  2905. if (persistor.IsStoring())
  2906. {
  2907. /*
  2908. * can't store variants that aren't "simple" (i.e. by-ref, array, etc.)
  2909. */
  2910. if (!IsPersistable())
  2911. (sc = E_FAIL).Throw();
  2912. /*
  2913. * special case for VT_BOOL
  2914. */
  2915. if (V_VT(this) == VT_BOOL)
  2916. {
  2917. strValue = (V_BOOL(this) == VARIANT_FALSE) ? L"False" : L"True";
  2918. strType = L"VT_BOOL";
  2919. }
  2920. else
  2921. {
  2922. /*
  2923. * we can only VARIANTs that can be converted to text
  2924. */
  2925. CComVariant varPersist;
  2926. sc = varPersist.ChangeType (VT_BSTR, this);
  2927. if (sc)
  2928. sc.Throw();
  2929. /*
  2930. * find the name for the type we're persisting
  2931. */
  2932. for (int i = 0; i < countof (TypeMap); i++)
  2933. {
  2934. if (V_VT(this) == TypeMap[i].vt)
  2935. break;
  2936. }
  2937. /*
  2938. * unrecognized type that's convertible to string?
  2939. */
  2940. if (i >= countof (TypeMap))
  2941. (sc = E_FAIL).Throw();
  2942. /*
  2943. * set the values that'll get saved
  2944. */
  2945. strValue = V_BSTR(&varPersist);
  2946. strType = TypeMap[i].pszName;
  2947. }
  2948. }
  2949. /*
  2950. * put to/get from the persistor
  2951. */
  2952. persistor.PersistAttribute (XML_ATTR_VARIANT_VALUE, strValue);
  2953. persistor.PersistAttribute (XML_ATTR_VARIANT_TYPE, strType);
  2954. /*
  2955. * loading?
  2956. */
  2957. if (persistor.IsLoading())
  2958. {
  2959. /*
  2960. * clear out the current contents
  2961. */
  2962. Clear();
  2963. /*
  2964. * special case for VT_BOOL
  2965. */
  2966. if (strType == L"VT_BOOL")
  2967. {
  2968. V_VT (this) = VT_BOOL;
  2969. V_BOOL(this) = (_wcsicmp (strValue.data(), L"False")) ? VARIANT_FALSE : VARIANT_TRUE;
  2970. }
  2971. else
  2972. {
  2973. /*
  2974. * find the VARIANT type in our map so we can convert back
  2975. * to the right type
  2976. */
  2977. for (int i = 0; i < countof (TypeMap); i++)
  2978. {
  2979. if (strType == TypeMap[i].pszName)
  2980. break;
  2981. }
  2982. /*
  2983. * unrecognized type that's convertible to string?
  2984. */
  2985. if (i >= countof (TypeMap))
  2986. (sc = E_FAIL).Throw();
  2987. /*
  2988. * convert from string back to the original type
  2989. */
  2990. CComVariant varPersisted (strValue.data());
  2991. sc = ChangeType (TypeMap[i].vt, &varPersisted);
  2992. if (sc)
  2993. sc.Throw();
  2994. }
  2995. }
  2996. }
  2997. /***************************************************************************\
  2998. *
  2999. * METHOD: CXMLEnumeration::ScReadFromBSTR
  3000. *
  3001. * PURPOSE: reads value from BSTR and evaluates (decodes) it
  3002. *
  3003. * PARAMETERS:
  3004. * const BSTR bstr - [in] string containing the value
  3005. *
  3006. * RETURNS:
  3007. * SC - result code
  3008. *
  3009. \***************************************************************************/
  3010. SC CXMLEnumeration::ScReadFromBSTR(const BSTR bstr)
  3011. {
  3012. DECLARE_SC(sc, TEXT("CXMLEnumeration::ScReadFromBSTR"));
  3013. // parameter check. (null BSTR is legal, but we do not support empty values either)
  3014. sc = ScCheckPointers(bstr);
  3015. if (sc)
  3016. return sc;
  3017. // convert to TSTRING
  3018. USES_CONVERSION;
  3019. LPCTSTR strInput = OLE2CT(bstr);
  3020. // find a match in the mapping array
  3021. for (size_t idx = 0; idx < m_count; idx ++)
  3022. {
  3023. if ( 0 == _tcscmp(strInput, m_pMaps[idx].m_literal) )
  3024. {
  3025. // found! set enum to proper value
  3026. m_rVal = static_cast<enum_t>(m_pMaps[idx].m_enum);
  3027. return sc;
  3028. }
  3029. }
  3030. // didn't find? - too bad
  3031. return sc = E_INVALIDARG;
  3032. }
  3033. /***************************************************************************\
  3034. *
  3035. * METHOD: CXMLEnumeration::ScWriteToBSTR
  3036. *
  3037. * PURPOSE: Strores (prints) value into BSTR to be used in XML document
  3038. *
  3039. * PARAMETERS:
  3040. * BSTR * pbstr [out] resulting string
  3041. *
  3042. * RETURNS:
  3043. * SC - result code
  3044. *
  3045. \***************************************************************************/
  3046. SC CXMLEnumeration::ScWriteToBSTR (BSTR * pbstr ) const
  3047. {
  3048. DECLARE_SC(sc, TEXT("CXMLEnumeration::ScWriteToBSTR"));
  3049. // parameter check
  3050. sc = ScCheckPointers(pbstr);
  3051. if (sc)
  3052. return sc;
  3053. // initialization
  3054. *pbstr = NULL;
  3055. // find string representation for enum
  3056. for (size_t idx = 0; idx < m_count; idx ++)
  3057. {
  3058. if ( m_pMaps[idx].m_enum == (UINT)m_rVal )
  3059. {
  3060. // found! - return it
  3061. *pbstr = CComBSTR(m_pMaps[idx].m_literal).Detach();
  3062. return sc;
  3063. }
  3064. }
  3065. // didn't find? - too bad
  3066. return sc = E_INVALIDARG;
  3067. }
  3068. /***************************************************************************\
  3069. *
  3070. * METHOD: CXMLBitFlags::PersistMultipleAttributes
  3071. *
  3072. * PURPOSE: perists bitflags as separate attributes. These are stored as
  3073. * attributes of the PARENT object, using the names specified in the
  3074. * name map. Any unknown flags are stored in an attribute
  3075. * specified by the name parameter, in numerical form.
  3076. *
  3077. * PARAMETERS:
  3078. * LPCTSTR name [in] flag name (used only for not recognized flags)
  3079. * CPersistor &persistor [in] persistor to perform operation on
  3080. *
  3081. * RETURNS:
  3082. * void
  3083. *
  3084. \***************************************************************************/
  3085. void CXMLBitFlags::PersistMultipleAttributes(LPCTSTR name, CPersistor &persistor)
  3086. {
  3087. // temporaries
  3088. UINT uiValToSave = persistor.IsStoring() ? m_rVal : 0;
  3089. UINT uiValLoaded = 0;
  3090. // iterate thru all the entries in the map
  3091. for (size_t idx = 0; idx < m_count; idx ++)
  3092. {
  3093. UINT uiMask = m_pMaps[idx].m_enum;
  3094. // we do only care about true flags - any nonzero value.
  3095. if (!uiMask)
  3096. continue;
  3097. // initialize the value properly for storing
  3098. // when loading (it will remain the same if attribute isn't found)
  3099. bool bValue = false;
  3100. if ( (uiValToSave & uiMask) == uiMask )
  3101. {
  3102. bValue = true;
  3103. uiValToSave &= ~uiMask; // since we have taken care of this, remove the bits.
  3104. // anything left over is saved numerically (see below)
  3105. }
  3106. // do not store "false" values - they are useless
  3107. bool bNeedsPersisting = persistor.IsLoading() || bValue;
  3108. if (bNeedsPersisting)
  3109. persistor.PersistAttribute( m_pMaps[idx].m_literal, CXMLBoolean(bValue), attr_optional );
  3110. uiValLoaded |= bValue ? uiMask : 0;
  3111. }
  3112. /* If there are any flags which do not have a corresponding text version,
  3113. these are persisted using the original name of the attribute, with the numerical
  3114. value of the flags*/
  3115. UINT uiValTheRest = uiValToSave;
  3116. bool bNeedsPersisting = persistor.IsLoading() || (uiValTheRest != 0);
  3117. if (bNeedsPersisting)
  3118. persistor.PersistAttribute( name, uiValTheRest, attr_optional );
  3119. uiValLoaded |= uiValTheRest;
  3120. if (persistor.IsLoading())
  3121. m_rVal = uiValLoaded;
  3122. }
  3123. /***************************************************************************\
  3124. *
  3125. * METHOD: CXMLBinary::CXMLBinary
  3126. *
  3127. * PURPOSE: default constructor
  3128. *
  3129. * PARAMETERS:
  3130. *
  3131. \***************************************************************************/
  3132. CXMLBinary::CXMLBinary() :
  3133. m_Handle(NULL),
  3134. m_Size(0),
  3135. m_Locks(0)
  3136. {
  3137. }
  3138. /***************************************************************************\
  3139. *
  3140. * METHOD: CXMLBinary::CXMLBinary
  3141. *
  3142. * PURPOSE: constructor
  3143. *
  3144. * PARAMETERS:
  3145. * HGLOBAL handle - handle to attach to
  3146. * size_t size - real size of data
  3147. *
  3148. \***************************************************************************/
  3149. CXMLBinary::CXMLBinary(HGLOBAL handle, size_t size) :
  3150. m_Handle(handle),
  3151. m_Size(size),
  3152. m_Locks(0)
  3153. {
  3154. }
  3155. /***************************************************************************\
  3156. *
  3157. * METHOD: CXMLBinary::Attach
  3158. *
  3159. * PURPOSE: Attaches object to allocated data. Will free the data it already has
  3160. *
  3161. * PARAMETERS:
  3162. * HGLOBAL handle - handle to attach to
  3163. * size_t size - real size of data
  3164. *
  3165. * RETURNS:
  3166. * void
  3167. *
  3168. \***************************************************************************/
  3169. void CXMLBinary::Attach(HGLOBAL handle, size_t size)
  3170. {
  3171. DECLARE_SC(sc, TEXT("CXMLBinary::Attach"));
  3172. sc = ScFree();
  3173. if (sc)
  3174. sc.TraceAndClear();
  3175. ASSERT(m_Handle == NULL && m_Size == 0 && m_Locks == 0);
  3176. m_Handle = handle;
  3177. m_Size = size;
  3178. }
  3179. /***************************************************************************\
  3180. *
  3181. * METHOD: CXMLBinary::Detach
  3182. *
  3183. * PURPOSE: transfers control to the caller
  3184. *
  3185. * PARAMETERS:
  3186. *
  3187. * RETURNS:
  3188. * HGLOBAL - handle of allocated memory
  3189. *
  3190. \***************************************************************************/
  3191. HGLOBAL CXMLBinary::Detach()
  3192. {
  3193. HGLOBAL ret = m_Handle;
  3194. m_Handle = NULL;
  3195. m_Size = 0;
  3196. m_Locks = 0;
  3197. return ret;
  3198. }
  3199. /***************************************************************************\
  3200. *
  3201. * METHOD: CXMLBinary::GetSize
  3202. *
  3203. * PURPOSE: returns the size of binary data
  3204. *
  3205. * PARAMETERS:
  3206. *
  3207. * RETURNS:
  3208. * size_t - size
  3209. *
  3210. \***************************************************************************/
  3211. size_t CXMLBinary::GetSize() const
  3212. {
  3213. return m_Size;
  3214. }
  3215. /***************************************************************************\
  3216. *
  3217. * METHOD: CXMLBinary::GetHandle
  3218. *
  3219. * PURPOSE: returns handle to allocated memory (NULL if size is zero)
  3220. *
  3221. * PARAMETERS:
  3222. *
  3223. * RETURNS:
  3224. * HGLOBAL - handle
  3225. *
  3226. \***************************************************************************/
  3227. HGLOBAL CXMLBinary::GetHandle() const
  3228. {
  3229. return m_Handle;
  3230. }
  3231. /***************************************************************************\
  3232. *
  3233. * METHOD: CXMLBinary::ScAlloc
  3234. *
  3235. * PURPOSE: allocates the memory for binary data. Previosly allocated date will
  3236. * be fred.
  3237. *
  3238. * NOTE: 0 in general is a valid size, GetHandle will return NULL in that case
  3239. * ScLock however will fail
  3240. *
  3241. * PARAMETERS:
  3242. * size_t size - new size of binary data
  3243. *
  3244. * RETURNS:
  3245. * SC - result code
  3246. *
  3247. \***************************************************************************/
  3248. SC CXMLBinary::ScAlloc(size_t size, bool fZeroInit /* =false */)
  3249. {
  3250. DECLARE_SC(sc, TEXT("CXMLBinary::ScAlloc"));
  3251. if (size == 0) // use ScFree to free the data
  3252. return sc = E_INVALIDARG;
  3253. sc = ScFree();
  3254. if (sc)
  3255. sc.TraceAndClear();
  3256. ASSERT(m_Handle == NULL && m_Size == 0 && m_Locks == 0);
  3257. DWORD dwFlags = GMEM_MOVEABLE;
  3258. if (fZeroInit)
  3259. dwFlags |= GMEM_ZEROINIT;
  3260. m_Handle = GlobalAlloc(dwFlags, size);
  3261. if (!m_Handle)
  3262. return sc.FromLastError(), sc;
  3263. m_Size = size;
  3264. return sc;
  3265. }
  3266. /***************************************************************************\
  3267. *
  3268. * METHOD: CXMLBinary::ScRealloc
  3269. *
  3270. * PURPOSE: reallocates the data. If data is present it will be coppied over
  3271. *
  3272. * PARAMETERS:
  3273. * size_t new_size - new binary data size
  3274. *
  3275. * RETURNS:
  3276. * SC - result code
  3277. *
  3278. \***************************************************************************/
  3279. SC CXMLBinary::ScRealloc(size_t new_size, bool fZeroInit /* =false */)
  3280. {
  3281. DECLARE_SC(sc, TEXT("CXMLBinary::ScRealloc"));
  3282. if (new_size == 0) // use ScFree to fre the data
  3283. return sc = E_INVALIDARG;
  3284. if (m_Size == 0) // use Alloc to allocate new data
  3285. return sc = E_UNEXPECTED;
  3286. ASSERT(m_Handle != NULL && m_Locks == 0);
  3287. if (m_Handle == NULL)
  3288. return sc = E_UNEXPECTED;
  3289. HGLOBAL hgNew = GlobalReAlloc(m_Handle, new_size, fZeroInit ? GMEM_ZEROINIT : 0);
  3290. if (!hgNew)
  3291. return sc.FromLastError(), sc;
  3292. m_Handle = hgNew;
  3293. m_Size = new_size;
  3294. m_Locks = 0;
  3295. return sc;
  3296. }
  3297. /***************************************************************************\
  3298. *
  3299. * METHOD: CXMLBinary::ScUnlock
  3300. *
  3301. * PURPOSE: Remove one lock from binary data
  3302. *
  3303. * PARAMETERS:
  3304. *
  3305. * RETURNS:
  3306. * SC - result code
  3307. *
  3308. \***************************************************************************/
  3309. SC CXMLBinary::ScUnlockData() const
  3310. {
  3311. DECLARE_SC(sc, TEXT("CXMLBinary::ScUnlockData()"));
  3312. ASSERT(m_Handle != NULL && m_Locks != 0);
  3313. if (!m_Locks || m_Handle == NULL)
  3314. return sc = E_UNEXPECTED;
  3315. GlobalUnlock(m_Handle);
  3316. --m_Locks;
  3317. return sc;
  3318. }
  3319. /***************************************************************************\
  3320. *
  3321. * METHOD: CXMLBinary::Free
  3322. *
  3323. * PURPOSE: Frees data asociated with the object
  3324. *
  3325. * PARAMETERS:
  3326. *
  3327. * RETURNS:
  3328. * void
  3329. *
  3330. \***************************************************************************/
  3331. SC CXMLBinary::ScFree()
  3332. {
  3333. DECLARE_SC(sc, TEXT("CXMLBinary::ScFree"));
  3334. while(m_Locks)
  3335. {
  3336. sc = ScUnlockData();
  3337. if (sc)
  3338. sc.TraceAndClear();
  3339. }
  3340. if (m_Handle)
  3341. GlobalFree(m_Handle);
  3342. Detach(); // null the handle, etc.
  3343. return sc;
  3344. }
  3345. /***************************************************************************\
  3346. *
  3347. * METHOD: CXMLBinary::ScLockData
  3348. *
  3349. * PURPOSE: Helper function used frol ScLock templates
  3350. *
  3351. * PARAMETERS:
  3352. * const void **ppData
  3353. *
  3354. * RETURNS:
  3355. * SC - result code
  3356. *
  3357. \***************************************************************************/
  3358. SC CXMLBinary::ScLockData(const void **ppData) const
  3359. {
  3360. DECLARE_SC(sc, TEXT("CXMLBinary::ScLockData"));
  3361. // paramter check
  3362. sc = ScCheckPointers(ppData);
  3363. if (sc)
  3364. return sc;
  3365. // initialization
  3366. *ppData = NULL;
  3367. // data allocated?
  3368. if (!m_Handle)
  3369. return sc = E_POINTER;
  3370. // lock
  3371. *ppData = GlobalLock(m_Handle);
  3372. // recheck
  3373. if (*ppData == NULL)
  3374. return sc.FromLastError(), sc;
  3375. ++m_Locks; // keep count of locks
  3376. return sc;
  3377. }
  3378. /***************************************************************************\
  3379. *
  3380. * METHOD: CXMLBinaryLock::CXMLBinaryLock
  3381. *
  3382. * PURPOSE: constructor
  3383. *
  3384. * PARAMETERS:
  3385. * CXMLBinary& binary - object to perform locking on
  3386. *
  3387. \***************************************************************************/
  3388. CXMLBinaryLock::CXMLBinaryLock(CXMLBinary& binary) :
  3389. m_rBinary(binary),
  3390. m_bLocked(false)
  3391. {
  3392. }
  3393. /***************************************************************************\
  3394. *
  3395. * METHOD: CXMLBinaryLock::~CXMLBinaryLock
  3396. *
  3397. * PURPOSE: destructor; also removes existing lock
  3398. *
  3399. * PARAMETERS:
  3400. *
  3401. \***************************************************************************/
  3402. CXMLBinaryLock::~CXMLBinaryLock()
  3403. {
  3404. DECLARE_SC(sc, TEXT("CXMLBinaryLock::~CXMLBinaryLock"));
  3405. if (m_bLocked)
  3406. {
  3407. sc = ScUnlock();
  3408. if (sc)
  3409. sc.TraceAndClear();
  3410. }
  3411. }
  3412. /***************************************************************************\
  3413. *
  3414. * METHOD: CXMLBinaryLock::ScLockWorker
  3415. *
  3416. * PURPOSE: type-insensitive lock method (helper)
  3417. *
  3418. * PARAMETERS:
  3419. * void **ppData - pointer to locked data
  3420. *
  3421. * RETURNS:
  3422. * SC - result code
  3423. *
  3424. \***************************************************************************/
  3425. SC CXMLBinaryLock::ScLockWorker(void **ppData)
  3426. {
  3427. DECLARE_SC(sc, TEXT("CXMLBinaryLock::ScLockWorker"));
  3428. if (m_bLocked)
  3429. return sc = E_UNEXPECTED;
  3430. sc = m_rBinary.ScLockData(reinterpret_cast<void**>(ppData));
  3431. if (sc)
  3432. return sc;
  3433. m_bLocked = true;
  3434. return sc;
  3435. }
  3436. /***************************************************************************\
  3437. *
  3438. * METHOD: CXMLBinaryLock::ScUnlock
  3439. *
  3440. * PURPOSE: removes the lock
  3441. *
  3442. * PARAMETERS:
  3443. *
  3444. * RETURNS:
  3445. * SC - result code
  3446. *
  3447. \***************************************************************************/
  3448. SC CXMLBinaryLock::ScUnlock()
  3449. {
  3450. DECLARE_SC(sc, TEXT("ScUnlock"));
  3451. if (!m_bLocked)
  3452. return sc = E_UNEXPECTED;
  3453. sc = m_rBinary.ScUnlockData();
  3454. if (sc)
  3455. return sc;
  3456. m_bLocked = false;
  3457. return sc;
  3458. }
  3459. /***************************************************************************\
  3460. *
  3461. * METHOD: ScGetConsoleFileChecksum
  3462. *
  3463. * PURPOSE: inspects the contents and validates if it looks like valid XML document
  3464. *
  3465. * PARAMETERS:
  3466. * LPCTSTR lpszPathName - [in] path to the document
  3467. * bool& bXmlBased - [out] true if file is xml based
  3468. * tstring& pstrFileCRC - [out] crc for the file
  3469. *
  3470. * RETURNS:
  3471. * SC - error or validation result (S_OK / S_FALSE)
  3472. *
  3473. \***************************************************************************/
  3474. SC ScGetConsoleFileChecksum(LPCTSTR lpszPathName, tstring& strFileCRC)
  3475. {
  3476. DECLARE_SC(sc, TEXT("ScGetConsoleFileChecksum"));
  3477. // parameter check
  3478. sc = ScCheckPointers(lpszPathName);
  3479. if (sc)
  3480. return sc;
  3481. // init out parameters;
  3482. strFileCRC.erase();
  3483. // open the file
  3484. CAutoWin32Handle shFile( CreateFile(lpszPathName, GENERIC_READ, FILE_SHARE_READ,
  3485. NULL, OPEN_EXISTING, 0, NULL) );
  3486. if ( !shFile.IsValid() )
  3487. return sc.FromLastError();
  3488. // we are sure here the sizeHi is zero. mapping should fail else
  3489. DWORD dwLenHi = 0;
  3490. DWORD dwLen = GetFileSize(shFile, &dwLenHi);
  3491. if ( dwLenHi != 0 )
  3492. return sc = E_OUTOFMEMORY;
  3493. // allocate memory for whole file
  3494. CAutoArrayPtr<BYTE> spData( new BYTE[dwLen] );
  3495. if ( spData == NULL )
  3496. return sc = E_OUTOFMEMORY;
  3497. // read the file into the memory
  3498. DWORD dwRead = 0;
  3499. if ( TRUE != ReadFile( shFile, spData, dwLen, &dwRead, NULL ) )
  3500. return sc.FromLastError();
  3501. // assert all the data was read
  3502. if ( dwRead != dwLen )
  3503. return sc = E_UNEXPECTED;
  3504. // calculate the crc
  3505. ULONG init_crc = 0; /*initial crc - do not change this, or you will have different
  3506. checksums calculated - thus existing user data discarded */
  3507. ULONG crc = crc32( init_crc, spData, dwLen );
  3508. // convert
  3509. TCHAR buff[20] = {0};
  3510. strFileCRC = _ultot(crc, buff, 10 /*radix*/);
  3511. // done
  3512. return sc;
  3513. }
  3514. /***************************************************************************\
  3515. *
  3516. * METHOD: CConsoleFilePersistor::ScOpenDocAsStructuredStorage
  3517. *
  3518. * PURPOSE: Opens the file and reads the contents into the memory
  3519. * returns the pointer to memory based IStorage
  3520. *
  3521. * PARAMETERS:
  3522. * LPCTSTR lpszPathName [in] - file name
  3523. * IStorage **ppStorage [out] - pointer to IStorage
  3524. *
  3525. * RETURNS:
  3526. * SC - result code
  3527. *
  3528. \***************************************************************************/
  3529. SC CConsoleFilePersistor::ScOpenDocAsStructuredStorage(LPCTSTR lpszPathName, IStorage **ppStorage)
  3530. {
  3531. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScOpenDocAsStructuredStorage"));
  3532. // check out parameter
  3533. sc = ScCheckPointers(ppStorage);
  3534. if (sc)
  3535. return sc;
  3536. // init out parameter
  3537. *ppStorage = NULL;
  3538. // check in parameter
  3539. sc = ScCheckPointers(lpszPathName);
  3540. if (sc)
  3541. return sc;
  3542. CAutoWin32Handle hFile(CreateFile(lpszPathName, GENERIC_READ, FILE_SHARE_READ,
  3543. NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
  3544. if (!hFile.IsValid())
  3545. return sc.FromLastError();
  3546. // get file data
  3547. ULARGE_INTEGER cbFileSize;
  3548. cbFileSize.LowPart = GetFileSize(hFile, &cbFileSize.HighPart);
  3549. // will not handle files bigger than 2Gb
  3550. if (cbFileSize.HighPart)
  3551. return E_UNEXPECTED;
  3552. // alocate memory blob and read the data
  3553. CXMLAutoBinary binData;
  3554. if (cbFileSize.LowPart)
  3555. {
  3556. // allocate
  3557. sc = binData.ScAlloc(cbFileSize.LowPart);
  3558. if (sc)
  3559. return sc;
  3560. // get pointer to data
  3561. CXMLBinaryLock lock(binData);
  3562. BYTE *pData = NULL;
  3563. sc = lock.ScLock(&pData);
  3564. if (sc)
  3565. return sc;
  3566. // read file contents
  3567. DWORD dwBytesRead = 0;
  3568. BOOL bOK = ReadFile(hFile, pData, cbFileSize.LowPart, &dwBytesRead, NULL);
  3569. if (!bOK)
  3570. return sc.FromLastError();
  3571. else if (cbFileSize.LowPart != dwBytesRead)
  3572. return sc = E_UNEXPECTED;
  3573. }
  3574. // create lockbytes
  3575. ILockBytesPtr spLockBytes;
  3576. sc = CreateILockBytesOnHGlobal(binData.GetHandle(), TRUE, &spLockBytes);
  3577. if(sc)
  3578. return sc;
  3579. // ILockBytes took control over HGLOBAL block, detach from it
  3580. binData.Detach();
  3581. // set correct size for data
  3582. sc = spLockBytes->SetSize(cbFileSize);
  3583. if(sc)
  3584. return sc;
  3585. // ask ole to open storage for client
  3586. const DWORD grfMode = STGM_DIRECT | STGM_SHARE_EXCLUSIVE | STGM_READWRITE;
  3587. sc = StgOpenStorageOnILockBytes(spLockBytes, NULL, grfMode, NULL, 0, ppStorage);
  3588. if(sc)
  3589. return sc;
  3590. // done...
  3591. return sc;
  3592. }
  3593. /***************************************************************************\
  3594. *
  3595. * METHOD: CConsoleFilePersistor::ScGetUserDataFolder
  3596. *
  3597. * PURPOSE: Calculates location (dir) for user data folder
  3598. *
  3599. * PARAMETERS:
  3600. * tstring& strUserDataFolder [out] - user data folder path
  3601. * * for instance 'E:\Documents and Settings\John\Application Data\Microsoft\MMC' *
  3602. *
  3603. * RETURNS:
  3604. * SC - result code
  3605. *
  3606. \***************************************************************************/
  3607. SC CConsoleFilePersistor::ScGetUserDataFolder(tstring& strUserDataFolder)
  3608. {
  3609. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScGetUserDataFolder"));
  3610. // init out parameter
  3611. strUserDataFolder.erase();
  3612. // get owner for error boxes
  3613. HWND hwndOwner = IsWindowVisible(sc.GetHWnd()) ? sc.GetHWnd() : NULL;
  3614. // get shell folder
  3615. TCHAR szFolderPath[_MAX_PATH] = {0};
  3616. BOOL bOK = SHGetSpecialFolderPath(hwndOwner, szFolderPath, CSIDL_APPDATA, TRUE/*fCreate*/);
  3617. if ( !bOK )
  3618. return sc = E_FAIL;
  3619. // return the path;
  3620. strUserDataFolder = szFolderPath;
  3621. strUserDataFolder += _T('\\');
  3622. strUserDataFolder += g_szUserDataSubFolder;
  3623. return sc;
  3624. }
  3625. /***************************************************************************\
  3626. *
  3627. * METHOD: CConsoleFilePersistor::ScGetUserDataPath
  3628. *
  3629. * PURPOSE: Calculates location (dir) for user data file by given original console path
  3630. *
  3631. * PARAMETERS:
  3632. * LPCTSTR lpstrOriginalPath [in] - original console path
  3633. * * for instance 'c:\my consoles\my_tool.msc' *
  3634. * tstring& strUserDataPath [out] - user data file path
  3635. * * for instance 'E:\Documents and Settings\John\Application Data\Microsoft\MMC\my_tool.msc' *
  3636. *
  3637. * RETURNS:
  3638. * SC - result code
  3639. *
  3640. \***************************************************************************/
  3641. SC CConsoleFilePersistor::ScGetUserDataPath(LPCTSTR lpstrOriginalPath, tstring& strUserDataPath)
  3642. {
  3643. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScGetUserDataPath"));
  3644. // parameter check
  3645. sc = ScCheckPointers(lpstrOriginalPath);
  3646. if ( sc )
  3647. return sc;
  3648. // init out parameter
  3649. strUserDataPath.erase();
  3650. // get only the filename from the path
  3651. LPCTSTR lpstrOriginalFileName = _tcsrchr( lpstrOriginalPath, _T('\\') );
  3652. if ( lpstrOriginalFileName == NULL )
  3653. lpstrOriginalFileName = lpstrOriginalPath;
  3654. else
  3655. ++lpstrOriginalFileName;
  3656. // skip whitespaces
  3657. while ( *lpstrOriginalFileName && _istspace(*lpstrOriginalFileName) )
  3658. ++lpstrOriginalFileName;
  3659. // check if the name is non-empty
  3660. if ( !*lpstrOriginalFileName )
  3661. return sc = E_INVALIDARG;
  3662. // get folder
  3663. sc = ScGetUserDataFolder(strUserDataPath);
  3664. if (sc)
  3665. return sc;
  3666. // ensure mmc folder exists
  3667. DWORD dwFileAtts = ::GetFileAttributes( strUserDataPath.c_str() );
  3668. if ( 0 == ( dwFileAtts & FILE_ATTRIBUTE_DIRECTORY ) || (DWORD)-1 == dwFileAtts )
  3669. {
  3670. // create the directory
  3671. if ( !CreateDirectory( strUserDataPath.c_str(), NULL ) )
  3672. return sc.FromLastError();
  3673. }
  3674. // get the length of the file
  3675. int iFileNameLen = _tcslen( lpstrOriginalFileName );
  3676. int iConsoleExtensionLen = _tcslen( g_szDEFAULT_CONSOLE_EXTENSION );
  3677. // subtract 'msc' extension if such was added
  3678. if ( iFileNameLen > iConsoleExtensionLen )
  3679. {
  3680. if ( 0 == _tcsicmp( g_szDEFAULT_CONSOLE_EXTENSION, lpstrOriginalFileName + iFileNameLen - iConsoleExtensionLen ) )
  3681. {
  3682. iFileNameLen -= (iConsoleExtensionLen - 1); // will add the dot to prevent assumming the different extension
  3683. // so that a.b.msc won't have b extension after msc is removed
  3684. }
  3685. }
  3686. strUserDataPath += _T('\\');
  3687. strUserDataPath.append( lpstrOriginalFileName, iFileNameLen ); // excludes .msc extension
  3688. return sc;
  3689. }
  3690. /*+-------------------------------------------------------------------------*
  3691. *
  3692. * CConsoleFilePersistor::GetBinaryCollection
  3693. *
  3694. * PURPOSE: Returns a handle to the collection of Binary elements in the specified
  3695. * document
  3696. *
  3697. * PARAMETERS:
  3698. * CXMLDocument& xmlDocument : [in]: the specified console file document
  3699. * CXMLElementCollection& colBinary : [out]: the collection
  3700. *
  3701. * RETURNS:
  3702. * void
  3703. *
  3704. *+-------------------------------------------------------------------------*/
  3705. void
  3706. CConsoleFilePersistor::GetBinaryCollection(CXMLDocument& xmlDocument, CXMLElementCollection& colBinary)
  3707. {
  3708. // get the root elements of the source and the destination documents
  3709. CPersistor persistorRoot (xmlDocument, CXMLElement(xmlDocument ));
  3710. // set the navigation to loading
  3711. persistorRoot.SetLoading(true);
  3712. // navigate to the MMC_ConsoleFile node
  3713. CPersistor persistorConsole (persistorRoot, XML_TAG_MMC_CONSOLE_FILE);
  3714. // navigate to the binary storage node
  3715. CPersistor persistorBinaryStorage (persistorConsole, XML_TAG_BINARY_STORAGE);
  3716. // get the collection of binary objects
  3717. persistorBinaryStorage .GetCurrentElement().getChildrenByName(XML_TAG_BINARY, &colBinary);
  3718. }
  3719. /*+-------------------------------------------------------------------------*
  3720. *
  3721. * CompareStrings
  3722. *
  3723. * PURPOSE: Does a whitespace-insensitive, but case-SENSITIVE comparison
  3724. * of the two strings.
  3725. *
  3726. * PARAMETERS:
  3727. * CComBSTR& bstr1 :
  3728. * CComBSTR & bstr2 :
  3729. *
  3730. * RETURNS:
  3731. * static bool : true if match. else false
  3732. *
  3733. *+-------------------------------------------------------------------------*/
  3734. static bool
  3735. CompareStrings(CComBSTR& bstr1, CComBSTR &bstr2)
  3736. {
  3737. UINT length1 = bstr1.Length();
  3738. UINT length2 = bstr2.Length();
  3739. // the current indexes
  3740. UINT i1 = 0;
  3741. UINT i2 = 0;
  3742. bool bEnd1 = false; // is the first string over?
  3743. bool bEnd2 = false; // is the second string over?
  3744. BSTR sz1 = bstr1;
  3745. BSTR sz2 = bstr2;
  3746. // either both should be null or neither should be
  3747. if( (NULL == sz1) && (NULL==sz2) )
  3748. return true;
  3749. if( (NULL == sz1) || (NULL==sz2) )
  3750. return false;
  3751. // compare the strings
  3752. while( (!bEnd1) || (!bEnd2) )
  3753. {
  3754. WCHAR ch1 = sz1[i1];
  3755. WCHAR ch2 = sz2[i2];
  3756. // 1. get the next non-whitespace char of the first string
  3757. if (i1 == length1)
  3758. bEnd1 = true;
  3759. else
  3760. {
  3761. if(iswspace(ch1))
  3762. {
  3763. ++i1;
  3764. continue;
  3765. }
  3766. }
  3767. // 2. get the next non-whitespace char of the second string
  3768. if (i2 == length2)
  3769. bEnd2 = true;
  3770. else
  3771. {
  3772. if(iswspace(ch2))
  3773. {
  3774. ++i2;
  3775. continue;
  3776. }
  3777. }
  3778. // 3. if either of the strings have ended, break. Taken care of below.
  3779. if(bEnd1 || bEnd2)
  3780. break;
  3781. // 4. compare the characters (must be a case sensitive comparison)
  3782. if(ch1 != ch2)
  3783. return false;
  3784. // 5. increment the counters
  3785. ++i1;
  3786. ++i2;
  3787. }
  3788. // both strings should have ended together for a match
  3789. if(bEnd1 && bEnd2)
  3790. return true;
  3791. return false;
  3792. }
  3793. /*+-------------------------------------------------------------------------*
  3794. *
  3795. * CConsoleFilePersistor::ScCompressUserStateFile
  3796. *
  3797. * PURPOSE: Compresses the user-state console file to avoid redundancies. Most of a
  3798. * console file's size is in the binary elements. These are also usually the
  3799. * least likely to change in user mode. For instance, the console file icons
  3800. * and console task icons cannot be changed in user mode.
  3801. *
  3802. * Therefore, the compression algorithm iterates through all <BINARY> elements
  3803. * in the user state file, and looks for matches in the original console file.
  3804. * If a <BINARY> element has the same contents as a <BINARY> element in the
  3805. * original console file, the contents are replaced by a SourceIndex attribute
  3806. * that gives the index of the matching <BINARY> element in the source.
  3807. * This usually results in a >80% reduction of user state file size.
  3808. *
  3809. * PARAMETERS:
  3810. * LPCTSTR szConsoleFilePath : [IN]: the (authored) console file path
  3811. * CXMLDocument & xmlDocument : [IN/OUT]: The user state document, which is compressed
  3812. *
  3813. * RETURNS:
  3814. * static SC
  3815. *
  3816. *+-------------------------------------------------------------------------*/
  3817. SC
  3818. CConsoleFilePersistor::ScCompressUserStateFile(LPCTSTR szConsoleFilePath, CXMLDocument & xmlDocument)
  3819. {
  3820. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScCompressUserStateFile"));
  3821. sc = ScCheckPointers(szConsoleFilePath);
  3822. if(sc)
  3823. return sc;
  3824. CXMLDocument xmlDocumentOriginal; // the original file
  3825. sc = xmlDocumentOriginal.ScCoCreate( false/*bPutHeader*/ ); // initialize it.
  3826. if(sc)
  3827. return sc;
  3828. sc = /*CConsoleFilePersistor::*/ScLoadXMLDocumentFromFile(xmlDocumentOriginal, szConsoleFilePath, true /*bSilentOnErrors*/);
  3829. if(sc)
  3830. {
  3831. // ignore the error - this just means that original console is not
  3832. // an XML based - we are not able to compress it - not an error
  3833. sc.Clear();
  3834. return sc;
  3835. }
  3836. try
  3837. {
  3838. // get the collection of Binary tags
  3839. CXMLElementCollection colBinaryOrignal, colBinary;
  3840. GetBinaryCollection(xmlDocumentOriginal, colBinaryOrignal);
  3841. GetBinaryCollection(xmlDocument, colBinary);
  3842. long cItemsOriginal = 0;
  3843. long cItems = 0;
  3844. colBinaryOrignal.get_count(&cItemsOriginal);
  3845. colBinary .get_count(&cItems);
  3846. // look for matches
  3847. for(int i = 0; i< cItems; i++)
  3848. {
  3849. CXMLElement elemBinary = NULL;
  3850. colBinary.item(i, &elemBinary); // get the i'th Binary element in the dest. file
  3851. CComBSTR bstrBinary;
  3852. elemBinary.get_text(bstrBinary);
  3853. for(int j = 0; j< cItemsOriginal; j++)
  3854. {
  3855. CXMLElement elemBinaryOriginal = NULL;
  3856. colBinaryOrignal.item(j, &elemBinaryOriginal); // get the j'th Binary element in the dest. file
  3857. CComBSTR bstrBinaryOriginal;
  3858. elemBinaryOriginal.get_text(bstrBinaryOriginal);
  3859. // compare
  3860. if(CompareStrings(bstrBinaryOriginal, bstrBinary))
  3861. {
  3862. // yahoo!! compress.
  3863. Trace(tagXMLCompression, TEXT("Found match!"));
  3864. // 1. nuke the contents
  3865. elemBinary.put_text(NULL); // NULL is a valid value for a BSTR
  3866. CStr strValue;
  3867. strValue.Format(TEXT("%d"), j);
  3868. // 2. set the contents
  3869. elemBinary.setAttribute(XML_ATTR_SOURCE_INDEX, CComBSTR(strValue));
  3870. // done.
  3871. break;
  3872. }
  3873. }
  3874. }
  3875. }
  3876. catch(SC sc_thrown)
  3877. {
  3878. return sc = sc_thrown;
  3879. }
  3880. return sc;
  3881. }
  3882. /*+-------------------------------------------------------------------------*
  3883. *
  3884. * CConsoleFilePersistor::ScUncompressUserStateFile
  3885. *
  3886. * PURPOSE: Uncompresses user data files that were compressed by ScCompressUserStateFile.
  3887. * Applies the compression algorithm in reverse.
  3888. *
  3889. * PARAMETERS:
  3890. * CXMLDocument & xmlDocumentOriginal :
  3891. * CXMLDocument& xmlDocument :
  3892. *
  3893. * RETURNS:
  3894. * SC
  3895. *
  3896. *+-------------------------------------------------------------------------*/
  3897. SC
  3898. CConsoleFilePersistor::ScUncompressUserStateFile(CXMLDocument &xmlDocumentOriginal, CXMLDocument& xmlDocument)
  3899. {
  3900. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScUncompressUserStateFile"));
  3901. try
  3902. {
  3903. // get the collection of Binary tags
  3904. CXMLElementCollection colBinaryOrignal, colBinary;
  3905. GetBinaryCollection(xmlDocumentOriginal, colBinaryOrignal);
  3906. GetBinaryCollection(xmlDocument, colBinary);
  3907. long cItems = 0;
  3908. colBinary .get_count(&cItems);
  3909. // decompress each item in colBinary
  3910. for(int i = 0; i< cItems; i++)
  3911. {
  3912. CXMLElement elemBinary = NULL;
  3913. colBinary.item(i, &elemBinary); // get the i'th Binary element in the dest. file
  3914. CComBSTR bstrSourceIndex;
  3915. if(elemBinary.getAttribute(XML_ATTR_SOURCE_INDEX, bstrSourceIndex))
  3916. {
  3917. int j = _wtoi(bstrSourceIndex);
  3918. CXMLElement elemBinaryOriginal;
  3919. colBinaryOrignal.item(j, &elemBinaryOriginal); // get the j'th Binary element in the dest. file
  3920. CComBSTR bstrBinaryOriginal;
  3921. elemBinaryOriginal.get_text(bstrBinaryOriginal);
  3922. // replace the destination binary contents (which should be empty) with the original.
  3923. elemBinary.put_text(bstrBinaryOriginal);
  3924. // don't need to delete the SourceIndex attribute because the xmlDocument is thrown away after reading it in.
  3925. }
  3926. }
  3927. }
  3928. catch(SC sc_thrown)
  3929. {
  3930. return sc = sc_thrown;
  3931. }
  3932. return sc;
  3933. }
  3934. /***************************************************************************\
  3935. *
  3936. * METHOD: CConsoleFilePersistor::ScLoadConsole
  3937. *
  3938. * PURPOSE: Loads the mmc console from file
  3939. *
  3940. * PARAMETERS:
  3941. * LPCTSTR lpstrConsolePath [in] path, where the console resides.
  3942. * bool& bXmlBased [out] whether document is XML-based
  3943. * CXMLDocument& xmlDocument [out] xmlDocument containing data (only if xml-Based)
  3944. * IStorage **ppStorage [out] storage containing data(only if non xml-Based)
  3945. *
  3946. * RETURNS:
  3947. * SC - result code
  3948. *
  3949. \***************************************************************************/
  3950. SC CConsoleFilePersistor::ScLoadConsole(LPCTSTR lpstrConsolePath, bool& bXmlBased,
  3951. CXMLDocument& xmlDocument, IStorage **ppStorage)
  3952. {
  3953. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScLoadConsole"));
  3954. // parameter check
  3955. sc = ScCheckPointers(lpstrConsolePath, ppStorage);
  3956. if (sc)
  3957. return sc;
  3958. // init out parameters
  3959. bXmlBased = false;
  3960. *ppStorage = NULL;
  3961. // Create an empty XML document
  3962. CXMLDocument xmlOriginalDoc;
  3963. sc = xmlOriginalDoc.ScCoCreate(false/*bPutHeader*/);
  3964. if(sc)
  3965. return sc;
  3966. // inspect original console file by trying to load XML document
  3967. bool bOriginalXmlBased = false;
  3968. sc = ScLoadXMLDocumentFromFile(xmlOriginalDoc, lpstrConsolePath, true /*bSilentOnErrors*/);
  3969. if( !sc.IsError() )
  3970. bOriginalXmlBased = true;
  3971. sc.Clear(); // ignore the error - assume it is not XML based
  3972. // test it is not a user data which is being opened - cannot be so!
  3973. if ( bOriginalXmlBased )
  3974. {
  3975. try
  3976. {
  3977. // construct persistor
  3978. CPersistor persistor(xmlOriginalDoc, CXMLElement(xmlOriginalDoc));
  3979. persistor.SetLoading(true);
  3980. // navigate to CRC storage
  3981. CPersistor persistorConsole( persistor, XML_TAG_MMC_CONSOLE_FILE );
  3982. if ( persistorConsole.HasElement(XML_TAG_ORIGINAL_CONSOLE_CRC, NULL) )
  3983. return sc = E_UNEXPECTED;
  3984. }
  3985. catch(SC sc_thrown)
  3986. {
  3987. return sc = sc_thrown;
  3988. }
  3989. }
  3990. tstring strFileCRC;
  3991. sc = ScGetConsoleFileChecksum( lpstrConsolePath, strFileCRC );
  3992. if (sc)
  3993. return sc;
  3994. // store data to be used for saving
  3995. m_strFileCRC = strFileCRC;
  3996. m_bCRCValid = true;
  3997. // get the path to user data
  3998. tstring strUserDataPath;
  3999. sc = ScGetUserDataPath( lpstrConsolePath, strUserDataPath);
  4000. if (sc)
  4001. {
  4002. // don't fail - trace only - missing user data not a reason to fail loading
  4003. sc.TraceAndClear();
  4004. }
  4005. // go get the user data
  4006. bool bValidUserData = false;
  4007. sc = ScGetUserData( strUserDataPath, strFileCRC, bValidUserData, xmlDocument );
  4008. if (sc)
  4009. {
  4010. // don't fail - trace only - missing user data not a reason to fail loading
  4011. bValidUserData = false;
  4012. sc.TraceAndClear();
  4013. }
  4014. // user data loaded?
  4015. if (bValidUserData)
  4016. {
  4017. // uncompress the user data if the original was XML
  4018. if(bOriginalXmlBased)
  4019. {
  4020. sc = ScUncompressUserStateFile(xmlOriginalDoc, xmlDocument);
  4021. if(sc)
  4022. return sc;
  4023. }
  4024. // done, just return the staff
  4025. bXmlBased = true; // user data always is XML
  4026. // pxmlDocument is already updated by ScGetUserData
  4027. return sc;
  4028. }
  4029. // no luck with user data, lets load the original file
  4030. // XML contents
  4031. if ( bOriginalXmlBased )
  4032. {
  4033. // return the data
  4034. bXmlBased = true;
  4035. xmlDocument = xmlOriginalDoc;
  4036. return sc;
  4037. }
  4038. // old, ole-storage based file:
  4039. sc = ScOpenDocAsStructuredStorage( lpstrConsolePath, ppStorage );
  4040. if (sc)
  4041. return sc;
  4042. return sc;
  4043. }
  4044. /***************************************************************************\
  4045. *
  4046. * METHOD: CConsoleFilePersistor::ScGetUserData
  4047. *
  4048. * PURPOSE: inspects if user data matches console file, loads the xml document if it does
  4049. *
  4050. * PARAMETERS:
  4051. * tstring& strUserDataConsolePath [in] - path to the user data
  4052. * const tstring& strFileCRC, [in] - crc of original console file
  4053. * bool& bValid [out] - if user data is valid
  4054. * CXMLDocument& xmlDocument [out] - loaded document (only if valid)
  4055. *
  4056. * RETURNS:
  4057. * SC - result code
  4058. *
  4059. \***************************************************************************/
  4060. SC CConsoleFilePersistor::ScGetUserData(const tstring& strUserDataConsolePath, const tstring& strFileCRC,
  4061. bool& bValid, CXMLDocument& xmlDocument)
  4062. {
  4063. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScGetUserData"));
  4064. // assume invalid initially
  4065. bValid = false;
  4066. // check if user file exist
  4067. DWORD dwFileAtts = ::GetFileAttributes( strUserDataConsolePath.c_str() );
  4068. // if file is missing dwFileAtts will be -1, so bValidUserData will be eq. to false
  4069. bool bValidUserData = ( ( dwFileAtts & FILE_ATTRIBUTE_DIRECTORY ) == 0 );
  4070. if ( !bValidUserData )
  4071. return sc;
  4072. // Create an empty XML document
  4073. CXMLDocument xmlDoc;
  4074. sc = xmlDoc.ScCoCreate( false/*bPutHeader*/ );
  4075. if(sc)
  4076. return sc;
  4077. // upload the data
  4078. sc = ScLoadXMLDocumentFromFile( xmlDoc, strUserDataConsolePath.c_str() );
  4079. if(sc)
  4080. return sc;
  4081. // get the CRC
  4082. try
  4083. {
  4084. CPersistor persistor(xmlDoc, CXMLElement(xmlDoc));
  4085. persistor.SetLoading(true);
  4086. // navigate to CRC storage
  4087. CPersistor persistorConsole( persistor, XML_TAG_MMC_CONSOLE_FILE );
  4088. CPersistor persistorCRC( persistorConsole, XML_TAG_ORIGINAL_CONSOLE_CRC );
  4089. tstring strCRC;
  4090. persistorCRC.PersistContents(strCRC);
  4091. // valid if CRC matches
  4092. if ( strCRC == strFileCRC )
  4093. {
  4094. // return the document
  4095. bValid = true;
  4096. xmlDocument = xmlDoc;
  4097. }
  4098. }
  4099. catch(SC sc_thrown)
  4100. {
  4101. return sc = sc_thrown;
  4102. }
  4103. return sc;
  4104. }
  4105. /***************************************************************************\
  4106. *
  4107. * METHOD: CConsoleFilePersistor::ScSaveConsole
  4108. *
  4109. * PURPOSE: Saves console to file
  4110. *
  4111. * PARAMETERS:
  4112. * LPCTSTR lpstrConsolePath [in] - console file path
  4113. * bool bForAuthorMode [in] - if console was authored
  4114. * const CXMLDocument& xmlDocument [in] - document conatining data to be saved
  4115. *
  4116. * RETURNS:
  4117. * SC - result code
  4118. *
  4119. \***************************************************************************/
  4120. SC CConsoleFilePersistor::ScSaveConsole(LPCTSTR lpstrConsolePath, bool bForAuthorMode, const CXMLDocument& xmlDocument)
  4121. {
  4122. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScSaveConsole"));
  4123. // parameter check
  4124. sc = ScCheckPointers( lpstrConsolePath );
  4125. if (sc)
  4126. return sc;
  4127. // sanity check - if saving in user mode, have to be loaded from file.
  4128. // To save in user mode CRC of the original document must be known.
  4129. // It is calculated on loading, but seems like loading was never done.
  4130. if ( !bForAuthorMode && !m_bCRCValid )
  4131. return sc = E_UNEXPECTED;
  4132. // prepare data for save
  4133. tstring strDestinationFile( lpstrConsolePath );
  4134. CXMLDocument xmlDocumentToSave( xmlDocument );
  4135. // need to modify slightly if saving just the user data
  4136. if ( !bForAuthorMode )
  4137. {
  4138. // get user data file path
  4139. sc = ScGetUserDataPath( lpstrConsolePath, strDestinationFile );
  4140. if (sc)
  4141. return sc;
  4142. // optimize the file to be saved, to remove redundancies
  4143. sc = ScCompressUserStateFile(lpstrConsolePath, xmlDocumentToSave);
  4144. if(sc)
  4145. return sc;
  4146. // add crc to the document
  4147. try
  4148. {
  4149. CPersistor persistor(xmlDocumentToSave, CXMLElement(xmlDocumentToSave));
  4150. persistor.SetLoading(true); // navigate like 'loading'
  4151. // navigate to CRC storage
  4152. CPersistor persistorConsole( persistor, XML_TAG_MMC_CONSOLE_FILE );
  4153. // create the crc record
  4154. persistorConsole.SetLoading(false);
  4155. CPersistor persistorCRC( persistorConsole, XML_TAG_ORIGINAL_CONSOLE_CRC );
  4156. // save data
  4157. persistorCRC.PersistContents( m_strFileCRC );
  4158. }
  4159. catch(SC sc_thrown)
  4160. {
  4161. return sc = sc_thrown;
  4162. }
  4163. }
  4164. // save document contents
  4165. sc = xmlDocumentToSave.ScSaveToFile( strDestinationFile.c_str() );
  4166. if (sc)
  4167. return sc;
  4168. return sc;
  4169. }
  4170. /***************************************************************************\
  4171. *
  4172. * METHOD: CConsoleFilePersistor::ScLoadXMLDocumentFromFile
  4173. *
  4174. * PURPOSE: reads CXMLDocument contents from file
  4175. *
  4176. * PARAMETERS:
  4177. * CXMLDocument& xmlDocument [out] document to be receive contents
  4178. * LPCTSTR szFileName [in] source file name
  4179. * bool bSilentOnErrors [in] if true - does not trace opennning errors
  4180. *
  4181. * RETURNS:
  4182. * SC - result code
  4183. *
  4184. \***************************************************************************/
  4185. SC CConsoleFilePersistor::ScLoadXMLDocumentFromFile(CXMLDocument& xmlDocument, LPCTSTR szFileName, bool bSilentOnErrors /*= false*/)
  4186. {
  4187. DECLARE_SC(sc, TEXT("CConsoleFilePersistor::ScLoadXMLDocumentFromFile"));
  4188. // read data
  4189. CXMLAutoBinary binData;
  4190. sc = ScReadDataFromFile(szFileName, &binData);
  4191. if (sc)
  4192. return sc;
  4193. // create stream - NOTE it will take care of HGLOBAL if succeeds
  4194. IStreamPtr spStream;
  4195. sc = CreateStreamOnHGlobal(binData.GetHandle(), TRUE, &spStream);
  4196. if (sc)
  4197. return sc;
  4198. const ULARGE_INTEGER new_size = { binData.GetSize(), 0 };
  4199. binData.Detach(); // not the owner anymore (IStream took ownership)
  4200. sc = ScCheckPointers(spStream, E_UNEXPECTED);
  4201. if (sc)
  4202. return sc;
  4203. sc = spStream->SetSize(new_size);
  4204. if (sc)
  4205. return sc;
  4206. // load data (do not trace by default - it is used to inspect the document as well)
  4207. SC sc_no_trace = xmlDocument.ScLoad(spStream, bSilentOnErrors);
  4208. if(sc_no_trace)
  4209. {
  4210. if ( !bSilentOnErrors )
  4211. sc = sc_no_trace;
  4212. return sc_no_trace;
  4213. }
  4214. return sc;
  4215. }