public AsyncDeployMetadataThread(RequestHandlerProxy proxy, Common.Solution solution, Stream messageBody, bool checkTabularSectionKey) { this.proxy = proxy; this.solution = solution; this.messageBody = messageBody; this.checkTabularSectionKey = checkTabularSectionKey; }
public Stream DownloadDeleted(Common.Solution solution) { try { System.IO.MemoryStream response = new MemoryStream(); SqlConnection conn = GetConnection(solution); using (conn) { StreamWriter wr = new StreamWriter(response); wr.AutoFlush = true; SqlCommand cmd = new SqlCommand("[admin].GetDeleted", conn); cmd.CommandType = CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); XmlReader result = cmd.ExecuteXmlReader(); result.MoveToContent(); wr.Write(result.ReadOuterXml()); response.Position = 0; return(Zip.ZipStream(response)); } } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
private SqlConnection GetConnection(Common.Solution solution) { SqlConnection conn = new SqlConnection(solution.ConnectionString); conn.Open(); return(conn); }
private String CheckAsyncUploadRecord(Common.Solution solution, Guid sessionId) { String result = ""; SqlConnection conn = GetConnection(solution); using (conn) { SqlCommand cmd = new SqlCommand("[admin].CheckAsyncUploadSession", conn); cmd.CommandType = CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@SessionId"].Value = sessionId; using (SqlDataReader r = cmd.ExecuteReader()) { if (r.Read()) { result = r.GetString(0); } else { result = "Task not found"; } } } if (String.IsNullOrEmpty(result)) { return("processing"); } else { return(result); } }
private void GetLicenseInfo(Common.Solution solution, Guid id, out bool exists, out bool activated) { exists = false; activated = false; Trace.TraceInformation("Trying to get info for license {0}", id); using (SqlConnection conn = new SqlConnection(solution.ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("dbo.GetLicenseInfo", conn); cmd.CommandType = System.Data.CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@Id"].Value = id; SqlDataReader r = cmd.ExecuteReader(); if (!r.Read()) { Trace.TraceError("Could not find info for license {0}", id); return; } else { exists = true; activated = r.GetBoolean(r.GetOrdinal("Activated")); Trace.TraceInformation("License {0} exists:{1}, activated:{2}", id, exists, activated); } } }
public Stream ReDeployMetadata(Common.Solution solution) { String scope = solution.Name; try { String path = Common.Solution.GetSolutionFolder(scope); if (!System.IO.Directory.Exists(path)) { throw new Exception(String.Format("Solution '{0}' does not exist", scope)); } Common.Solution.ChangeHostState(scope, "stop"); new CodeFactory.Builder().Build(Common.Solution.CreateFromContext(scope), false); ArchiveFileSystemInternal(solution); Common.Solution.ChangeHostState(scope, "start"); return(Common.Utils.MakeTextAnswer("ok")); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, scope)); } }
public override void UploadData(Common.Solution solution, Stream messageBody, bool checkExisting) { UpdateCurrentCulterInfo(); SqlConnection conn = GetConnection(solution); using (conn) { SqlTransaction tran = conn.BeginTransaction(); Dictionary <String, SqlCommand[]> sqlCommands = new Dictionary <String, SqlCommand[]>(); Dictionary <XmlNode, Exception> fkErrors = new System.Collections.Generic.Dictionary <XmlNode, Exception>(); XmlDocument doc = new XmlDocument(); try { doc.Load(messageBody); XmlNodeList rows = doc.DocumentElement.SelectNodes("//Root/Rows/Row"); foreach (XmlNode row in rows) { UploadRow(row, tran, sqlCommands, fkErrors, checkExisting); } int pass = 0; int cnt = 0; System.Collections.IEnumerable errorRows = null; while (fkErrors.Count > 0) { if (pass > 0 && cnt == 0 && fkErrors.Count > 0) { System.Collections.IEnumerator err = fkErrors.Values.GetEnumerator(); if (err.MoveNext()) { throw (Exception)err.Current; } } cnt = 0; errorRows = new List <XmlNode>(fkErrors.Keys); foreach (XmlNode row in errorRows) { if (UploadRow(row, tran, sqlCommands, fkErrors, checkExisting)) { fkErrors.Remove(row); cnt++; } } pass++; } tran.Commit(); } catch (Exception) { tran.Rollback(); throw; } } }
public Stream CheckIfExists(Common.Solution solution, Stream messageBody) { try { UpdateCurrentCulterInfo(); XmlDocument doc = new XmlDocument(); doc.Load(Zip.UnzipStream(messageBody)); System.IO.MemoryStream response = new MemoryStream(); SqlConnection conn = GetConnection(solution); using (conn) { SqlTransaction tran = conn.BeginTransaction(); try { StreamWriter wr = new StreamWriter(response); wr.AutoFlush = true; wr.WriteLine("<Root>"); //build response.. XmlNodeList entities = doc.DocumentElement.SelectNodes("//Request/Entity"); foreach (XmlNode entityNode in entities) { String entityName = entityNode.Attributes["Name"].Value; String[] arr = entityName.Split('.'); entityName = String.Format("[{0}].[{1}]", arr[0], arr[1]); SqlCommand cmd = new SqlCommand(String.Format("[{0}].[{1}_adm_getnotexisting]", arr[0], arr[1]), conn, tran); cmd.CommandType = CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@Xml"].Value = entityNode.OuterXml; XmlReader result = cmd.ExecuteXmlReader(); result.MoveToContent(); wr.Write(result.ReadOuterXml()); } tran.Commit(); wr.WriteLine("</Root>"); response.Position = 0; return(Zip.ZipStream(response)); } catch (Exception) { tran.Rollback(); throw; } } } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public PushService(String scope, NetworkCredential credential) { if (credential.UserName.ToLower().Equals("admin")) Common.Logon.CheckAdminCredential(scope, credential); else Common.Logon.CheckUserCredential(scope, credential); _solution = Common.Solution.CreateFromContext(scope); _credential = credential; }
public System.IO.Stream PostData(System.IO.Stream messageBody) { System.Data.DataTable tbl = new System.Data.DataTable(); tbl.ReadXml(messageBody); if (tbl.Rows.Count == 0) { return(MakeTextAnswer("ok")); } else { Common.Solution solution = Common.Solution.CreateFromContext(this.scope); DateTime serverTime = DateTime.UtcNow; Guid userId = Guid.Parse(WebOperationContext.Current.IncomingRequest.Headers["userid"]); using (SqlConnection conn = new SqlConnection(solution.ConnectionString)) { conn.Open(); SqlTransaction tran = conn.BeginTransaction(); try { SqlCommand cmd = new SqlCommand("INSERT INTO [admin].GPS([UserId],[ServerTime],[BeginTime],[EndTime],[Latitude],[Longitude],[Speed],[Direction],[SatellitesCount]) VALUES(@UserId,@ServerTime,@BeginTime,@EndTime,@Latitude,@Longitude,@Speed,@Direction,@SatellitesCount)", conn, tran); cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier); cmd.Parameters.Add("@ServerTime", SqlDbType.DateTime); cmd.Parameters.Add("@BeginTime", SqlDbType.DateTime); cmd.Parameters.Add("@EndTime", SqlDbType.DateTime); cmd.Parameters.Add("@Latitude", SqlDbType.Decimal); cmd.Parameters.Add("@Longitude", SqlDbType.Decimal); cmd.Parameters.Add("@Speed", SqlDbType.Decimal); cmd.Parameters.Add("@Direction", SqlDbType.Int); cmd.Parameters.Add("@SatellitesCount", SqlDbType.Int); cmd.Parameters.Add("@Altitude", SqlDbType.Decimal); foreach (DataRow row in tbl.Rows) { cmd.Parameters["@UserId"].Value = userId; cmd.Parameters["@ServerTime"].Value = serverTime; cmd.Parameters["@BeginTime"].Value = row["BeginTime"]; cmd.Parameters["@EndTime"].Value = row["EndTime"]; cmd.Parameters["@Latitude"].Value = row["Latitude"]; cmd.Parameters["@Longitude"].Value = row["Longitude"]; cmd.Parameters["@Speed"].Value = row["Speed"]; cmd.Parameters["@Direction"].Value = row["Direction"]; cmd.Parameters["@SatellitesCount"].Value = row["SatellitesCount"]; cmd.Parameters["@Altitude"].Value = row["Altitude"]; cmd.ExecuteNonQuery(); } tran.Commit(); return(MakeTextAnswer("ok")); } catch (Exception e) { tran.Rollback(); throw; } } } }
public void UploadMetadataInternal(Common.Solution solution, Stream messageBody, bool checkTabularSectionKey = false, bool filtersOnly = false) { Common.Solution.ChangeHostState(solution.Name, "stop"); System.IO.File.WriteAllText(solution.ConfigurationFile, new System.IO.StreamReader(messageBody).ReadToEnd()); new CodeFactory.Builder().Build(solution, false, checkTabularSectionKey, filtersOnly); ArchiveFileSystemInternal(solution); Common.Solution.ChangeHostState(solution.Name, "start"); }
public AsyncUploadThread(RequestHandlerProxy proxy, Guid sessionGuid, Common.Solution solution, Stream messageBody, bool checkExisting, bool zippedStream = true, String contentEncoding = null, String filepath = null) { this.proxy = proxy; this.sessionGuid = sessionGuid; this.solution = solution; this.messageBody = messageBody; this.checkExisting = checkExisting; this.zippedStream = zippedStream; this.contentEncoding = contentEncoding; this.filepath = filepath; }
public Stream UploadData3(Common.Solution solution, Stream messageBody) { try { UploadDataInternal(solution, messageBody, true); return(Common.Utils.MakeTextAnswer("ok")); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public Stream ArchiveFileSystem(Common.Solution solution) { try { ArchiveFileSystemInternal(solution); return(Common.Utils.MakeTextAnswer("ok")); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public PushService(String scope, NetworkCredential credential) { if (credential.UserName.ToLower().Equals("admin")) { Common.Logon.CheckAdminCredential(scope, credential); } else { Common.Logon.CheckUserCredential(scope, credential); } _solution = Common.Solution.CreateFromContext(scope); _credential = credential; }
public Stream DeploySolutionPackage(Common.Solution solution, Stream messageBody) { String scope = solution.Name; try { //create temp dir String tempDir = Path.Combine(System.IO.Path.GetTempPath(), System.Guid.NewGuid().ToString()); System.IO.Directory.CreateDirectory(tempDir); //save stream to file String packagePath = System.IO.Path.Combine(tempDir, "package.zip"); using (FileStream tempZipFileStream = new FileStream(packagePath, FileMode.Create)) { messageBody.CopyTo(tempZipFileStream); } //unzip folder FileHelper.CreateUnzipFolder(packagePath, tempDir, "package"); //deploy metadata String metadatafile = System.IO.Path.Combine(tempDir, "package", "metadata.xml"); using (System.IO.FileStream fs = new FileStream(metadatafile, FileMode.Open)) { UploadMetadataInternal(solution, fs); } //deploy data String datafile = System.IO.Path.Combine(tempDir, "package", "data.xml"); UploadDataInternal(solution, null, false, false, null, datafile); //deploy resources String resource = System.IO.Path.Combine(tempDir, "package", "resource"); String resourceFolder = System.IO.Path.Combine(solution.SolutionFolder, "resource"); if (System.IO.Directory.Exists(resourceFolder)) { System.IO.Directory.Delete(resourceFolder, true); } System.IO.Directory.CreateDirectory(resourceFolder); DirectoryCopy.Copy(resource, resourceFolder, true); //apply resources new CodeFactory.Builder().Build(solution, true); return(Common.Utils.MakeTextAnswer("ok")); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, scope)); } }
public Stream GetClientMetadata(Common.Solution solution) { try { string pathToClientDll = Path.Combine(solution.SolutionFolder, @"configuration\configuration.xml"); FileStream fs = File.OpenRead(pathToClientDll); return(fs); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
private Stream UploadDataAsync(Common.Solution solution, Stream messageBody, bool checkExisting) { try { String contentEncoding = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.ContentEncoding]; Guid sessionGuid = Guid.NewGuid(); //save file string filepath = Path.Combine(System.IO.Path.GetTempPath(), sessionGuid.ToString()); using (FileStream fs = System.IO.File.OpenWrite(filepath)) { messageBody.CopyTo(fs); fs.Flush(); } try { //try to create session CreateAyncUploadRecord(solution, sessionGuid); } catch { try { System.IO.File.Delete(filepath); } catch { } throw; } AsyncUploadThread t = new AsyncUploadThread(this, sessionGuid, solution, null, checkExisting, !String.IsNullOrEmpty(contentEncoding), contentEncoding, filepath); t.Start(); if (t.IsStarted()) { return(Common.Utils.MakeTextAnswer(String.Format("{0}", sessionGuid.ToString()))); } else { //t.Terminate(); return(Common.Utils.MakeTextAnswer("Unable to start async upload session")); } } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
private bool LogRequestInfo(Common.Solution solution, DateTime startTime) { HttpRequestMessageProperty g = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; System.Net.WebHeaderCollection headers = g.Headers; String msg = String.Format("StartTime:{1};Duration:{2}ms", startTime.ToShortDateString(), startTime.ToLongTimeString(), (DateTime.Now - startTime).Milliseconds.ToString()); foreach (String key in g.Headers.Keys) { msg = msg + String.Format(";{0}:{1}", key, headers[key] == null ? "null" : headers[key]); } Common.Solution.Log(solution.Name, "admin", msg); return(true); }
private bool CheckIfDbExists(Common.Solution solution) { using (SqlConnection conn = new SqlConnection(solution.ConnectionString)) { try { conn.Open(); return(true); } catch { return(false); } } }
public Stream GetAllStorageData(Common.Solution solution) { try { string folderForZip = solution.SolutionFolder; string zippingFilePath = System.IO.Path.GetTempPath() + "Solution.zip"; FileHelper.CreateZipArchieve(folderForZip, zippingFilePath); FileStream fs = File.OpenRead(zippingFilePath); return(fs); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public Stream UpdateResources(Common.Solution solution) { try { new CodeFactory.Builder().Build(solution, true); return(Common.Utils.MakeTextAnswer("ok")); } catch (Common.UnsupportedCoreException e) { return(Common.Utils.MakeTextAnswer(e.Message)); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public void CommitAsyncUploadRecord(Common.Solution solution, Guid sessionId, String status = "") { SqlConnection conn = GetConnection(solution); using (conn) { using (SqlCommand cmd = new SqlCommand("[admin].CommitAsyncUploadSession", conn)) { cmd.CommandType = CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@SessionId"].Value = sessionId; cmd.Parameters["@Status"].Value = String.IsNullOrEmpty(status) ? "ok" : status; cmd.ExecuteNonQuery(); } } }
public Stream UploadMetadata2Async(Common.Solution solution, Stream messageBody) { try { System.IO.MemoryStream ms = new MemoryStream(); messageBody.CopyTo(ms); ms.Position = 0; AsyncDeployMetadataThread t = new AsyncDeployMetadataThread(this, solution, ms, true); t.Start(); return(Common.Utils.MakeTextAnswer(String.Format("accepted"))); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public Stream AsyncTaskStatus(Common.Solution solution, String id) { try { Guid sessionId; if (!Guid.TryParse(id, out sessionId)) { throw new Exception("Invalid task id"); } else { return(Common.Utils.MakeTextAnswer(CheckAsyncUploadRecord(solution, sessionId))); } } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
private void ActivateLicenseDbRecord(Common.Solution solution, String server, Guid id, String name, int qty, DateTime expireDate) { Trace.TraceInformation("Trying to add activation db record for license {0}, name:{1}, quantity:{2}, expireDate{3}", id, name, qty, expireDate); using (SqlConnection conn = new SqlConnection(solution.ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("dbo.ActivateLicense", conn); cmd.CommandType = System.Data.CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@Id"].Value = id; cmd.Parameters["@Server"].Value = server; cmd.Parameters["@Name"].Value = name; cmd.Parameters["@Qty"].Value = qty; cmd.Parameters["@ExpireDate"].Value = expireDate; cmd.ExecuteNonQuery(); } }
public Stream CreateLicense() { Trace.TraceInformation("Processing CreateLicense request"); try { Common.Logon.CheckRootCredential(scope, credential); } catch (UnauthorizedAccessException e) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; WebOperationContext.Current.OutgoingResponse.StatusDescription = e.Message; return(null); } Common.Solution solution = CreateSolution(); try { if (!CheckIfDbExists(solution)) { return(MakeErrorAnswer("License service is not initialized")); } Dictionary <String, String> ps = GetParameters(); String server = GetServer(); Guid id = Guid.NewGuid(); String ln = ps["ln"]; int lqty = int.Parse(ps["lqty"]); DateTime le = DateTime.Parse(ps["le"]); CreateLicenseDbRecord(solution, server, id, ln, lqty, le); return(CreateLicenseFile(server, id, ln, lqty, le)); } catch (Exception e) { Trace.TraceError("EXCEPTION {0}", Common.Utils.MakeDetailedExceptionString(e)); throw; } }
private void CreateAyncUploadRecord(Common.Solution solution, Guid sessionId) { SqlConnection conn = GetConnection(solution); using (conn) { SqlCommand cmd = new SqlCommand("[admin].BeginAsyncUploadSession", conn); cmd.CommandType = CommandType.StoredProcedure; try { SqlCommandBuilder.DeriveParameters(cmd); } catch { throw new Exception("Database does not support async upload"); } cmd.Parameters["@SessionId"].Value = sessionId; cmd.ExecuteNonQuery(); } }
public Stream DeploySolution(Common.Solution solution, Stream resourcesZipFileStream) { try { string filepath = Path.Combine(System.IO.Path.GetTempPath(), "resource.zip"); using (FileStream tempZipFileStream = new FileStream(filepath, FileMode.Create)) { resourcesZipFileStream.CopyTo(tempZipFileStream); } FileHelper.CreateUnzipFolder(filepath, solution.SolutionFolder); ArchiveFileSystemInternal(solution); return(Common.Utils.MakeTextAnswer("ok")); } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (args.Name.Equals(AppDomain.CurrentDomain.FriendlyName)) { Common.Solution solution = Common.Solution.CreateFromContext(AppDomain.CurrentDomain.FriendlyName); String[] arr = System.IO.Directory.GetFiles(System.IO.Path.Combine(solution.SolutionFolder, "bin"), "Server*.dll", System.IO.SearchOption.TopDirectoryOnly); if (arr.Length == 0) { throw new Exception("No Server.dll found."); } Array.Sort(arr); String fileName = arr[arr.Length - 1]; return(System.Reflection.Assembly.LoadFile(fileName)); } else { return(null); } }
public Stream DownloadDataCommit(Common.Solution solution, Stream messageBody) { try { XmlDocument doc = new XmlDocument(); doc.Load(Zip.UnzipStream(messageBody)); Guid sessionId = new Guid(doc.DocumentElement.Attributes["Session"].Value); SqlConnection conn = GetConnection(solution); using (conn) { SqlTransaction tran = conn.BeginTransaction(); try { SqlCommand cmd = new SqlCommand("[admin].CommitSyncSession", conn, tran); cmd.CommandType = CommandType.StoredProcedure; SqlCommandBuilder.DeriveParameters(cmd); cmd.Parameters["@SessionId"].Value = sessionId; cmd.ExecuteNonQuery(); tran.Commit(); return(Common.Utils.MakeTextAnswer("ok")); } catch (Exception) { tran.Rollback(); throw; } } } catch (Exception e) { return(Common.Utils.MakeExceptionAnswer(e, solution.Name)); } }
public SyncServiceEx(String scope, NetworkCredential credential) { this.solution = Common.Solution.CreateFromContext(scope); this.credential = credential; }
public AdminSyncService(String scope, System.Net.NetworkCredential credential) { Common.Logon.CheckAdminCredential(scope, credential); this.solution = Common.Solution.CreateFromContext(scope); }