PageRenderTime 67ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/Migration/exportsqlce/Generator/DataContextHelper.cs

http://elab.codeplex.com
C# | 763 lines | 707 code | 47 blank | 9 comment | 30 complexity | 787bf2c065d40229bdb6f6d8e6de0370 MD5 | raw file
Possible License(s): Apache-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using ErikEJ.SqlCeScripting;
  6. using System.Diagnostics;
  7. using System.IO;
  8. namespace ErikEJ.SqlCeScripting
  9. {
  10. public class DataContextHelper
  11. {
  12. private StringBuilder _sbResult = new StringBuilder();
  13. public void GenerateWPDataContext(IRepository repository, string connectionString, string dcPath)
  14. {
  15. if (dcPath.ToUpperInvariant().EndsWith(".CS") || dcPath.ToUpperInvariant().EndsWith(".VB"))
  16. { }
  17. else
  18. {
  19. throw new Exception("DataContext file name must end with either .cs or .vb");
  20. }
  21. string sqlMetalPath = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\WinSDK-NetFx40Tools", "InstallationFolder", null);
  22. if (sqlMetalPath == null)
  23. {
  24. throw new Exception("Could not find SQLMetal location in registry");
  25. }
  26. sqlMetalPath = Path.Combine(sqlMetalPath, "sqlmetal.exe");
  27. if (!File.Exists(sqlMetalPath))
  28. {
  29. throw new Exception("Could not find SqlMetal in the expected location: " + sqlMetalPath);
  30. }
  31. string model = Path.GetFileNameWithoutExtension(dcPath).Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty);
  32. model = model + "Context";
  33. string parameters = " /provider:SQLCompact /code:\"" + dcPath + "\"";
  34. parameters += " /conn:\"" + connectionString + "\"";
  35. parameters += " /context:" + model;
  36. parameters += " /pluralize";
  37. string sqlmetalResult = RunSqlMetal(sqlMetalPath, parameters);
  38. if (!File.Exists(dcPath))
  39. {
  40. throw new Exception("Error during SQL Metal run: " + sqlmetalResult);
  41. }
  42. string sdfFileName = string.Empty;
  43. List<KeyValuePair<string, string>> dbInfo = repository.GetDatabaseInfo();
  44. foreach (var kvp in dbInfo)
  45. {
  46. if (kvp.Key == "Database")
  47. {
  48. sdfFileName = kvp.Value;
  49. break;
  50. }
  51. }
  52. sdfFileName = Path.GetFileName(sdfFileName);
  53. if (dcPath.ToUpperInvariant().EndsWith(".VB"))
  54. {
  55. FixDataContextVB(dcPath, model, null, sdfFileName, repository);
  56. }
  57. else
  58. {
  59. FixDataContextCS(dcPath, model, null, sdfFileName, repository);
  60. }
  61. }
  62. public string RunSqlMetal(string sqlMetalPath, string parameters)
  63. {
  64. ProcessStartInfo startInfo = new ProcessStartInfo();
  65. startInfo.RedirectStandardOutput = true;
  66. startInfo.RedirectStandardInput = true;
  67. startInfo.RedirectStandardError = true;
  68. startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
  69. startInfo.CreateNoWindow = true;
  70. startInfo.UseShellExecute = false;
  71. startInfo.FileName = sqlMetalPath;
  72. startInfo.Arguments = parameters;
  73. using (var _command = new Process())
  74. {
  75. _command.StartInfo = startInfo;
  76. _command.ErrorDataReceived += new DataReceivedEventHandler(_command_ErrorDataReceived);
  77. _command.OutputDataReceived += new DataReceivedEventHandler(_command_OutputDataReceived);
  78. _command.EnableRaisingEvents = true;
  79. _command.Start();
  80. _command.BeginOutputReadLine();
  81. _command.BeginErrorReadLine();
  82. _command.WaitForExit();
  83. return _sbResult.ToString();
  84. }
  85. }
  86. void _command_OutputDataReceived(object sender, DataReceivedEventArgs e)
  87. {
  88. _sbResult.AppendLine("SqlMetal output: " + e.Data);
  89. }
  90. void _command_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  91. {
  92. _sbResult.AppendLine("SqlMetal error: " + e.Data);
  93. }
  94. private static string T(int n)
  95. {
  96. return new String('\t', n);
  97. }
  98. private static string ToUpperFirst(string s)
  99. {
  100. if (string.IsNullOrEmpty(s))
  101. {
  102. return string.Empty;
  103. }
  104. char[] a = s.ToCharArray();
  105. a[0] = char.ToUpper(a[0]);
  106. return new string(a);
  107. }
  108. public void FixDataContextCS(string path, string model, string nameSpace, string sdfFileName, IRepository repository)
  109. {
  110. string debugWriter = @"
  111. public class DebugWriter : TextWriter
  112. {
  113. private const int DefaultBufferSize = 256;
  114. private System.Text.StringBuilder _buffer;
  115. public DebugWriter()
  116. {
  117. BufferSize = 256;
  118. _buffer = new System.Text.StringBuilder(BufferSize);
  119. }
  120. public int BufferSize
  121. {
  122. get;
  123. private set;
  124. }
  125. public override System.Text.Encoding Encoding
  126. {
  127. get { return System.Text.Encoding.UTF8; }
  128. }
  129. #region StreamWriter Overrides
  130. public override void Write(char value)
  131. {
  132. _buffer.Append(value);
  133. if (_buffer.Length >= BufferSize)
  134. Flush();
  135. }
  136. public override void WriteLine(string value)
  137. {
  138. Flush();
  139. using(var reader = new StringReader(value))
  140. {
  141. string line;
  142. while( null != (line = reader.ReadLine()))
  143. System.Diagnostics.Debug.WriteLine(line);
  144. }
  145. }
  146. protected override void Dispose(bool disposing)
  147. {
  148. if (disposing)
  149. Flush();
  150. }
  151. public override void Flush()
  152. {
  153. if (_buffer.Length > 0)
  154. {
  155. System.Diagnostics.Debug.WriteLine(_buffer);
  156. _buffer.Clear();
  157. }
  158. }
  159. #endregion
  160. }
  161. ";
  162. List<string> dcLines = System.IO.File.ReadAllLines(path).ToList();
  163. var n = string.Empty;
  164. if (!string.IsNullOrEmpty(nameSpace))
  165. {
  166. n += "\t";
  167. }
  168. var t = "\t";
  169. int i = dcLines.IndexOf(n + "public partial class " + model + " : System.Data.Linq.DataContext");
  170. if (i > -1)
  171. {
  172. dcLines.Insert(i - 2, debugWriter);
  173. dcLines.Insert(i - 2, "");
  174. dcLines.Insert(i - 2, "using Microsoft.Phone.Data.Linq;");
  175. dcLines.Insert(i - 2, "using Microsoft.Phone.Data.Linq.Mapping;");
  176. dcLines.Insert(i - 2, "using System.IO.IsolatedStorage;");
  177. dcLines.Insert(i - 2, "using System.IO;");
  178. }
  179. i = dcLines.IndexOf(n + "public partial class " + model + " : System.Data.Linq.DataContext");
  180. if (i > -1)
  181. {
  182. dcLines.RemoveAt(i - 1);
  183. dcLines.RemoveAt(i - 2);
  184. i++;
  185. i++;
  186. dcLines.Insert(i++, n + t + "public static string ConnectionString = \"Data Source=isostore:/" + sdfFileName + "\";");
  187. dcLines.Insert(i++, "");
  188. dcLines.Insert(i++, n + t + "public static string ConnectionStringReadOnly = \"Data Source=appdata:/" + sdfFileName + ";File Mode=Read Only;\";");
  189. dcLines.Insert(i++, "");
  190. dcLines.Insert(i++, n + t + "public static string FileName = \"" + sdfFileName + "\";");
  191. dcLines.Insert(i++, "");
  192. dcLines.Insert(i++, n + t + "public " + model + "(string connectionString) : base(connectionString)");
  193. dcLines.Insert(i++, n + t + "{");
  194. dcLines.Insert(i++, n + t + t + "OnCreated();");
  195. dcLines.Insert(i++, n + t + "}");
  196. }
  197. i = dcLines.IndexOf(n + t + "public " + model + "(string connection) : ");
  198. if (i > -1)
  199. {
  200. dcLines.RemoveRange(i, 6);
  201. }
  202. i = dcLines.IndexOf(n + t + "public " + model + "(System.Data.IDbConnection connection) : ");
  203. if (i > -1)
  204. {
  205. dcLines.RemoveRange(i, 6);
  206. }
  207. i = dcLines.IndexOf(n + t + "public " + model + "(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : ");
  208. if (i > -1)
  209. {
  210. dcLines.RemoveRange(i, 6);
  211. }
  212. i = dcLines.IndexOf(n + t + "public " + model + "(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : ");
  213. if (i > -1)
  214. {
  215. dcLines.RemoveRange(i, 6);
  216. }
  217. i = dcLines.IndexOf(n + t + "private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();");
  218. if (i > -1)
  219. {
  220. dcLines.RemoveAt(i);
  221. dcLines.Insert(i++, n + t + "public bool CreateIfNotExists()");
  222. dcLines.Insert(i++, n + t + "{");
  223. dcLines.Insert(i++, n + T(2) + "bool created = false;");
  224. dcLines.Insert(i++, n + T(2) + "using (var db = new " + model + "(" + model + ".ConnectionString))");
  225. dcLines.Insert(i++, n + T(2) + "{");
  226. dcLines.Insert(i++, n + T(3) + "if (!db.DatabaseExists())");
  227. dcLines.Insert(i++, n + T(3) + "{");
  228. dcLines.Insert(i++, n + T(4) + "string[] names = this.GetType().Assembly.GetManifestResourceNames();");
  229. dcLines.Insert(i++, n + T(4) + "string name = names.Where(n => n.EndsWith(FileName)).FirstOrDefault();");
  230. dcLines.Insert(i++, n + T(4) + "if (name != null)");
  231. dcLines.Insert(i++, n + T(4) + "{");
  232. dcLines.Insert(i++, n + T(5) + "using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))");
  233. dcLines.Insert(i++, n + T(5) + "{");
  234. dcLines.Insert(i++, n + T(6) + "if (resourceStream != null)");
  235. dcLines.Insert(i++, n + T(6) + "{");
  236. dcLines.Insert(i++, n + T(7) + "using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())");
  237. dcLines.Insert(i++, n + T(7) + "{");
  238. dcLines.Insert(i++, n + T(8) + "using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))");
  239. dcLines.Insert(i++, n + T(8) + "{");
  240. dcLines.Insert(i++, n + T(9) + "using (BinaryWriter writer = new BinaryWriter(fileStream))");
  241. dcLines.Insert(i++, n + T(9) + "{");
  242. dcLines.Insert(i++, n + T(10) + "long length = resourceStream.Length;");
  243. dcLines.Insert(i++, n + T(10) + "byte[] buffer = new byte[32];");
  244. dcLines.Insert(i++, n + T(10) + "int readCount = 0;");
  245. dcLines.Insert(i++, n + T(10) + "using (BinaryReader reader = new BinaryReader(resourceStream))");
  246. dcLines.Insert(i++, n + T(10) + "{");
  247. dcLines.Insert(i++, n + T(11) + "// read file in chunks in order to reduce memory consumption and increase performance");
  248. dcLines.Insert(i++, n + T(11) + "while (readCount < length)");
  249. dcLines.Insert(i++, n + T(11) + "{");
  250. dcLines.Insert(i++, n + T(12) + "int actual = reader.Read(buffer, 0, buffer.Length);");
  251. dcLines.Insert(i++, n + T(12) + "readCount += actual;");
  252. dcLines.Insert(i++, n + T(12) + "writer.Write(buffer, 0, actual);");
  253. dcLines.Insert(i++, n + T(11) + "}");
  254. dcLines.Insert(i++, n + T(10) + "}");
  255. dcLines.Insert(i++, n + T(9) + "}");
  256. dcLines.Insert(i++, n + T(8) + "}");
  257. dcLines.Insert(i++, n + T(7) + "}");
  258. dcLines.Insert(i++, n + T(7) + "created = true;");
  259. dcLines.Insert(i++, n + T(6) + "}");
  260. dcLines.Insert(i++, n + T(6) + "else");
  261. dcLines.Insert(i++, n + T(6) + "{");
  262. dcLines.Insert(i++, n + T(7) + "db.CreateDatabase();");
  263. dcLines.Insert(i++, n + T(7) + "created = true;");
  264. dcLines.Insert(i++, n + T(6) + "}");
  265. dcLines.Insert(i++, n + T(5) + "}");
  266. dcLines.Insert(i++, n + T(4) + "}");
  267. dcLines.Insert(i++, n + T(4) + "else");
  268. dcLines.Insert(i++, n + T(4) + "{");
  269. dcLines.Insert(i++, n + T(5) + "db.CreateDatabase();");
  270. dcLines.Insert(i++, n + T(5) + "created = true;");
  271. dcLines.Insert(i++, n + T(4) + "}");
  272. dcLines.Insert(i++, n + T(3) + "}");
  273. dcLines.Insert(i++, n + T(2) + "}");
  274. dcLines.Insert(i++, n + T(2) + "return created;");
  275. dcLines.Insert(i++, n + t + "}");
  276. dcLines.Insert(i++, n + t + "");
  277. dcLines.Insert(i++, n + t + "public bool LogDebug");
  278. dcLines.Insert(i++, n + t + "{");
  279. dcLines.Insert(i++, n + T(2) + "set");
  280. dcLines.Insert(i++, n + T(2) + "{");
  281. dcLines.Insert(i++, n + T(3) + "if (value)");
  282. dcLines.Insert(i++, n + T(3) + "{");
  283. dcLines.Insert(i++, n + T(4) + "this.Log = new DebugWriter();");
  284. dcLines.Insert(i++, n + T(3) + "}");
  285. dcLines.Insert(i++, n + T(2) + "}");
  286. dcLines.Insert(i++, n + t + "}");
  287. dcLines.Insert(i++, n + t + "");
  288. }
  289. AddIndexes(repository, dcLines, n, true);
  290. System.IO.File.WriteAllLines(path, dcLines.ToArray());
  291. }
  292. public void FixDataContextVB(string path, string model, string nameSpace, string sdfFileName, IRepository repository)
  293. {
  294. string debugWriter = @"
  295. #Region ""DebugWriter""
  296. Public Class DebugWriter
  297. Inherits TextWriter
  298. Private Const DefaultBufferSize As Integer = 256
  299. Private _buffer As System.Text.StringBuilder
  300. Public Sub New()
  301. BufferSize = 256
  302. _buffer = New System.Text.StringBuilder(BufferSize)
  303. End Sub
  304. Public Property BufferSize() As Integer
  305. Get
  306. Return m_BufferSize
  307. End Get
  308. Private Set(value As Integer)
  309. m_BufferSize = value
  310. End Set
  311. End Property
  312. Private m_BufferSize As Integer
  313. Public Overrides ReadOnly Property Encoding() As System.Text.Encoding
  314. Get
  315. Return System.Text.Encoding.UTF8
  316. End Get
  317. End Property
  318. #Region ""StreamWriter Overrides""
  319. Public Overrides Sub Write(value As Char)
  320. _buffer.Append(value)
  321. If _buffer.Length >= BufferSize Then
  322. Flush()
  323. End If
  324. End Sub
  325. Public Overrides Sub WriteLine(value As String)
  326. Flush()
  327. Using reader = New StringReader(value)
  328. Dim line As String
  329. ' Read and display lines from the file until the end of
  330. ' the file is reached.
  331. Do
  332. line = reader.ReadLine()
  333. If Not (line Is Nothing) Then
  334. System.Diagnostics.Debug.WriteLine(line)
  335. End If
  336. Loop Until line Is Nothing
  337. End Using
  338. End Sub
  339. Protected Overrides Sub Dispose(disposing As Boolean)
  340. If disposing Then
  341. Flush()
  342. End If
  343. End Sub
  344. Public Overrides Sub Flush()
  345. If _buffer.Length > 0 Then
  346. System.Diagnostics.Debug.WriteLine(_buffer)
  347. _buffer.Clear()
  348. End If
  349. End Sub
  350. Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
  351. target = value
  352. Return value
  353. End Function
  354. #End Region
  355. End Class
  356. #End Region
  357. ";
  358. string createIfNotExists = @"
  359. Public Function CreateIfNotExists() As Boolean
  360. Dim created As Boolean = False
  361. Using db = New {0}({0}.ConnectionString)
  362. If Not db.DatabaseExists() Then
  363. Dim names As String() = Me.[GetType]().Assembly.GetManifestResourceNames()
  364. Dim name As String = names.Where(Function(n) n.EndsWith(FileName)).FirstOrDefault()
  365. If name IsNot Nothing Then
  366. Using resourceStream As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)
  367. If resourceStream IsNot Nothing Then
  368. Using myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
  369. Using fileStream As New IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage)
  370. Using writer As New BinaryWriter(fileStream)
  371. Dim length As Long = resourceStream.Length
  372. Dim buffer As Byte() = New Byte(32) {}
  373. Dim readCount As Integer = 0
  374. Using reader As New BinaryReader(resourceStream)
  375. ' read file in chunks in order to reduce memory consumption and increase performance
  376. While readCount < length
  377. Dim actual As Integer = reader.Read(buffer, 0, buffer.Length)
  378. readCount += actual
  379. writer.Write(buffer, 0, actual)
  380. End While
  381. End Using
  382. End Using
  383. End Using
  384. End Using
  385. created = True
  386. Else
  387. db.CreateDatabase()
  388. created = True
  389. End If
  390. End Using
  391. Else
  392. db.CreateDatabase()
  393. created = True
  394. End If
  395. End If
  396. End Using
  397. Return created
  398. End Function
  399. Public WriteOnly Property LogDebug() As Boolean
  400. Set(value As Boolean)
  401. If value Then
  402. Me.Log = New DebugWriter()
  403. End If
  404. End Set
  405. End Property
  406. ";
  407. List<string> dcLines = System.IO.File.ReadAllLines(path).ToList();
  408. var n = string.Empty;
  409. if (!string.IsNullOrEmpty(nameSpace))
  410. {
  411. n += "\t";
  412. }
  413. var t = "\t";
  414. int i = dcLines.IndexOf("Imports System.Reflection");
  415. if (i > -1)
  416. {
  417. dcLines.Insert(i++, "Imports Microsoft.Phone.Data.Linq");
  418. dcLines.Insert(i++, "Imports Microsoft.Phone.Data.Linq.Mapping");
  419. dcLines.Insert(i++, "Imports System.IO.IsolatedStorage");
  420. dcLines.Insert(i++, "Imports System.IO");
  421. }
  422. i = dcLines.IndexOf(n + "Partial Public Class " + model);
  423. if (i > -1)
  424. {
  425. dcLines.Insert(i - 2, debugWriter);
  426. dcLines.Insert(i - 2, "");
  427. }
  428. i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As String)");
  429. if (i > -1)
  430. {
  431. dcLines.RemoveRange(i, 4);
  432. }
  433. i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As System.Data.IDbConnection)");
  434. if (i > -1)
  435. {
  436. dcLines.RemoveRange(i, 4);
  437. }
  438. i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As String, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)");
  439. if (i > -1)
  440. {
  441. dcLines.RemoveRange(i, 4);
  442. }
  443. i = dcLines.IndexOf(n + t + "Public Sub New(ByVal connection As System.Data.IDbConnection, ByVal mappingSource As System.Data.Linq.Mapping.MappingSource)");
  444. if (i > -1)
  445. {
  446. dcLines.RemoveRange(i, 4);
  447. }
  448. i = dcLines.IndexOf(n + "Partial Public Class " + model);
  449. if (i > -1)
  450. {
  451. dcLines.RemoveAt(i - 1);
  452. dcLines.RemoveAt(i - 2);
  453. i++;
  454. i++;
  455. i++;
  456. dcLines.Insert(i++, n + t + "Public Shared ConnectionString As String = \"Data Source=isostore:/" + sdfFileName + ";\"");
  457. dcLines.Insert(i++, "");
  458. dcLines.Insert(i++, n + t + "Public Shared ConnectionStringReadOnly As String = \"Data Source=appdata:/" + sdfFileName + ";File Mode=Read Only;\"");
  459. dcLines.Insert(i++, "");
  460. dcLines.Insert(i++, n + t + "Public Shared FileName As String = \"" + sdfFileName + "\"");
  461. dcLines.Insert(i++, "");
  462. dcLines.Insert(i++, n + t + "Public Sub New(ByVal connection As String)");
  463. dcLines.Insert(i++, n + t + t + "MyBase.New(connection)");
  464. dcLines.Insert(i++, n + t + t + "OnCreated()");
  465. dcLines.Insert(i++, n + t + "End Sub");
  466. }
  467. i = dcLines.IndexOf(n + t + "Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource()");
  468. if (i > -1)
  469. {
  470. dcLines.RemoveAt(i);
  471. createIfNotExists = createIfNotExists.Replace("{0}", model);
  472. dcLines.Insert(i++, n + t + createIfNotExists);
  473. }
  474. AddIndexes(repository, dcLines, n, false);
  475. System.IO.File.WriteAllLines(path, dcLines.ToArray());
  476. }
  477. private static void AddIndexes(IRepository repository, List<string> dcLines, string n, bool cs)
  478. {
  479. for (int y = 0; y < dcLines.Count; y++)
  480. {
  481. string attr = "<Global.System.Data.Linq.Mapping.TableAttribute(";
  482. if (cs)
  483. attr = "[global::System.Data.Linq.Mapping.TableAttribute(";
  484. if (dcLines[y].StartsWith(n + attr))
  485. {
  486. string tableName = string.Empty;
  487. // if the Name attribute is used, that is the table name, otherwise use class name
  488. string[] names = dcLines[y].Split('"');
  489. if (names.Count() > 1)
  490. tableName = names[1];
  491. string[] words = dcLines[y + 1].Split(' ');
  492. if (words.Count() > 3)
  493. {
  494. if (tableName == string.Empty)
  495. tableName = words[3];
  496. List<Index> indexList = repository.GetIndexesFromTable(tableName);
  497. List<PrimaryKey> pkList = repository.GetAllPrimaryKeys().Where(pk => pk.TableName == tableName).ToList();
  498. //If there are indexes, add them
  499. if (indexList.Count > 0)
  500. {
  501. IEnumerable<string> uniqueIndexNameList = indexList.Select(ind => ind.IndexName).Distinct();
  502. foreach (string uniqueIndexName in uniqueIndexNameList)
  503. {
  504. string colList = string.Empty;
  505. IOrderedEnumerable<Index> indexesByName = from ind in indexList
  506. where ind.IndexName == uniqueIndexName
  507. orderby ind.OrdinalPosition
  508. select ind;
  509. // Check if a Unique index overlaps an existing primary key
  510. // If that is the case, do not add the duplicate index
  511. // as this will cause LINQ to SQL to crash
  512. // when doing updates with rowversion columns
  513. var ixList = indexesByName.ToList();
  514. if (ixList.Count > 0 && ixList[0].Unique)
  515. {
  516. int i = 0;
  517. foreach (var pk in pkList)
  518. {
  519. if (ixList.Count > i)
  520. {
  521. if (pk.ColumnName != ixList[i].ColumnName)
  522. {
  523. break;
  524. }
  525. }
  526. else
  527. {
  528. break;
  529. }
  530. i++;
  531. }
  532. if (i > 0)
  533. continue;
  534. }
  535. bool unique = false;
  536. var idx = indexesByName.First();
  537. if (idx.Unique)
  538. {
  539. unique = true;
  540. }
  541. foreach (Index col in indexesByName)
  542. {
  543. colList += string.Format("{0} {1}, ", ToUpperFirst(col.ColumnName.Replace(" ", string.Empty)), col.SortOrder.ToString());
  544. }
  545. colList = colList.Remove(colList.Length - 2, 2);
  546. string indexAttr = "<Index(Name:=\"{0}\", Columns:=\"{1}\", IsUnique:={2})>";
  547. if (cs)
  548. indexAttr = "[Index(Name=\"{0}\", Columns=\"{1}\", IsUnique={2})]";
  549. string falseString = "False";
  550. if (cs)
  551. falseString = "false";
  552. string trueString = "True";
  553. if (cs)
  554. trueString = "true";
  555. dcLines[y - 1] += Environment.NewLine + n + string.Format(indexAttr, idx.IndexName, colList, unique ? trueString : falseString);
  556. }
  557. }
  558. }
  559. }
  560. }
  561. }
  562. public Dictionary<string, string> SplitIntoMultipleFiles(string dcPath, string nameSpace, string model)
  563. {
  564. //Fist part is the class name, second in the file contents
  565. Dictionary<string, string> split = new Dictionary<string, string>();
  566. List<string> dcLines = System.IO.File.ReadAllLines(dcPath).ToList();
  567. var n = string.Empty;
  568. if (!string.IsNullOrEmpty(nameSpace))
  569. {
  570. n += "\t";
  571. }
  572. string usings = @"//------------------------------------------------------------------------------
  573. // <auto-generated>
  574. // This code was generated by a tool.
  575. // Runtime Version:4.0.30319.235
  576. //
  577. // Changes to this file may cause incorrect behavior and will be lost if
  578. // the code is regenerated.
  579. // </auto-generated>
  580. //------------------------------------------------------------------------------
  581. using System;
  582. using System.Collections.Generic;
  583. using System.ComponentModel;
  584. using System.Data;
  585. using System.Data.Linq;
  586. using System.Data.Linq.Mapping;
  587. using System.Linq;
  588. using System.Linq.Expressions;
  589. using System.Reflection;
  590. using System.IO;
  591. using System.IO.IsolatedStorage;
  592. using Microsoft.Phone.Data.Linq.Mapping;
  593. using Microsoft.Phone.Data.Linq;
  594. ";
  595. string remove1 =
  596. @" public System.Data.Linq.Table<{0}> {0}
  597. {
  598. get
  599. {
  600. return this.GetTable<{0}>();
  601. }
  602. }
  603. ";
  604. string remove2 =
  605. @" public System.Data.Linq.Table<{0}> {0}
  606. {
  607. get
  608. {
  609. return this.GetTable<{0}>();
  610. }
  611. }";
  612. string remove3 =
  613. @" public System.Data.Linq.Table<{0}> {0}s
  614. {
  615. get
  616. {
  617. return this.GetTable<{0}>();
  618. }
  619. }
  620. ";
  621. string remove4 =
  622. @" public System.Data.Linq.Table<{0}> {0}s
  623. {
  624. get
  625. {
  626. return this.GetTable<{0}>();
  627. }
  628. }";
  629. string contextName = string.Empty;
  630. List<string> systemClasses = new List<string>();
  631. for (int y = 0; y < dcLines.Count; y++)
  632. {
  633. if (dcLines[y].StartsWith(n + "public partial class ") || dcLines[y].StartsWith(n + "public class DebugWriter"))
  634. {
  635. var parts = dcLines[y].Split(' ');
  636. if (parts.Count() > 3)
  637. {
  638. string className = parts[3];
  639. if (contextName == string.Empty && !dcLines[y].StartsWith(n + "public class DebugWriter"))
  640. contextName = className;
  641. if (className == ":")
  642. className = parts[2];
  643. if (className.StartsWith("@__"))
  644. {
  645. systemClasses.Add(className);
  646. }
  647. else
  648. {
  649. int x = y - 1;
  650. while (dcLines[x] != string.Empty)
  651. {
  652. x--;
  653. }
  654. string finalClass = usings;
  655. while ((x < dcLines.Count - 1) && dcLines[x] != n + "}")
  656. {
  657. finalClass += Environment.NewLine + dcLines[x];
  658. x++;
  659. }
  660. finalClass += Environment.NewLine + "}";
  661. split.Add(className, finalClass);
  662. }
  663. }
  664. }
  665. }
  666. if (split.Count > 0)
  667. {
  668. foreach (var item in systemClasses)
  669. {
  670. split[contextName] = split[contextName].Replace(remove1.Replace("{0}", item), string.Empty);
  671. split[contextName] = split[contextName].Replace(remove2.Replace("{0}", item), string.Empty);
  672. split[contextName] = split[contextName].Replace(remove3.Replace("{0}", item), string.Empty);
  673. split[contextName] = split[contextName].Replace(remove4.Replace("{0}", item), string.Empty);
  674. }
  675. }
  676. return split;
  677. }
  678. }
  679. }