private bool CreateAppCORE() { RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)); string appName = (string)routeData.Values["appName"]; if (!string.IsNullOrEmpty(appName)) { COREobject.Create(User?.Identity.Name, appName); return(true); } if (routeData.Values.ContainsKey("appId")) { COREobject.Create(User?.Identity.Name, Convert.ToInt32(routeData.Values["appId"])); return(true); } var irouteData = (routeData.Values["MS_SubRoutes"] as System.Web.Http.Routing.IHttpRouteData[])?.FirstOrDefault(); if (irouteData?.Values.ContainsKey("appName") == true) { COREobject.Create(User?.Identity.Name, (string)irouteData?.Values["appName"]); return(true); } if (irouteData?.Values.ContainsKey("appId") == true) { COREobject.Create(User?.Identity.Name, Convert.ToInt32(irouteData?.Values["appId"])); return(true); } COREobject.Create(User?.Identity.Name, null); return(false); }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { COREobject core = COREobject.i; DBConnection db = core.Entitron; var context = core.AppContext; var rweUsersTable = db.Table("Users"); List <DBItem> results; if (vars.ContainsKey("Id")) { int userId = Convert.ToInt32(vars["Id"]); results = rweUsersTable.Select().Where(c => c.Column("id").Equal(userId)).ToList(); } else { results = rweUsersTable.Select().Where(c => c.Column("pernr").Equal((string)vars["Pernr"])).ToList(); } if (results.Count > 0) { string ad_email = (string)results[0]["ad_email"]; var userObject = context.Users.SingleOrDefault(u => u.Email == ad_email); outputVars["Result"] = userObject == null ? 0 : userObject.Id; } else { outputVars["Result"] = 0; } }
protected void Application_EndRequest() { if (Request.Url.AbsolutePath.ToLower().EndsWith("/core/account/login") && Request.HttpMethod.ToLower() == "post" && Context.Response.Headers.AllKeys.Contains("Set-Cookie") && Context.Response.Headers["Set-Cookie"].Contains(".AspNet.ApplicationCookie") && Request.Form.AllKeys.Contains("UserName") && !string.IsNullOrEmpty(Request.Form["UserName"]) ) { DBEntities db = COREobject.i.Context; string userName = Request.Form["UserName"].ToLower(); User user = db.Users.Single(u => u.UserName.ToLower() == userName); string cookies = Context.Response.Headers["Set-Cookie"]; var m = Regex.Match(cookies, ".AspNet.ApplicationCookie=(?<AppCookie>.*?);"); string appCookie = m.Groups["AppCookie"].Value; user.LastIp = Request.UserHostAddress; user.LastAppCookie = appCookie; db.SaveChanges(); } Debug.WriteLine($"Request time: {DateTime.UtcNow - COREobject.i.RequestStart} - Url: {Request.RawUrl}"); COREobject.Destroy(); }
public static void OpenUrl(COREobject core, string Block, string Button = "", int ModelId = -1) { DBConnection db = core.Entitron; string hostname = TapestryUtils.GetServerHostName(); string appName = db.Application.Name; string serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; string systemAccName = WebConfigurationManager.AppSettings["SystemAccountName"]; string systemAccPass = WebConfigurationManager.AppSettings["SystemAccountPass"]; string targetUrl; if (serverName == "localhost") { targetUrl = $"https://omnius-as.azurewebsites.net/{appName}/{Block}/Get?modelId={ModelId}&User={systemAccName}&Password={systemAccPass}"; } else { targetUrl = $"{hostname}/{appName}/{Block}/Get?modelId={ModelId}&User={systemAccName}&Password={systemAccPass}"; } if (Button != "") { targetUrl += $"&button={Button}"; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); }
public static string CombineAtRandom(COREobject core, string[] TableName, string[] Column, string Separator = " ") { DBConnection db = core.Entitron; if (TableName.Length != Column.Length) { throw new Exception("Missing table or column name!"); } string result = ""; for (int i = 0; i < TableName.Length; i++) { DBTable table = db.Table(TableName[i]); Random rnd = new Random(); var rows = table.Select(Column[i]).ToList(); result += rows[rnd.Next(rows.Count)][Column[i]].ToString() + Separator; } if (result.EndsWith(Separator)) { result.Remove(result.Length - Separator.Length); } return(result); }
public static (byte[], bool) Download(COREobject core, string Url) { try { var httpWebRequest = (HttpWebRequest)WebRequest.Create(Url); httpWebRequest.Method = "GET"; var response = httpWebRequest.GetResponse(); Stream responseStream = response.GetResponseStream(); if (response.ContentType.StartsWith("image")) { byte[] rawData; using (var ms = new MemoryStream()) { responseStream.CopyTo(ms); rawData = ms.ToArray(); } return(rawData, false); } else { Watchtower.OmniusInfo.Log($"Requested file \"{Url}\" is not image."); return(new byte[] { }, true); } } catch (Exception e) { Watchtower.OmniusInfo.Log(e.Message); return(new byte[] { }, true); } }
public static void NoAction(COREobject core, int?waitFor = null) { if (waitFor != null) { Thread.Sleep(waitFor.Value); } }
public ActionResult RunSender(string serverName = "") { bool isAuthorized = Authorize(); bool redirect = true; if (!isAuthorized) { return(new Http403Result()); } COREobject core = COREobject.i; if (core.User == null) { redirect = false; core.User = Persona.GetAuthenticatedUser(userName, false, Request); } Mailer mailer = new Mailer(serverName); mailer.RunSender(); if (redirect) { return(RedirectToRoute("Hermes", new { @action = "Index" })); } else { return(new EmptyResult()); } }
public static List <DBItem> RecordDatesDeleted(COREobject core, List <DBItem> OldData, List <DBItem> NewData) { // List of newly removed users from AD List <DBItem> removedUsers = new List <DBItem>(); for (int i = 0; i < OldData.Count; i++) { DBItem oldUser = OldData[i]; string sapid1 = (string)oldUser["sapid1"]; // Remove old active users, so oldData contains only deleted users in the end if (!(NewData.Any(c => (string)c["sapid1"] == sapid1))) { removedUsers.Add(oldUser); } } foreach (DBItem removedUser in removedUsers) { string sapid1 = (string)removedUser["sapid1"]; var user = core.Context.Users.SingleOrDefault(c => c.UserName == sapid1 && c.DeletedBySync == null); if (user != null) { user.DeletedBySync = DateTime.Now; } } core.Context.SaveChanges(); return(OldData); }
public override void OnAuthorization(AuthorizationContext filterContext) { // Allow Anonymous if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) { return; } // Is logged / guest COREobject core = COREobject.i; if (core.User == null) { core.User = Persona.GetAuthenticatedUser(filterContext.HttpContext.User.Identity.Name, core.Application?.IsAllowedGuests == true, filterContext.HttpContext.Request); } // authorize try { core.User.Authorize(NeedsAdmin, Module, Users, core.Application); } catch (NotAuthorizedException) { filterContext.Result = new Http403Result(); } }
/// <summary> /// </summary> /// <param name="dbSchemeCommit"></param> public void GenerateDatabase(DbSchemeCommit dbSchemeCommit, COREobject core) { if (dbSchemeCommit != null) { try { _db = core.Entitron; _ent = core.Context; _app = core.Application; _progressHandler.SetMessage("DropOldRelations", "Drop old relations"); _progressHandler.SetMessage("GenerateTables", "Generate tables"); _progressHandler.SetMessage("GenerateRelation", "Generate relations"); _progressHandler.SetMessage("GenerateView", "Generate views"); _progressHandler.SetMessage("DroppingOldTables", "Drop old tables"); DropOldRelations(dbSchemeCommit); GenerateTables(dbSchemeCommit); GenerateRelation(dbSchemeCommit); GenerateView(dbSchemeCommit); DroppingOldTables(dbSchemeCommit); _progressHandler.SetMessage("", type: MessageType.Success); } catch (Exception) { throw; } finally { Entitron.ClearCache(); } } }
// GET: DbDesigner public ActionResult Index(FormCollection formParams) { COREobject core = COREobject.i; DBEntities context = core.Context; int appId = 0; string appName = ""; if (formParams["appId"] != null) { appId = int.Parse(formParams["appId"]); core.User.DesignAppId = appId; context.SaveChanges(); appName = context.Applications.Find(appId).DisplayName; } else { var userApp = core.User.DesignApp; if (userApp == null) { userApp = context.Applications.First(); } appId = userApp.Id; appName = userApp.DisplayName; } var userId = core.User.Id; ViewData["appId"] = appId; ViewData["appName"] = appName; ViewData["currentUserId"] = userId; ViewData["currentUserName"] = context.Users.SingleOrDefault(u => u.Id == userId).DisplayName; return(View()); }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { if (!vars.ContainsKey(InputVar[0])) { return; } int fileId = Convert.ToInt32(vars[InputVar[0]]); COREobject core = COREobject.i; DBEntities context = core.Context; FileMetadata fmd = context.FileMetadataRecords.Find(fileId); IFileSyncService serviceFileSync = new WebDavFileSyncService(); serviceFileSync.DownloadFile(fmd); HttpContext httpContext = HttpContext.Current; HttpResponse response = httpContext.Response; response.Clear(); response.StatusCode = 202; response.ContentType = "application/octet-stream"; response.AddHeader("content-disposition", $"attachment; filename={fmd.Filename}"); response.BinaryWrite(fmd.CachedCopy.Blob); response.Flush(); response.Close(); response.End(); }
public static object ColumnAutosum(COREobject core, List <DBItem> TableData, string ColumnName) { if (TableData.Count == 0) { return(0); } if (TableData[0][ColumnName] is int) { int sum = 0; foreach (var row in TableData) { sum += (int)row[ColumnName]; } return(sum); } else { double sum = 0; foreach (var row in TableData) { sum += Convert.ToDouble(row[ColumnName]); } return(sum); } }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { COREobject core = COREobject.i; DBEntities context = core.Context; string userEmail = (string)vars["Email"]; string name = (string)vars["Name"]; string surname = (string)vars["Surname"]; bool userExists = context.Users.Any(c => c.Email == userEmail); if (!userExists) { var user = new User { Email = userEmail, UserName = userEmail, DisplayName = name + " " + surname, SecurityStamp = "b532ea85-8d2e-4ffb-8c64-86e8bfe363d7", localExpiresAt = DateTime.Now.AddYears(1), CurrentLogin = DateTime.Now, LastLogin = DateTime.Now, LastLogout = DateTime.Now, LastAction = DateTime.Now }; context.Users.Add(user); context.SaveChanges(); } }
public static object ColumnAutosumListObject(COREobject core, string ColumnName, List <object> TableData) { if (TableData.Count == 0) { return(0); } if (((Dictionary <string, object>)(TableData[0]))[ColumnName] is int) { int sum = 0; foreach (var row in TableData) { sum += (int)((Dictionary <string, object>)row)[ColumnName]; } return(sum); } else { double sum = 0; foreach (var row in TableData) { sum += Convert.ToDouble(((Dictionary <string, object>)row)[ColumnName]); } return(sum); } }
public static List <DBItem> CopyInVector(COREobject core, List <DBItem> TableData, string SourceColumn, string TargetColumn, object ConstantSource = null) { if (TableData.Count == 0) { return(TableData); } var firstRow = TableData[0]; if (ConstantSource != null) { foreach (var row in TableData) { row[TargetColumn] = ConstantSource; } } else { foreach (var row in TableData) { row[TargetColumn] = row[SourceColumn]; } } return(TableData); }
public static List <DBItem> ColumnAutosum(COREobject core, List <DBItem> TableData, string ColumnA, string ColumnB, string ResultColumn) { if (TableData.Count == 0) { return(TableData); } var firstRow = TableData[0]; bool integerMode = firstRow[ColumnA] is int && firstRow[ColumnB] is int; if (integerMode) { foreach (var row in TableData) { row[ResultColumn] = (int)row[ColumnA] / (int)row[ColumnB]; } } else { foreach (var row in TableData) { row[ResultColumn] = Convert.ToDouble(row[ColumnA]) / Convert.ToDouble(row[ColumnB]); } } return(TableData); }
// GET: Editor public ActionResult Index(FormCollection formParams) { COREobject core = COREobject.i; DBEntities context = core.Context; if (formParams["appId"] != null) { int appId = int.Parse(formParams["appId"]); core.User.DesignAppId = appId; context.SaveChanges(); ViewData["appId"] = appId; ViewData["pageId"] = formParams["pageId"]; ViewData["appName"] = context.Applications.Find(appId).DisplayName; } else { var userApp = core.User.DesignApp; if (userApp == null) { userApp = context.Applications.First(); } ViewData["appId"] = userApp.Id; ViewData["pageId"] = 0; ViewData["appName"] = userApp.DisplayName; } return(View()); }
public static void SendMail(COREobject core, string Template, string Subject = "", Dictionary <string, string> Recipients = null, Dictionary <string, string> CC = null, Dictionary <string, string> BCC = null, Dictionary <string, object> Data = null) { var context = core.Context; var dataDictionary = Data ?? new Dictionary <string, object>(); Mailer czechMailer = new Mailer("", Template, dataDictionary, Locale.cs); Mailer englishMailer = new Mailer("", Template, dataDictionary, Locale.en); var recipientsCzechOutput = new Dictionary <string, string>(); var recipientsEnglishOutput = new Dictionary <string, string>(); var bccCzechOutput = new Dictionary <string, string>(); var bccEnglishOutput = new Dictionary <string, string>(); if (Recipients != null) { foreach (var addressPair in Recipients) { var user = context.Users.Where(u => u.Email == addressPair.Key).FirstOrDefault(); if (user != null && user.Locale == Locale.en) { recipientsEnglishOutput.Add(addressPair.Key, addressPair.Value); } else { recipientsCzechOutput.Add(addressPair.Key, addressPair.Value); } } czechMailer.To(recipientsCzechOutput); englishMailer.To(recipientsEnglishOutput); } if (BCC != null) { foreach (var addressPair in BCC) { var user = context.Users.Where(u => u.Email == addressPair.Key).FirstOrDefault(); if (user != null && user.Locale == Locale.en) { bccEnglishOutput.Add(addressPair.Key, addressPair.Value); } else { bccCzechOutput.Add(addressPair.Key, addressPair.Value); } } czechMailer.BCC(bccCzechOutput); englishMailer.BCC(bccEnglishOutput); } if (recipientsCzechOutput.Count > 0 || bccCzechOutput.Count > 0) { czechMailer.SendMail(); } if (recipientsEnglishOutput.Count > 0 || bccEnglishOutput.Count > 0) { englishMailer.SendMail(); } }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { COREobject core = COREobject.i; DBEntities context = core.Context; try { string dbName = (string)vars["dbName"]; string tableName = (string)vars["TableName"]; JToken data = (JToken)vars["Data"]; object where = (object)vars["Where"]; if (where == null || (where is String && string.IsNullOrEmpty((string)where))) { throw new Exception(string.Format("{0}: where is missing. You must provide where clausule or rethingDB item id", Name)); } ExtDB dbInfo = context.ExtDBs.Where(d => d.DB_Alias == dbName).SingleOrDefault(); if (dbInfo == null) { throw new Exception(string.Format("{0}: Integration was not found", Name)); } NexusExtDBBaseService service; switch (dbInfo.DB_Type) { case ExtDBType.RethinkDB: service = new NexusExtDBRethingService(dbInfo); break; default: service = (new NexusExtDBService(dbInfo.DB_Server, dbInfo.DB_Alias)).NewQuery(""); break; } NexusExtDBResult result = service.Update(tableName, data, where); if (result.Errors == 0) { outputVars["Result"] = result.Replaced; outputVars["Error"] = false; } else { outputVars["Result"] = result.FirstError; outputVars["Error"] = true; OmniusException.Log(result.FirstError, OmniusLogSource.Nexus, null, core.Application, core.User); } } catch (Exception e) { string errorMsg = e.Message; OmniusException.Log(e, OmniusLogSource.Nexus, core.Application, core.User); outputVars["Result"] = String.Empty; outputVars["Error"] = true; } }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { COREobject core = COREobject.i; DBEntities context = core.Context; if (!vars.ContainsKey(InputVar[0])) { throw new Exception($"Input Var {InputVar[0]} was not defined for WebDavUploadAction!"); } var files = HttpContext.Current.Request.Files; if (files == null) { return; } foreach (string fileName in files) { HttpPostedFile file = HttpContext.Current.Request.Files[fileName]; if (file.ContentLength == 0 || fileName != vars[InputVar[0]].ToString()) { continue; } FileMetadata fmd = new FileMetadata(); fmd.AppFolderName = core.Application.Name; fmd.CachedCopy = new FileSyncCache(); byte[] streamBytes = new byte[file.ContentLength]; file.InputStream.Read(streamBytes, 0, file.ContentLength); fmd.CachedCopy.Blob = streamBytes; fmd.Filename = Path.GetFileName(file.FileName); fmd.TimeChanged = DateTime.Now; fmd.TimeCreated = DateTime.Now; fmd.Version = 0; string name = vars.ContainsKey(InputVar[1]) ? vars[InputVar[1]].ToString() : string.Empty; if (!string.IsNullOrWhiteSpace(name)) { fmd.WebDavServer = context.WebDavServers.Single(a => a.Name == name); } else { fmd.WebDavServer = context.WebDavServers.First(); } context.FileMetadataRecords.Add(fmd); context.SaveChanges(); //ukládat po jednom souboru IFileSyncService service = new WebDavFileSyncService(); service.UploadFile(fmd); outputVars.Add(this.OutputVar[0], fmd.Id); } }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> invertedVars, Message message) { COREobject core = COREobject.i; string hostname = TapestryUtils.GetServerHostName(); string appName = core.Application.Name; outputVars["Result"] = $"{hostname}/{appName}"; }
public static List <object> JArrayToList(COREobject core, JArray List) { if (List.Count > 0) { return(List.ToObject <List <object> >()); } return(null); }
public override void OnOpen() { Task task = Task.Run(() => { _core = COREobject.Create(_username, _applicationId); Build(); Run(); Close(); }); }
public static T DefaultValue <T>(COREobject core, T Variable, T Value) { if (Variable == null) { return(Value); } return(Variable); }
public static byte[] Resize(COREobject core, byte[] ImageData, bool KeepAspectRatio, int Width, int Height = 0) { MemoryStream outStreem = new MemoryStream(); using (Stream stream = new MemoryStream(ImageData)) { Image original = Image.FromStream(stream); int originalWidth = original.Width; int originalHeight = original.Height; if (KeepAspectRatio || Height == 0) { double aspect = (double)originalWidth / (double)originalHeight; int targetWidth = Width; int targetHeight = (int)System.Math.Floor(Width / aspect); if (Height > 0 && targetHeight > Height) { targetWidth = (int)System.Math.Floor(Height * aspect); targetHeight = Height; } Width = targetWidth; Height = targetHeight; } Rectangle destRect = new Rectangle(0, 0, Width, Height); Bitmap destImage = new Bitmap(Width, Height, PixelFormat.Format24bppRgb); destImage.SetResolution(original.HorizontalResolution, original.VerticalResolution); using (var g = Graphics.FromImage(destImage)) { g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(original, destRect, 0, 0, originalWidth, originalHeight, GraphicsUnit.Pixel, wrapMode); } } ImageCodecInfo jpgEncoder = ImageCodecInfo.GetImageDecoders().FirstOrDefault(dec => dec.FormatID == ImageFormat.Jpeg.Guid); Encoder myEncoder = Encoder.Quality; EncoderParameters myEncoderParams = new EncoderParameters(1); EncoderParameter myEncoderParam = new EncoderParameter(myEncoder, 90L); myEncoderParams.Param[0] = myEncoderParam; destImage.Save(outStreem, jpgEncoder, myEncoderParams); } return(outStreem.ToArray()); }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> invertedVars, Message message) { COREobject core = COREobject.i; string hostname = TapestryUtils.GetServerHostName(); string appName = core.Application.Name; string blockName = (string)vars["BlockName"]; int modelId = (int)vars["Id"]; outputVars["Result"] = $"{hostname}/{appName}/{blockName}?modelId={modelId}"; }
public static bool UserHasRole(COREobject core, string[] Role, int?UserId = null) { var context = core.Context; User user = UserId != null ? context.Users.Find(UserId.Value) : core.User; return(Role.Any(r => user.HasRole(r, core.Application.Id))); }
public static DateTime ParseDatetime(COREobject core, string Input) { DateTime datetime; DateTime.TryParseExact(Input, new string[] { "d.M.yyyy H:mm:ss", "d.M.yyyy", "H:mm:ss", "yyyy-MM-ddTHH:mm", "dd.MM.yyyy HH:mm", }, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetime); return(datetime); }