public void Increment(Syslog.HAProxySyslogDatagram datagram) { Interlocked.Increment(ref countHTTPRequestTotal); if (datagram.Status_Code >= 100 && datagram.Status_Code < 200) { Interlocked.Increment(ref countHTTPRequest1xx); } else if (datagram.Status_Code >= 200 && datagram.Status_Code < 300) { Interlocked.Increment(ref countHTTPRequest2xx); } else if (datagram.Status_Code >= 300 && datagram.Status_Code < 400) { Interlocked.Increment(ref countHTTPRequest3xx); } else if (datagram.Status_Code >= 400 && datagram.Status_Code < 500) { Interlocked.Increment(ref countHTTPRequest4xx); } else if (datagram.Status_Code >= 500 && datagram.Status_Code < 600) { Interlocked.Increment(ref countHTTPRequest5xx); } else { Interlocked.Increment(ref countHTTPRequestOther); } Interlocked.Add(ref sumHTTPContentLength, datagram.Content_Length); Interlocked.Add(ref sumHTTPBytesRead, datagram.Bytes_Read); Interlocked.Add(ref sumTq, datagram.Tq); Interlocked.Add(ref sumTw, datagram.Tw); Interlocked.Add(ref sumTc, datagram.Tc); Interlocked.Add(ref sumTr, datagram.Tr); Interlocked.Add(ref sumTt, datagram.Tt); }
public override void Init() { try { if (GetLogDir()) { if (InitializeLogger()) { _log.Log(LogType.FILE, LogLevel.INFORM, " Init() -->> Start creating DAL"); } else { _log.Log(LogType.FILE, LogLevel.ERROR, " Init() -->> An error occurred : "); return; } } else { return; } _log.Log(LogType.FILE, LogLevel.INFORM, " Init() -->> Start listening syslogs on ip: " + _remoteHost + " port: " + _syslogPort.ToString()); _sysLog = new Syslog(_remoteHost, _syslogPort, _protocolType); _sysLog.Start(); _sysLog.SyslogEvent += new Syslog.SyslogEventDelegate(SlogSyslogEvent); _log.Log(LogType.FILE, LogLevel.INFORM, "Init() -->> Finish initializing MCAffeeUTMSyslogRecorder Event"); } catch (Exception er) { EventLog.WriteEntry("Security Manager MCAffeeUTMSyslogRecorder Init", er.ToString(), EventLogEntryType.Error); } }
public override bool CreateReader(ref Exception error) { try { Recorder.Log(LogLevel.DEBUG, "Creating instance for:" + string.Format("Server({0}), Port({1}) Protocol({2})", SyslogAddress, Port, ProtocolType)); syslogInstance = new Syslog(SyslogAddress, Port, ProtocolType); return true; } catch (Exception e) { error = e; } return false; }
// handles liquid template assets public ActionResult Handler(string filename, string domainpath) { string uniqueid; if (domainpath == "facebook") { uniqueid = domainpath; } else { var pathparts = domainpath.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries); uniqueid = pathparts[0]; } // setup physical path first string liquidPhysicalPath; bool isSVG = false; if (Request.RawUrl.IndexOf(".svg.png") != -1) { liquidPhysicalPath = Request.PhysicalPath.Replace(".png", ".liquid"); isSVG = true; } else { liquidPhysicalPath = Request.PhysicalPath + ".liquid"; } // cachekey = filename dynamic result; var cachekey = ThemeHandler.GetCacheKey(uniqueid, filename, (bool)Session[BrowserCapability.IsMobileSession]); if (!CacheHelper.Instance.TryGetCache(CacheItemType.liquid_assets, cachekey, out result)) { if (System.IO.File.Exists(liquidPhysicalPath)) { LiquidTemplateBase template; var accountHostname = Request.Headers["Host"]; MASTERsubdomain sd; using (var db = new tradelrDataContext()) { #if DEBUG if (accountHostname.EndsWith("localhost")) #else if (accountHostname.EndsWith("tradelr.com")) #endif { ////////////// handles case for subdomains string[] host = accountHostname.Split('.'); // not on a subdomain sd = db.GetSubDomain(host[0]); } else { ////////////////// handles case for custom subdomains sd = db.GetCustomHostname(accountHostname); } template = new LiquidTemplateBase(sd, (bool)Session[BrowserCapability.IsMobileSession]); var parsed_string = template.ReadTemplateFile(liquidPhysicalPath); template.InitContentTemplate(parsed_string); template.AddParameters("shop", sd.ToLiquidModel()); } var dirIndex = liquidPhysicalPath.LastIndexOf("\\"); // handle not found var config_file = liquidPhysicalPath.Substring(0, dirIndex).Replace("assets", "config\\settings_data.json"); if (System.IO.File.Exists(config_file)) { var current = template.ReadThemeSettings(config_file); if (current != null) { template.AddParameters("settings", current); } if (isSVG) { // convert to png using (var stream = template.RenderBasicToStreamNoHeader()) { var svg = SvgDocument.Open(stream); result = svg.Draw(); } } else { result = template.RenderBasicNoHeader(); } CacheHelper.Instance.Insert(CacheItemType.liquid_assets, cachekey, result); if (uniqueid != "facebook") { CacheHelper.Instance.add_dependency(DependencyType.liquid_assets, uniqueid, CacheItemType.liquid_assets, cachekey); } } } } if (Request.RawUrl.IndexOf(".css") != -1) { Response.ContentType = "text/css"; return(Content(result)); } if (Request.RawUrl.IndexOf(".js") != -1) { Response.ContentType = "application/x-javascript"; return(Content(result)); } if (isSVG) { return(new SvgToPngActionResult(result)); } Syslog.Write(string.Format("Unknown filetype: {0}", Request.RawUrl)); return(new EmptyResult()); }
public override void Start() { try { // TODO: Add any initialization after the Init call L.Log(LogType.FILE, LogLevel.INFORM, "Finish initializing CheckpointDHCPRecorder"); L.Log(LogType.FILE, LogLevel.INFORM, "Start listening CheckpointDHCPRecorder on ip: " + Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString() + " port: " + Syslog_Port.ToString()); ProtocolType pro; if (protocol.ToLower() == "udp") pro = ProtocolType.Udp; else pro = ProtocolType.Tcp; if (usingRegistry) { L.Log(LogType.FILE, LogLevel.INFORM, "Start listening Syslogs on ip: " + Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString() + " port: " + Syslog_Port.ToString()); slog = new Syslog(Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString(), Syslog_Port, pro); } else { L.Log(LogType.FILE, LogLevel.INFORM, "Start listening Syslogs on ip: " + remote_host + " port: " + Syslog_Port.ToString()); slog = new Syslog(remote_host, Syslog_Port, pro); } //slog = new Syslog(Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString(), Syslog_Port, pro); slog.Start(); slog.SyslogEvent += new Syslog.SyslogEventDelegate(checkpoint_DHCP); L.Log(LogType.FILE, LogLevel.INFORM, "Finish initializing CheckpointDHCPRecorder Event"); } catch (Exception er) { EventLog.WriteEntry("Security Manager CheckpointDHCPRecorder Constructor", er.ToString(), EventLogEntryType.Error); } }
public ActionResult Ship(long id, string trackingno, string trackingAddress, string shippingService, string shipwire) { try { var order = repository.GetOrder(subdomainid.Value, id); if (order == null) { return(Json("Order not found".ToJsonFail())); } var transaction = new Transaction(order, repository, sessionid.Value); if (!string.IsNullOrEmpty(shipwire)) { if (!transaction.HasValidShippingAddress()) { return(SendJsonErrorResponse("The destination shipping address is incomplete.")); } var shipwireService = transaction.GetShipWireService(); var shipwireItems = order.ToShipwireItems(); var shippingMethod = order.shipwireShippingid; var address = transaction.GetShipwireShippingAddress(); shipwireService.CreateOrder(transaction.GetID().ToString(), shippingMethod, shipwireItems, address); var resp = shipwireService.SubmitOrder(); // got response? if (resp == null) { return(SendJsonErrorResponse("No response from Shipwire. Please try again later.")); } // check for exceptions var exceptions = resp.GetExceptions(); if (exceptions.Count != 0) { return(SendJsonErrorResponse(exceptions[transaction.GetID().ToString()])); } // check for one order var submittedOrder = resp.OrderInformation.Order[0]; transaction.UpdateOrderStatus(OrderStatus.SHIPPED); transaction.AddShipwireTransaction(submittedOrder.number.ToString(), XElement.Parse(shipwireService.GetXmlResponse())); transaction.SaveUpdatedTransaction(); } else { transaction.UpdateOrderAsShipped(shippingService, trackingno, trackingAddress); // notify buyer that order has been shipped var viewloc = MASTERdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()); var emailContent = new OrderShippedEmailContent { orderNumber = transaction.GetOrderNumber(), shippingAddress = transaction.GetShippingAddress().ToHtmlString(), sender = transaction.GetOwner().ToEmailName(false), viewloc = viewloc }; string subject = "Invoice #" + emailContent.orderNumber + " has been shipped"; var msg = new Message(transaction.GetReceiver(), transaction.GetOwner(), subdomainid.Value); var result = msg.SendMessage(this, repository, EmailViewType.ORDER_SHIPPED, emailContent, subject, viewloc); if (!result.success) { Syslog.Write(result.message); } } return(Json("".ToJsonOKMessage())); } catch (Exception ex) { return(SendJsonErrorResponse(ex)); } }
internal void Start(string path, string externs, string compilation_level, string detail_level) { string oldFile = path; string newFile = oldFile.Replace(".unc.js", ".min.js"); using (var p = new Process()) { // build cmd argument var argumentBuilder = new StringBuilder(); argumentBuilder.AppendFormat( @"-jar ""{0}"" --js {1} --js_output_file {2} --compilation_level {3} --summary_detail_level {4}", @"D:\code\clearpixels\clearpixels.closure\jar\compiler.jar", oldFile, newFile, compilation_level, detail_level); if (!string.IsNullOrEmpty(externs)) { foreach (var extfile in externs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { if (!extfile.EndsWith("js")) { var outputfile = BuildJSFeature(new[] { extfile }, extfile + ".js"); argumentBuilder.AppendFormat(" --externs {0}", outputfile); } else { argumentBuilder.AppendFormat(" --externs {0}{1}", workingdir, extfile); } } } // google map extern http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/ argumentBuilder.Append(" --externs D:/code/clearpixels/clearpixels.closure/externs/google_maps_api_v3_9.js"); p.StartInfo = new ProcessStartInfo { FileName = "java", Arguments = argumentBuilder.ToString(), UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true }; p.StartInfo.EnvironmentVariables["Path"] = Environment.GetEnvironmentVariable("Path"); try { if (compilation_level != "NONE") { p.Start(); string[] warnings = p.StandardError.ReadToEnd() .Replace("\r", String.Empty) .Split(new[] { "\n\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var warning in warnings) { Debug.WriteLine(warning); } p.WaitForExit(5000); } } catch (Exception ex) { Syslog.Write(ex); } } }
public static void GenerateDefaultStructures(long subdomainid) { using (var repository = new TradelrRepository()) { var mastersubdomain = repository.GetSubDomain(subdomainid); if (mastersubdomain == null) { Syslog.Write("Can't generate liquid structures for domainid: " + subdomainid); return; } if (mastersubdomain.theme != null) { // already initialise, return return; } // init default theme (SOLO) mastersubdomain.theme = new DBML.theme() { created = DateTime.UtcNow, title = "Solo", preset = "", url = "/Content/templates/store/themes/solo/thumb.jpg" }; // do liquid stuff var page_about = new page() { name = "About Us", permalink = "about-us", creator = mastersubdomain.organisation.users.First().id, updated = DateTime.UtcNow, settings = (int)PageSettings.VISIBLE }; using (var reader = File.OpenText(GeneralConstants.APP_ROOT_DIR + "Content/templates/store/aboutus.txt")) { page_about.content = reader.ReadToEnd(); } mastersubdomain.pages.Add(page_about); var linklist_mainmenu = new linklist() { permalink = "main-menu", permanent = true, title = "Main Menu" }; mastersubdomain.linklists.Add(linklist_mainmenu); var link_home = new link { title = "Home", type = (int)LinkType.FRONTPAGE, url = "/" }; var link_catalog = new link() { title = "Catalog", type = (int)LinkType.WEB, url = "/collections/all" }; var link_about = new link() { title = "About Us", type = (int)LinkType.PAGE, url = "/pages/about-us" }; linklist_mainmenu.links.Add(link_home); linklist_mainmenu.links.Add(link_catalog); linklist_mainmenu.links.Add(link_about); var linklist_footer = new linklist() { permalink = "footer", permanent = true, title = "Footer" }; mastersubdomain.linklists.Add(linklist_footer); var link_search = new link { title = "Search", type = (int)LinkType.SEARCHPAGE, url = "/search" }; linklist_footer.links.Add(link_search); linklist_footer.links.Add(link_about); // create default collection var collection = new product_collection() { name = "Frontpage", permalink = "frontpage", settings = (int)(CollectionSettings.VISIBLE | CollectionSettings.PERMANENT) }; mastersubdomain.product_collections.Add(collection); // finally save repository.Save(); // copy theme files var handler = new ThemeHandler(mastersubdomain, false); new Thread(() => { var source = new DirectoryInfo(GeneralConstants.APP_ROOT_DIR + "Content/templates/store/themes/solo"); handler.CopyThemeToUserThemeDirectory(source); }).Start(); // copy mobile theme files var handler_mobile = new ThemeHandler(mastersubdomain, true); new Thread(() => { var source = handler.GetMobileThemeRepositorySourceDir(); handler_mobile.CopyThemeToUserThemeDirectory(source); }).Start(); } }
// json is true when checkout is done from an iframe, eg. facebook page public ActionResult create(CheckoutStatus status, string shippingmethod, string paymentmethod, bool isJson = false) { Debug.Assert(!cart.orderid.HasValue); var shop_owner = cart.MASTERsubdomain.organisation.users.First(); var currency = cart.MASTERsubdomain.currency.ToCurrency(); var buyer = cart.user; var transaction = new Transaction(cart.MASTERsubdomain, buyer, TransactionType.INVOICE, repository, sessionid.Value); transaction.CreateTransaction( repository.GetNewOrderNumber(subdomainid.Value, TransactionType.INVOICE), DateTime.UtcNow, cart.MASTERsubdomain.paymentTerms, currency.id); // mark as sent transaction.UpdateOrderStatus(OrderStatus.SENT); var shoppingcart = new ShoppingCart(currency.code) { shippingMethod = shippingmethod }; foreach (var item in cart.cartitems) { var checkOutItem = item.product_variant.ToCheckoutItem(item.quantity, sessionid); var orderItem = new orderItem { description = item.product_variant.ToProductFullTitle(), variantid = item.product_variant.id, unitPrice = item.product_variant.product.ToUserPrice(cart.userid.Value), tax = item.product_variant.product.tax, quantity = item.quantity }; transaction.AddOrderItem(orderItem, item.product_variant.product.products_digitals); // update inventory transaction.UpdateInventoryItem(orderItem, item.quantity); shoppingcart.items.Add(checkOutItem); } if (!cart.isDigitalOrder()) { shoppingcart.CalculateShippingCost(cart.cartitems.Select(x => x.product_variant).AsQueryable(), cart.MASTERsubdomain, buyer); if (cart.cartitems.Select(x => x.product_variant.product.shippingProfile).UseShipwire()) { transaction.UpdateShippingMethod(shoppingcart.shipwireShippingName, shoppingcart.shippingMethod); } else { transaction.UpdateShippingMethod(shoppingcart.shippingMethod); } } transaction.UpdateTotal(cart.coupon); transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE repository.AddActivity(buyer.id, new ActivityMessage(transaction.GetID(), shop_owner.id, ActivityMessageType.INVOICE_NEW, new HtmlLink(transaction.GetOrderNumber(), transaction.GetID()).ToTransactionString(TransactionType.INVOICE)), subdomainid.Value); // add checkout note as a comment if (!string.IsNullOrEmpty(cart.note)) { transaction.AddComment(cart.note, cart.userid.Value); } // add comment if shipping method not specified if (!transaction.HasShippingMethod() && !cart.isDigitalOrder()) { transaction.AddComment(OrderComment.SHIPPING_WAIT_FOR_COST); } // set cart as processed cart.orderid = transaction.GetID(); // save payment method if (!string.IsNullOrEmpty(paymentmethod)) { switch (paymentmethod) { case "paypal": cart.paymentMethod = PaymentMethodType.Paypal.ToString(); break; default: cart.paymentMethod = PaymentMethodType.Custom.ToString(); cart.paymentCustomId = long.Parse(paymentmethod); break; } } repository.Save(); // send emails // send mail to buyer var buyerEmailContent = new OrderReceipt() { viewloc = cart.MASTERsubdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()), shopname = cart.MASTERsubdomain.storeName, date = transaction.GetOrderDate().ToShortDateString(), shippingAddress = transaction.GetShippingAddress().ToHtmlString(), billingAddress = transaction.GetBillingAddress().ToHtmlString(), subtotal = string.Format("{0}{1}", currency.symbol, transaction.GetSubTotal().ToString("n" + currency.decimalCount)), shippingcost = string.Format("{0}{1}", currency.symbol, transaction.GetShippingCost().ToString("n" + currency.decimalCount)), discount = string.Format("{0}{1}", currency.symbol, transaction.GetDiscount().ToString("n" + currency.decimalCount)), totalcost = string.Format("{0}{1}{2}", currency.code, currency.symbol, transaction.GetTotal().ToString("n" + currency.decimalCount)), orderitems = transaction .GetOrderItems() .Select(x => string.Format("{0} x {1}{2} {3}", x.quantity, currency.symbol, x.unitPrice.Value.ToString("n" + currency.decimalCount), x.description)) }; // send mail to seller var sellerEmailContent = new NewOrderEmailContent { viewloc = cart.MASTERsubdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()), sender = buyer.organisation1.name }; string buyer_subject; string seller_subject; switch (status) { case CheckoutStatus.SHIPPING_FAIL: buyer_subject = string.Format("[{0}]Invoice #{1}", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); seller_subject = string.Format("[{0}]New Invoice #{1} : ACTION REQUIRED", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); buyerEmailContent.message = "Thank you for placing an order with us. Unfortunately, we are not able to provide a shipping cost at this moment. We will contact you once we have the shipping costs. You can check the status of your order by following the link below:"; sellerEmailContent.message = "A customer has placed an order on your online store. However, the shipping cost could not be calculated. You will need to manually update the invoice with the shipping cost. To update the invoice, follow the link below:"; break; case CheckoutStatus.SHIPPING_NONE: case CheckoutStatus.SHIPPING_OK: buyer_subject = string.Format("[{0}]Invoice #{1} confirmed", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); seller_subject = string.Format("[{0}]New Invoice #{1}", cart.MASTERsubdomain.name, transaction.GetOrderNumber()); if (cart.isDigitalOrder()) { buyerEmailContent.message = "Download links will be provided once payment is confirmed"; } sellerEmailContent.message = "A customer has placed an order on your online store. To view the invoice, follow the link below:"; break; default: throw new ArgumentOutOfRangeException("status"); } this.SendEmail(EmailViewType.INVOICEORDER_NEW, sellerEmailContent, seller_subject, shop_owner.GetEmailAddress(), shop_owner.ToFullName(), buyer); this.SendEmail(EmailViewType.ORDER_RECEIPT, buyerEmailContent, buyer_subject, buyer.GetEmailAddress(), buyer.ToFullName(), shop_owner); // handle payment string redirecturl = ""; if (!string.IsNullOrEmpty(paymentmethod)) { switch (paymentmethod) { case "paypal": string returnUrl; if (isJson) { returnUrl = string.Format("{0}/checkout/order/{1}/close", GeneralConstants.HTTP_SECURE, cart.id); } else { returnUrl = string.Format("{0}/checkout/order/{1}", GeneralConstants.HTTP_SECURE, cart.id); } var pworker = new PaypalWorker(cart.id.ToString(), transaction, repository, cart.MASTERsubdomain.GetPaypalID(), transaction.GetCurrency().id, returnUrl); try { redirecturl = pworker.GetPaymentUrl(); } catch (Exception ex) { Syslog.Write(ex); return(RedirectToAction("Index", "Error")); } break; default: break; } } if (!string.IsNullOrEmpty(redirecturl)) { return(Redirect(redirecturl)); } if (isJson) { return(View("close")); } return(RedirectToAction("Index")); }
public override void Hook_PRIV(Channel channel, libirc.UserInfo invoker, string message) { // "\uff01" is the full-width version of "!". if ((message.StartsWith("!") || message.StartsWith("\uff01")) && GetConfig(channel, "Infobot.Enabled", true)) { while (Unwritable) { Thread.Sleep(10); } Unwritable = true; Infobot.InfoItem item = new Infobot.InfoItem { Channel = channel, Name = "!" + message.Substring(1), User = invoker, }; jobs.Add(item); Unwritable = false; } Infobot infobot = null; if (message.StartsWith(Configuration.System.CommandPrefix)) { infobot = (Infobot)channel.RetrieveObject("Infobot"); if (infobot == null) { Syslog.Log("Object Infobot in " + channel.Name + " doesn't exist", true); } if (GetConfig(channel, "Infobot.Enabled", true)) { if (infobot != null) { infobot.Find(message, channel); infobot.RSearch(message, channel); } } } if (Snapshots) { if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-recovery ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionRestoreSnapshot)) { string name = message.Substring("@infobot-recovery ".Length); if (!GetConfig(channel, "Infobot.Enabled", true)) { IRC.DeliverMessage("Infobot is not enabled in this channel", channel, libirc.Defs.Priority.Low); return; } if (infobot != null) { infobot.RecoverSnapshot(channel, name); } return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-snapshot ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionSnaphot)) { string name = message.Substring("@infobot-snapshot ".Length); if (!GetConfig(channel, "Infobot.Enabled", true)) { IRC.DeliverMessage("Infobot is not enabled in this channel", channel, libirc.Defs.Priority.Low); return; } if (infobot != null) { infobot.CreateSnapshot(channel, name); } return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-set-raw ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionAdd)) { string name = message.Substring("@infobot-set-raw ".Length); if (!GetConfig(channel, "Infobot.Enabled", true)) { IRC.DeliverMessage("Infobot is not enabled in this channel", channel, libirc.Defs.Priority.Low); return; } if (infobot != null) { infobot.SetRaw(name, invoker.Nick, channel); return; } } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-unset-raw ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionAdd)) { string name = message.Substring("@infobot-unset-raw ".Length); if (!GetConfig(channel, "Infobot.Enabled", true)) { IRC.DeliverMessage("Infobot is not enabled in this channel", channel, libirc.Defs.Priority.Low); return; } if (infobot != null) { infobot.UnsetRaw(name, invoker.Nick, channel); return; } } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-snapshot-rm ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionDeleteSnapshot)) { string name = message.Substring("@infobot-snapshot-rm ".Length); name.Replace(".", ""); name.Replace("/", ""); name.Replace("\\", ""); name.Replace("*", ""); name.Replace("?", ""); if (name == "") { IRC.DeliverMessage("You should specify a file name", channel); return; } if (!File.Exists(SnapshotsDirectory + Path.DirectorySeparatorChar + channel.Name + Path.DirectorySeparatorChar + name)) { IRC.DeliverMessage("File not found", channel); return; } File.Delete(SnapshotsDirectory + Path.DirectorySeparatorChar + channel.Name + Path.DirectorySeparatorChar + name); IRC.DeliverMessage("Requested file was removed", channel); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel); } return; } if (message == Configuration.System.CommandPrefix + "infobot-snapshot-ls") { string files = ""; DirectoryInfo di = new DirectoryInfo(SnapshotsDirectory + Path.DirectorySeparatorChar + channel.Name); FileInfo[] rgFiles = di.GetFiles("*"); int curr = 0; int displaying = 0; foreach (FileInfo fi in rgFiles) { curr++; if (files.Length < 200) { files += fi.Name + " "; displaying++; } } string response; if (curr == displaying) { response = "There are " + displaying + " files: " + files; } else { response = "There are " + curr + " files, but displaying only " + displaying + " of them: " + files; } if (curr == 0) { response = "There is no snapshot so far, create one!:)"; } IRC.DeliverMessage(response, channel.Name); return; } } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-share-trust+ ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionShare)) { if (channel.SharedDB != "local") { IRC.DeliverMessage(messages.Localize("infobot16", channel.Language), channel); return; } if (channel.SharedDB != "local" && channel.SharedDB != "") { IRC.DeliverMessage(messages.Localize("infobot15", channel.Language), channel); return; } if (message.Length <= "@infobot-share-trust+ ".Length) { IRC.DeliverMessage(messages.Localize("db6", channel.Language), channel.Name); return; } string name = message.Substring("@infobot-share-trust+ ".Length); Channel guest = Core.GetChannel(name); if (guest == null) { IRC.DeliverMessage(messages.Localize("db8", channel.Language), channel.Name); return; } if (channel.SharedLinkedChan.Contains(guest)) { IRC.DeliverMessage(messages.Localize("db14", channel.Language), channel.Name); return; } IRC.DeliverMessage(messages.Localize("db1", channel.Language, new List <string> { name }), channel.Name); lock (channel.SharedLinkedChan) { channel.SharedLinkedChan.Add(guest); } channel.SaveConfig(); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel.Name, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-ignore- ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionIgnore)) { string item = message.Substring("@infobot-ignore+ ".Length); if (item != "") { if (!channel.Infobot_IgnoredNames.Contains(item)) { IRC.DeliverMessage(messages.Localize("infobot-ignore-found", channel.Language, new List <string> { item }), channel); return; } channel.Infobot_IgnoredNames.Remove(item); IRC.DeliverMessage(messages.Localize("infobot-ignore-rm", channel.Language, new List <string> { item }), channel); channel.SaveConfig(); return; } } else { if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } } } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-ignore+ ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionIgnore)) { string item = message.Substring("@infobot-ignore+ ".Length); if (item != "") { if (channel.Infobot_IgnoredNames.Contains(item)) { IRC.DeliverMessage(messages.Localize("infobot-ignore-exist", channel.Language, new List <string> { item }), channel); return; } channel.Infobot_IgnoredNames.Add(item); IRC.DeliverMessage(messages.Localize("infobot-ignore-ok", channel.Language, new List <string> { item }), channel); channel.SaveConfig(); return; } } else { if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } } } if (message == Configuration.System.CommandPrefix + "infobot-off") { if (channel.SystemUsers.IsApproved(invoker, PermissionManage)) { if (!GetConfig(channel, "Infobot.Enabled", true)) { IRC.DeliverMessage(messages.Localize("infobot1", channel.Language), channel); return; } IRC.DeliverMessage(messages.Localize("infobot2", channel.Language), channel, libirc.Defs.Priority.High); SetConfig(channel, "Infobot.Enabled", false); channel.SaveConfig(); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-share-trust- ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionShare)) { if (channel.SharedDB != "local") { IRC.DeliverMessage(messages.Localize("infobot16", channel.Language), channel); return; } if (message.Length <= "@infobot-share-trust+ ".Length) { IRC.DeliverMessage(messages.Localize("db6", channel.Language), channel); return; } string name = message.Substring("@infobot-share-trust- ".Length); Channel target = Core.GetChannel(name); if (target == null) { IRC.DeliverMessage(messages.Localize("db8", channel.Language), channel); return; } if (channel.SharedLinkedChan.Contains(target)) { channel.SharedLinkedChan.Remove(target); IRC.DeliverMessage(messages.Localize("db2", channel.Language, new List <string> { name }), channel); channel.SaveConfig(); return; } IRC.DeliverMessage(messages.Localize("db4", channel.Language), channel); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-detail ")) { if ((message.Length) <= "@infobot-detail ".Length) { IRC.DeliverMessage(messages.Localize("db6", channel.Language), channel); return; } if (GetConfig(channel, "Infobot.Enabled", true)) { if (channel.SharedDB == "local" || channel.SharedDB == "") { if (infobot != null) { infobot.InfobotDetail(message.Substring(16), channel); } return; } if (channel.SharedDB != "") { Channel db = Core.GetChannel(channel.SharedDB); if (db == null) { IRC.DeliverMessage("Error, null pointer to shared channel", channel, libirc.Defs.Priority.Low); return; } if (infobot != null) { infobot.InfobotDetail(message.Substring(16), channel); } return; } return; } IRC.DeliverMessage("Infobot is not enabled on this channel", channel, libirc.Defs.Priority.Low); return; } if (message.StartsWith(Configuration.System.CommandPrefix + "infobot-link ")) { if (channel.SystemUsers.IsApproved(invoker, PermissionShare)) { if (channel.SharedDB == "local") { IRC.DeliverMessage(messages.Localize("infobot17", channel.Language), channel); return; } if (channel.SharedDB != "") { IRC.DeliverMessage(messages.Localize("infobot18", channel.Language, new List <string> { channel.SharedDB }), channel); return; } if ((message.Length - 1) < "@infobot-link ".Length) { IRC.DeliverMessage(messages.Localize("db6", channel.Language), channel); return; } string name = message.Substring("@infobot-link ".Length); Channel db = Core.GetChannel(name); if (db == null) { IRC.DeliverMessage(messages.Localize("db8", channel.Language), channel); return; } if (!Infobot.Linkable(db, channel)) { IRC.DeliverMessage(messages.Localize("db9", channel.Language), channel); return; } channel.SharedDB = name.ToLower(); IRC.DeliverMessage(messages.Localize("db10", channel.Language), channel); channel.SaveConfig(); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message == Configuration.System.CommandPrefix + "infobot-share-off") { if (channel.SystemUsers.IsApproved(invoker, PermissionShare)) { if (channel.SharedDB == "") { IRC.DeliverMessage(messages.Localize("infobot14", channel.Language), channel); return; } IRC.DeliverMessage(messages.Localize("infobot13", channel.Language), channel); foreach (Channel curr in Configuration.ChannelList) { if (curr.SharedDB == channel.Name.ToLower()) { curr.SharedDB = ""; curr.SaveConfig(); IRC.DeliverMessage(messages.Localize("infobot19", curr.Language, new List <string> { invoker.Nick }), curr); } } channel.SharedDB = ""; channel.SaveConfig(); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message == Configuration.System.CommandPrefix + "infobot-on") { if (channel.SystemUsers.IsApproved(invoker, PermissionManage)) { if (GetConfig(channel, "Infobot.Enabled", true)) { IRC.DeliverMessage(messages.Localize("infobot3", channel.Language), channel); return; } SetConfig(channel, "Infobot.Enabled", true); channel.SaveConfig(); IRC.DeliverMessage(messages.Localize("infobot4", channel.Language), channel, libirc.Defs.Priority.High); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } return; } if (message == Configuration.System.CommandPrefix + "infobot-share-on") { if (channel.SystemUsers.IsApproved(invoker, PermissionShare)) { if (channel.SharedDB == "local") { IRC.DeliverMessage(messages.Localize("infobot11", channel.Language), channel, libirc.Defs.Priority.High); return; } if (channel.SharedDB != "local" && channel.SharedDB != "") { IRC.DeliverMessage(messages.Localize("infobot15", channel.Language), channel, libirc.Defs.Priority.High); return; } IRC.DeliverMessage(messages.Localize("infobot12", channel.Language), channel); channel.SharedDB = "local"; channel.SaveConfig(); return; } if (!channel.SuppressWarnings) { IRC.DeliverMessage(messages.Localize("PermissionDenied", channel.Language), channel, libirc.Defs.Priority.Low); } } }
/// <summary> /// /// </summary> /// <param name="entry"></param> /// <param name="isAsync"></param> /// <param name="repository">if specified, email is queued</param> public static void SendMail(mail entry, bool isAsync, bool queueMail) { // need to check for invalid email address if (!entry.toEmail.IsEmail()) { return; } if (queueMail) { // queue it instead using (var db = new tradelrDataContext()) { db.mails.InsertOnSubmit(entry); db.SubmitChanges(); } return; } var from = new MailAddress(MAIL_SOURCE_ADDRESS, "tradelr", Encoding.UTF8); MailAddress replyto = null; if (!string.IsNullOrEmpty(entry.fromEmail)) { replyto = new MailAddress(entry.fromEmail, entry.fromName, Encoding.UTF8); } else { entry.fromEmail = MAIL_SOURCE_ADDRESS; entry.fromName = "tradelr"; } var to = new MailAddress(entry.toEmail, entry.toName, Encoding.UTF8); var msg = new MailMessage(from, to) { Body = entry.body, IsBodyHtml = true, BodyEncoding = Encoding.UTF8, Subject = entry.subject, SubjectEncoding = Encoding.UTF8 }; if (replyto != null) { msg.ReplyToList.Add(replyto); } #if DEBUG var smtp = new SmtpClient(MAIL_SERVER, 587) { EnableSsl = true }; var cred = new NetworkCredential("*****@*****.**", MAIL_PASSWORD); //smtp.Timeout = 10000; #else SmtpClient smtp = new SmtpClient(MAIL_SERVER); NetworkCredential cred = new NetworkCredential(MAIL_SOURCE_ADDRESS, MAIL_PASSWORD); #endif new Thread(() => { smtp.Credentials = cred; if (isAsync) { smtp.SendCompleted += SendCompletedCallback; smtp.SendAsync(msg, entry); } else { try { smtp.Send(msg); } catch (Exception ex) { Syslog.Write(ex); } } }).Start(); }
public IQueryable <user> GetUsers(long?viewerid, UserAuth viewer_auth, int?school, int?schoolClass, UserGroup?group, string discipline, AttendanceStatus?attendanceStatus, string attendanceDate, int year, int?eca, bool active = true, bool hasIssues = false) { /* * var loadOptions = new DataLoadOptions(); * loadOptions.LoadWith<user>(x => x.user_image); * loadOptions.LoadWith<user>(x => x.user_parents); * loadOptions.LoadWith<user>(x => x.school); * * db.LoadOptions = loadOptions; * db.DeferredLoadingEnabled = false; */ var usrs = db.users.AsQueryable(); if (group.HasValue) { usrs = usrs.Where(x => (x.usergroup & (int)group.Value) != 0); } if (active) { usrs = usrs.Where(x => (x.settings & (int)UserSettings.INACTIVE) == 0); } else { usrs = usrs.Where(x => (x.settings & (int)UserSettings.INACTIVE) != 0); } if (schoolClass.HasValue) { var teachers = usrs.SelectMany(x => x.classes_teachers_allocateds) .Where(y => y.classid == schoolClass.Value && y.year == year) .Select(x => x.user); var students = usrs.SelectMany(x => x.classes_students_allocateds) .Where(y => y.classid == schoolClass.Value && y.year == year) .Select(x => x.user); //var parents = students.SelectMany(x => x.students_guardians).Select(y => y.user1); usrs = teachers.Union(students).Distinct(); } else if (school.HasValue) { usrs = usrs.Where(x => x.schoolid.HasValue && x.schoolid.Value == school); } else { var teachers = usrs.SelectMany(x => x.classes_teachers_allocateds) .Where(y => y.year == year) .Select(x => x.user); var students = usrs.SelectMany(x => x.classes_students_allocateds) .Where(y => y.year == year) .Select(x => x.user); //var parents = students.SelectMany(x => x.students_guardians).Select(y => y.user1); // now get others exclude teachers and students var others = usrs.Where(x => (x.usergroup & (int)(UserGroup.STUDENT | UserGroup.TEACHER)) == 0); usrs = teachers.Union(students).Union(others).Distinct(); } if (eca.HasValue) { usrs = usrs.Where( x => x.usergroup == (int)UserGroup.STUDENT && x.eca_students.Count(y => y.ecaid == eca.Value && y.year == year) != 0); } if (!string.IsNullOrEmpty(discipline)) { // discipline can somehow end up as undefined try { var sorter = new Sorter(discipline); if (sorter.type == SorterType.LESSTHAN) { usrs = usrs.Where(x => x.students_disciplines.Where(w => w.created.Year == year).Sum(y => y.points) <= sorter.value && x.students_disciplines.Where(w => w.created.Year == year).Sum(y => y.points) != 0); } else { usrs = usrs.Where(x => x.students_disciplines.Where(w => w.created.Year == year).Sum(y => y.points) >= sorter.value && x.students_disciplines.Where(w => w.created.Year == year).Sum(y => y.points) != 0); } } catch (Exception ex) { Syslog.Write(ex); Syslog.Write(ErrorLevel.WARNING, viewerid.HasValue?viewerid.Value.ToString():""); } } if (!string.IsNullOrEmpty(attendanceDate) && attendanceStatus.HasValue) { DateTime date; if (DateTime.TryParseExact(attendanceDate, Constants.DATEFORMAT_DATEPICKER, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { usrs = usrs.SelectMany(x => x.attendances).Where(x => x.date == date && x.status == attendanceStatus.Value.ToString()).Select(x => x.user); } } // filter here if (viewer_auth != null && viewerid.HasValue) { if (UserSuperGroups.STAFF.HasFlag(viewer_auth.group)) { var student = Enumerable.Empty <user>(); var parents = Enumerable.Empty <user>(); var staff = Enumerable.Empty <user>(); if ((viewer_auth.perms & (Permission.USERS_VIEW_STUDENTS | Permission.USERS_EDIT_STUDENTS)) != 0) { student = usrs.Where(x => x.usergroup == (int)UserGroup.STUDENT); } if ((viewer_auth.perms & (Permission.USERS_VIEW_PARENTS | Permission.USERS_EDIT_PARENTS)) != 0) { parents = usrs.Where(x => x.usergroup == (int)UserGroup.GUARDIAN); } if ((viewer_auth.perms & (Permission.USERS_VIEW_STAFF | Permission.USERS_EDIT_STAFF)) != 0) { staff = usrs.Where(x => (x.usergroup & (int)UserSuperGroups.STAFF) != 0); } usrs = student.Union(parents).Union(staff).AsQueryable(); } else { usrs = Enumerable.Empty <user>().AsQueryable(); } } // do issue checking last as this is quite intensive if (hasIssues) { usrs = usrs.ToArray().Where(x => x.GetIssues(year, true) != UserIssue.NONE).AsQueryable(); } return(usrs); }
protected ResponseData <T> SendRequest <T>(Parameters prms = null, bool isMultiPart = false) { parameters = prms ?? new Parameters(); // build the uri var actionUrl = GetAction(URI); WebRequest req; if (method == "POST" || method == "PUT" || method == "DELETE") { requestUrl = new Uri(string.Concat(Constants.BaseUrl, actionUrl)); if (isMultiPart) { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); req = WebRequest.Create(requestUrl); req.ContentType = "multipart/form-data; boundary=" + boundary; req.Method = "POST"; Stream rs = req.GetRequestStream(); const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; foreach (string key in parameters.parameters.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, parameters.parameters[key]); byte[] formitembytes = Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } rs.Write(boundarybytes, 0, boundarybytes.Length); const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "image", DateTime.UtcNow.Ticks, "multipart/form-data"); byte[] headerbytes = Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } fileStream.Close(); byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); } else { req = WebRequest.Create(requestUrl); req.Method = method; using (var sw = new StreamWriter(req.GetRequestStream())) { sw.Write(parameters.ToQueryString().Substring(1)); // skips the ? } } } else { requestUrl = new Uri(string.Concat(Constants.BaseUrl, actionUrl, parameters.ToQueryString())); req = WebRequest.Create(requestUrl); req.Method = "GET"; } if (isPrivate) { if (!string.IsNullOrEmpty(info.oauth_key) && !string.IsNullOrEmpty(info.oauth_secret)) { req.Headers.Add(OAuthUtil.GenerateHeader(requestUrl, Constants.ApplicationKey, Constants.ApplicationSecret, info.oauth_key, info.oauth_secret, method)); } else { throw new AuthenticationException("etsy not authenticated: " + requestUrl); } } string jsonString = ""; WebResponse resp; try { resp = req.GetResponse(); using (var sr = new StreamReader(resp.GetResponseStream())) { jsonString = sr.ReadToEnd(); } if (!string.IsNullOrEmpty(jsonString)) { return(serializer.Deserialize <ResponseData <T> >(jsonString)); } } catch (WebException ex) { resp = ex.Response; if (resp != null) { using (var sr = new StreamReader(resp.GetResponseStream())) { var error = sr.ReadToEnd(); Syslog.Write("Etsy Error: " + requestUrl + " " + error); } } } catch (Exception ex) { Syslog.Write(string.Format("{0}:{1}", ex.Message, jsonString)); } return(null); }
public ActionResult NetworkFind(string id) { if (string.IsNullOrEmpty(id)) { return(Json(JavascriptReturnCodes.NOTFOUND.ToJsonOKData())); } Uri networkUri = null; try { if (id.IndexOf('.') == -1) { // user only enter store name id = string.Format("{0}.tradelr.com", id); } if (!id.StartsWith("http")) { // user did not enter http id = string.Format("http://{0}", id); } networkUri = new Uri(id); } catch (Exception ex) { Syslog.Write("Unable to parse " + id); } // we only get creators user usr; if (networkUri != null) { if (networkUri.Host.Split('.').Length < 3) { return(Json(JavascriptReturnCodes.NOTFOUND.ToJsonOKData())); } if (networkUri.Host.Contains("tradelr.com")) { var subdomainname = networkUri.Host.Substring(0, networkUri.Host.IndexOf('.')); var sd = repository.GetSubDomains().Where(x => x.name == subdomainname).SingleOrDefault(); if (sd == null) { return(Json(JavascriptReturnCodes.NOTFOUND.ToJsonOKData())); } usr = sd.organisation.users.First(); } else { // custom domain var sd = repository.GetSubDomains().Where(x => x.customDomain == networkUri.Host).SingleOrDefault(); if (sd == null) { return(Json(JavascriptReturnCodes.NOTFOUND.ToJsonOKData())); } usr = sd.organisation.users.First(); } } else { usr = repository.GetUsersByEmail(id).Where(x => (x.role & (int)UserRole.CREATOR) != 0).SingleOrDefault(); } // return detail of contact found if (usr != null && subdomainid.HasValue && usr.organisation1.subdomain != subdomainid.Value) { // check that we're not already linked var linked = repository.IsFriend(subdomainid.Value, usr.organisation1.subdomain); if (linked) { return(Json(JavascriptReturnCodes.ISLINKED.ToJsonOKData())); } return(Json(usr.ToModelBasic().ToJsonOKData())); } return(Json(JavascriptReturnCodes.NOTFOUND.ToJsonOKData())); }
public ActionResult Import(string type, string token) { var owner = db.GetUserById(sessionid.Value, subdomainid.Value); var viewdata = new ImportContactsViewData(baseviewmodel) { hostName = accountHostname, fbuid = owner.FBID, subdomainid = subdomainid.Value, appid = sessionid.Value }; // facebook var connectSession = UtilFacebook.GetConnectSession(); if (connectSession.IsConnected()) { var api = new Api(connectSession); IList <long> fdlist = api.Friends.GetAppUsers(); string s = string.Empty; for (int i = 0; i < fdlist.Count; i++) { s += fdlist[i].ToString(); if (i != fdlist.Count - 1) { s += ","; } } viewdata.invitedFbuidList = s; } // if callback from authsub authorisation if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(token)) { var importType = type.ToEnum <ContactImportType>(); switch (importType) { case ContactImportType.GOOGLE: var requestFactory = new GAuthSubRequestFactory("cp", "tradelr"); requestFactory.Token = token; var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); //query.OAuthRequestorId = string.Concat(sessionid.Value, '@', subdomainid.Value); var service = new ContactsService(requestFactory.ApplicationName); service.RequestFactory = requestFactory; try { var feed = service.Query(query); var contacts = new List <ContactBasic>(); foreach (ContactEntry entry in feed.Entries) { string email; // primary email can be null if (entry.PrimaryEmail == null) { if (entry.Emails == null || entry.Emails.Count == 0) { continue; // skip entry, cannot find email } email = entry.Emails[0].Address; } else { email = entry.PrimaryEmail.Address; } var contact = new ContactBasic() { address = entry.BillingInformation, companyName = email, email = email }; if (entry.Name != null) { if (!string.IsNullOrEmpty(entry.Name.GivenName)) { contact.firstName = entry.Name.GivenName; } if (!string.IsNullOrEmpty(entry.Name.FamilyName)) { contact.lastName = entry.Name.FamilyName; } } if (entry.PrimaryPhonenumber == null) { if (entry.Phonenumbers != null && entry.Phonenumbers.Count != 0) { contact.phone = entry.Phonenumbers[0].Value; } } else { contact.phone = entry.PrimaryPhonenumber.Value; } // now we need to format it nicely for display purposes contacts.Add(contact); } viewdata.contacts = contacts.OrderBy(x => x.email); } catch (Exception ex) { Syslog.Write(ex); } break; default: break; } } return(View(viewdata)); }
private void CacheItemRemovedCallback( string key, object value, CacheItemRemovedReason reason ) { //if (reason != CacheItemRemovedReason.Expired) //{ // eJException newex = new eJException(); // newex.logException("cacheExpired: " + key + " " + reason.ToString(), null); //} Debug.WriteLine("Cache Expired: " + key); switch (key.ToEnum <CacheTimerType>()) { #if DEBUG case CacheTimerType.Minute5: var thread = new Thread(ScheduledTask.SendEmails) { Name = TaskType.Email.ToString() }; if (!runningThreads.ContainsKey(TaskType.Email)) { runningThreads.Add(TaskType.Email, thread); thread.Start(); } else { if (!runningThreads[TaskType.Email].IsAlive) { runningThreads[TaskType.Email] = thread; thread.Start(); } } thread = new Thread(ScheduledTask.SetStudentInactiveIfLeavingDateSet) { Name = TaskType.Registration.ToString() }; if (!runningThreads.ContainsKey(TaskType.Registration)) { runningThreads.Add(TaskType.Registration, thread); thread.Start(); } else { if (!runningThreads[TaskType.Registration].IsAlive) { runningThreads[TaskType.Registration] = thread; thread.Start(); } } break; #else case CacheTimerType.Minute1: break; case CacheTimerType.Minute5: var thread = new Thread(ScheduledTask.SendEmails) { Name = TaskType.Email.ToString() }; if (!runningThreads.ContainsKey(TaskType.Email)) { runningThreads.Add(TaskType.Email, thread); thread.Start(); } else { if (!runningThreads[TaskType.Email].IsAlive) { runningThreads[TaskType.Email] = thread; thread.Start(); } } break; case CacheTimerType.Minute10: break; case CacheTimerType.Minute60: thread = new Thread(ScheduledTask.SetStudentInactiveIfLeavingDateSet) { Name = TaskType.Registration.ToString() }; if (!runningThreads.ContainsKey(TaskType.Registration)) { runningThreads.Add(TaskType.Registration, thread); thread.Start(); } else { if (!runningThreads[TaskType.Registration].IsAlive) { runningThreads[TaskType.Registration] = thread; thread.Start(); } } break; #endif default: #if !DEBUG Syslog.Write(ErrorLevel.CRITICAL, "CacheScheduler ERROR: " + key); #endif break; } HitPage(); }
public ActionResult Import(bool ismobile) { Stream inputStream; if (Request.Files.Count != 0) { inputStream = Request.Files[0].InputStream; } else { inputStream = Request.InputStream; } inputStream.Position = 0; var handler = new ThemeHandler(MASTERdomain, ismobile); try { var themedir = handler.ClearUserThemeDirectory(); using (var s = new ZipInputStream(inputStream)) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { Console.WriteLine(theEntry.Name); string directoryName = Path.GetDirectoryName(string.Format("{0}/{1}", themedir.FullName, theEntry.Name)); string fileName = Path.GetFileName(string.Format("{0}/{1}", themedir.FullName, theEntry.Name)); // create directory if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty) { using (FileStream streamWriter = System.IO.File.Create(string.Format("{0}/{1}", themedir.FullName, theEntry.Name))) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } } } catch (Exception ex) { Syslog.Write(ex); return(Json("Failed to extract theme files".ToJsonFail())); } // update theme var theme = MASTERdomain.theme; if (theme == null) { theme = new theme(); MASTERdomain.theme = theme; } theme.title = ThemeHandler.CustomThemeName; theme.url = "/Content/img/store/custom_theme.png"; theme.created = DateTime.UtcNow; // remove custom templates from existing pages var pages = MASTERdomain.pages.Where(x => !string.IsNullOrEmpty(x.templatename)); foreach (var page in pages) { page.templatename = ""; } repository.Save(); // need to invalidate any cached liquid assets CacheHelper.Instance.invalidate_dependency(DependencyType.liquid_assets, MASTERdomain.uniqueid); return(Json("Theme imported successfully".ToJsonOKMessage())); }
public bool GetRequestToken() { BuildRequestUrl(); string content; WebResponse response; try { var request = WebRequest.Create(requestUrl); request.Method = "GET"; response = request.GetResponse(); using (var sr = new StreamReader(response.GetResponseStream())) { content = sr.ReadToEnd(); } } catch (WebException ex) { response = ex.Response; if (response != null) { using (var sr = new StreamReader(response.GetResponseStream())) { var error = sr.ReadToEnd(); Syslog.Write("oauthrequest Error: " + requestUrl + " " + error); } } return(false); } parameters = HttpUtility.ParseQueryString(content); oauth_token = parameters["oauth_token"]; oauth_secret = parameters["oauth_token_secret"]; switch (type) { case OAuthTokenType.YAHOO: authorize_url = HttpUtility.UrlDecode(parameters["xoauth_request_auth_url"]); break; case OAuthTokenType.ETSY: authorize_url = HttpUtility.UrlDecode(parameters["login_url"]); break; case OAuthTokenType.TRADEME: #if DEBUG authorize_url = "https://secure.tmsandbox.co.nz/Oauth/Authorize?oauth_token=" + oauth_token; #else authorize_url = "https://secure.trademe.co.nz/Oauth/Authorize?oauth_token=" + oauth_token; #endif break; default: throw new NotImplementedException(); break; } if (String.IsNullOrEmpty(oauth_token) || String.IsNullOrEmpty(oauth_secret) || String.IsNullOrEmpty(authorize_url)) { Syslog.Write(String.Format("{0} OAuth fail", type)); return(false); } return(true); }
private static bool PaypalHandleBuyerPaidAndWeNeedToVerify(ITradelrRepository repository) { bool haveChanges = false; var paymentsNeededVerifying = repository.GetPayments(PaymentMethodType.Paypal, PaymentStatus.Charging); foreach (var payment in paymentsNeededVerifying) { var configurationMap = Configuration.GetAcctAndConfig(); var service = new AdaptivePaymentsService(configurationMap); var detailsRequest = new PaymentDetailsRequest { payKey = payment.redirectUrl.ToPayPalPayKey(), requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" }, trackingId = payment.reference }; PaymentDetailsResponse resp = null; bool haveError = false; try { resp = service.PaymentDetails(detailsRequest); } catch (Exception ex) { var affectedInvoice = payment.order; Syslog.Write( string.Format( "Failed to process payment for order {0}, payment amount of {1} deleted", affectedInvoice.id, payment.paidAmount)); Syslog.Write(ex); haveError = true; } if (!haveError && resp.responseEnvelope.ack == AckCode.SUCCESS) { var transaction = new Transaction(payment.order, repository, null); switch (resp.status) { case "COMPLETED": transaction.UpdatePaymentStatus(payment, PaymentStatus.Accepted); transaction.AddPaidAmount(payment.paidAmount); // <------- order status is updated inside here // send download links if digital order if (transaction.HasDigitalOrderItems()) { transaction.SendDownloadLinksEmail(); } haveChanges = true; break; case "ERROR": transaction.UpdatePaymentStatus(payment, PaymentStatus.Declined); haveChanges = true; break; case "EXPIRED": repository.DeletePayment(payment); haveChanges = true; break; } } } return(haveChanges); }
public ActionResult Index(string feature) { Syslog.Write("clicked: " + feature); return(new EmptyResult()); }
private void OnChange(object sender, XmlRcs.EditEventArgs ex) { ex.Change.EmptyNulls(); XmlRcs.RecentChange edit = ex.Change; if (edit.Type != XmlRcs.RecentChange.ChangeType.Edit && edit.Type != XmlRcs.RecentChange.ChangeType.New) { return; } if (edit.Type == XmlRcs.RecentChange.ChangeType.Edit && edit.RevID < 1) { Syslog.ErrorLog("RC: Invalid revid: " + edit.OriginalXml); return; } List <RecentChanges> recentChanges = new List <RecentChanges>(); RecentChanges.LastMessage = DateTime.Now; lock (RecentChanges.recentChangesList) { recentChanges.AddRange(RecentChanges.recentChangesList); } foreach (RecentChanges curr in recentChanges) { if (GetConfig(curr.channel, "RC.Enabled", false)) { lock (curr.MonitoredPages) { foreach (RecentChanges.IWatch iwatch in curr.MonitoredPages) { if (iwatch.Site == edit.ServerName || iwatch.Site == "*") { if ((!edit.Minor && edit.Bot && GetConfig(curr.channel, "Bot.Enabled", true)) || (!edit.Bot && edit.Minor && GetConfig(curr.channel, "Minor.Enabled", true)) || (!edit.Bot && !edit.Minor) || (edit.Minor && GetConfig(curr.channel, "Minor.Enabled", true) && edit.Bot && GetConfig(curr.channel, "Bot.Enabled", true))) { if (edit.Title == iwatch.Page) { if (edit.LengthNew != 0 || edit.LengthOld != 0) { int size = edit.LengthNew - edit.LengthOld; string sx = size.ToString(); if (size >= 0) { sx = "+" + sx; } edit.Summary = "[" + sx + "] " + edit.Summary; } if (iwatch.Site == null) { DebugLog("NULL pointer on idata 1", 2); } IRC.DeliverMessage(Format(edit.ServerName, edit.ServerName, edit.Title, edit.User, edit.RevID.ToString(), edit.Summary, curr.channel, edit.Bot, edit.Type == XmlRcs.RecentChange.ChangeType.New, edit.Minor), curr.channel.Name, libirc.Defs.Priority.Low); } else if (iwatch.Page.EndsWith("*") && edit.Title.StartsWith(iwatch.Page.Replace("*", ""))) { if (iwatch.Site == null) { DebugLog("NULL pointer on idata 2", 2); } IRC.DeliverMessage(Format(edit.ServerName, edit.ServerName, edit.Title, edit.User, edit.RevID.ToString(), edit.Summary, curr.channel, edit.Bot, edit.Type == XmlRcs.RecentChange.ChangeType.New, edit.Minor), curr.channel.Name, libirc.Defs.Priority.Low); } } } } } } } }
public void SetValues(string description, int?available, int?onOrder, int?reserved, int?sold) { if (available.HasValue && trackInventory && !isDigital) { if (item.available.HasValue) { item.available += available.Value; } else { item.available = available.Value; } if (item.available < 0) { Syslog.Write("-ve avalaible stock for ilocitem {0}", item.id); } CheckInventoryLevel(); } if (onOrder.HasValue) { if (item.onOrder.HasValue) { item.onOrder += onOrder.Value; } else { item.onOrder = onOrder.Value; } if (item.onOrder < 0) { Syslog.Write("-ve onorder stock for ilocitem {0}", item.id); } } if (reserved.HasValue) { if (item.reserved.HasValue) { item.reserved += reserved.Value; } else { item.reserved = reserved.Value; } if (item.reserved < 0) { Syslog.Write("-ve reserved stock for ilocitem {0}", item.id); } } if (sold.HasValue) { if (item.sold.HasValue) { item.sold += sold.Value; } else { item.sold = sold.Value; } if (item.sold < 0) { Syslog.Write("-ve sold stock for ilocitem {0}", item.id); } } var history = new inventoryHistory { created = DateTime.UtcNow, available = available, description = description, onOrder = onOrder, sold = sold, reserved = reserved }; item.inventoryHistories.Add(history); }
/// <summary> /// generates a thumbnail given the path of the original images /// </summary> /// <param name="filePath"></param> /// <param name="suffix"></param> /// <param name="desiredWidth"></param> /// <param name="desiredHeight"></param> /// <returns></returns> private static string thumbnail(string filePath, string suffix, float desiredWidth, float desiredHeight, Imgsize type) { string thumb = filePath; string file = filePath; string ext = thumb.Substring(thumb.LastIndexOf(".") + 1); thumb = thumb.Substring(0, thumb.IndexOf(".")) + "." + suffix + "." + ext; bool exists = System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + file); if (!exists) { //Syslog.Write(ErrorLevel.ERROR, string.Concat("Cannot find file: ", AppDomain.CurrentDomain.BaseDirectory + file)); return(""); } // These are the ratio calculations int width; int height; Image img = null; try { img = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + file); width = img.Width; height = img.Height; } catch (OutOfMemoryException) { Syslog.Write(ErrorLevel.ERROR, "Invalid image: " + filePath); return(""); } finally { if (img != null) { img.Dispose(); } } float factor = 0; if (width > 0 && height > 0) { float wfactor = desiredWidth / width; float hfactor = desiredHeight / height; factor = wfactor < hfactor ? wfactor : hfactor; } if (factor != 0 && factor < 1) { int twidth = Convert.ToInt32(Math.Floor(factor * width)); int theight = Convert.ToInt32(Math.Floor(factor * height)); convert(file, thumb, twidth, theight, type); } else { if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + thumb)) { System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + thumb); } System.IO.File.Copy(AppDomain.CurrentDomain.BaseDirectory + file, AppDomain.CurrentDomain.BaseDirectory + thumb); } return(thumb); }
/// <summary> /// /// </summary> /// <param name="entry"></param> /// <param name="isAsync"></param> /// <param name="queueMail"></param> /// <param name="ccList"></param> public static void SendMail(mail entry, bool isAsync, bool queueMail, IEnumerable <string> ccList = null) { // need to check for invalid email address if (!entry.toEmail.IsEmail()) { return; } if (queueMail) { // queue it instead using (var db = new ioschoolsDBDataContext()) { db.mails.InsertOnSubmit(entry); db.SubmitChanges(); } return; } var from = new MailAddress(MAIL_SOURCE_ADDRESS, " School", Encoding.UTF8); MailAddress replyto = null; if (!string.IsNullOrEmpty(entry.fromEmail)) { replyto = new MailAddress(entry.fromEmail, entry.fromName, Encoding.UTF8); } var to = new MailAddress(entry.toEmail, entry.toName, Encoding.UTF8); var msg = new MailMessage(from, to) { Body = entry.body, IsBodyHtml = true, BodyEncoding = Encoding.UTF8, Subject = entry.subject, SubjectEncoding = Encoding.UTF8 }; // add footer if (replyto != null) { msg.ReplyTo = replyto; msg.Body += "<p>You can directly reply to this email.</p>"; } else { msg.Body += "<p>This is an automated mail. Please DO NOT reply to this email.</p>"; } // cclist if (ccList != null) { foreach (var email in ccList) { msg.CC.Add(new MailAddress(email)); } } var smtp = new SmtpClient(MAIL_SERVER) { Credentials = new NetworkCredential(MAIL_SOURCE_ADDRESS, MAIL_PASSWORD) }; if (isAsync) { smtp.SendCompleted += SendCompletedCallback; smtp.SendAsync(msg, entry); } else { try { smtp.Send(msg); } catch (SmtpFailedRecipientException ex) { Syslog.Write(ex); } catch (Exception ex) { Syslog.Write(ex); // then we need to reinsert back // reinsert back into database using (var db = new ioschoolsDBDataContext()) { db.mails.InsertOnSubmit(entry); db.SubmitChanges(); } } } }
/// <summary> /// for HTML5 offline access /// </summary> /// <returns></returns> public ActionResult Index() { StringBuilder sb = new StringBuilder(); bool notfound = false; sb.AppendLine("CACHE MANIFEST"); sb.AppendLine("# " + GeneralConstants.TIMESTAMP); sb.AppendLine("FALLBACK:"); sb.AppendLine("/dashboard/product/edit /dashboard/product/edit"); sb.AppendLine("/dashboard/category/addsub /dashboard/category/addsub"); sb.AppendLine("NETWORK:"); sb.AppendLine("*"); sb.AppendLine("CACHE:"); foreach (var entry in URLS_TO_CACHE) { #if DEBUG // ignore invalid certificates ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; // verify that url is valid as it is a pita to debug applicationCache errors using (var client = new HeadClient()) { try { var head = client.DownloadString(accountHostname.ToDomainUrl(entry)); } catch (Exception ex) { Syslog.Write(ex); notfound = true; } } #endif sb.AppendLine(entry); } Debug.Assert(!notfound); // cannot cache all images as we're limited to 5mb offline cache /* * var images = db.images.Where(x => x.subdomain == subdomainid.Value); * var sizes = Enum.GetValues(typeof (Imgsize)); * foreach (var image in images) * { * foreach (Imgsize size in sizes) * { * try * { * var url = Img.by_size(image.url, size); * sb.AppendLine(url); * } * catch (Exception ex) * { * Syslog.Write(ex); * } * } * } */ Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1)); Response.Cache.SetValidUntilExpires(false); Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); Response.ContentType = "text/cache-manifest"; return(Content(sb.ToString())); }
/// <summary> /// Gets all Syslog objects /// <remarks> /// Returns ArrayList containing object passed in /// </remarks> /// <param name="o">Syslog to be returned</param> /// <retvalue>ArrayList containing Syslog object</retvalue> /// </summary> public ArrayList Get(Syslog o) { return(Get(o.SyslogID, o.InteractionID, o.DateCreated, o.DateCreated, o.DateModified, o.DateModified, o.Msgsource, o.Msgaction, o.Msgtxt)); }
public AdmissionStatus Process(Gender child_sex, int enrol_year, int school, int year, string child_name, string child_race, string child_dialect, string child_address, int child_dob_day, int child_dob_month, int child_dob_year, string child_pob, string child_citizenship, string child_birthcertno, string child_passportnric, bool child_bumi, string child_religion, HttpPostedFileBase child_photo, string child_previous_school, HttpPostedFileBase child_report, string child_previous_class, string child_leaving_reason, bool?child_handicap, bool?child_learning_problems, string child_disability_details, // parents fields string parent1_designation, string parent1_name, string parent1_passportnric, string parent1_occupation, string parent1_employer, string parent1_race, string parent1_dialect, bool?parent1_bumi, string parent1_marital, string parent1_citizenship, string parent1_religion, string parent1_officephone, string parent1_homephone, string parent1_handphone, string parent1_email, string parent1_address, string parent2_designation, string parent2_name, string parent2_passportnric, string parent2_occupation, string parent2_employer, string parent2_race, string parent2_dialect, bool?parent2_bumi, string parent2_marital, string parent2_citizenship, string parent2_religion, string parent2_officephone, string parent2_homephone, string parent2_handphone, string parent2_email, string parent2_address, // guardian fields string guardian_designation, string guardian_name, Gender?guardian_sex, string guardian_passportnric, string guardian_occupation, string guardian_employer, string guardian_race, string guardian_dialect, bool?guardian_bumi, string guardian_marital, string guardian_citizenship, string guardian_religion, string guardian_officephone, string guardian_homephone, string guardian_handphone, string guardian_email, string guardian_address, // other siblings string[] sibling_name, string[] sibling_nric, GuardianType?applicant_relationship, bool internalsubmission) { var noemail = true; // to ensure at least parent/guardian has email var emails = new List <string>(); // sanitize inputs parent1_email = (parent1_email ?? "").Trim().ToLower(); parent2_email = (parent2_email ?? "").Trim().ToLower(); guardian_email = (guardian_email ?? "").Trim().ToLower(); if (!string.IsNullOrEmpty(child_passportnric)) { child_passportnric = child_passportnric.Trim().Replace("-", ""); } if (!string.IsNullOrEmpty(parent1_passportnric)) { parent1_passportnric = parent1_passportnric.Trim().Replace("-", ""); } if (!string.IsNullOrEmpty(parent2_passportnric)) { parent2_passportnric = parent2_passportnric.Trim().Replace("-", ""); } if (!string.IsNullOrEmpty(guardian_passportnric)) { guardian_passportnric = guardian_passportnric.Trim().Replace("-", ""); } // check that student does not already exist if (!string.IsNullOrEmpty(child_passportnric)) { student = repository.GetUserByNewNRIC(child_passportnric); // only match student usergroup to prevent accidently matching with parents or teachers if (student != null && student.usergroup != (int)UserGroup.STUDENT) { Syslog.Write(ErrorLevel.WARNING, "NRIC incorrect match: " + child_passportnric); return(AdmissionStatus.INCORRECT_NRIC_PASSPORT); } } if (student == null && !string.IsNullOrEmpty(child_passportnric)) { student = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, child_passportnric, true) == 0); // only match student usergroup to prevent accidently matching with parents or teachers if (student != null && student.usergroup != (int)UserGroup.STUDENT) { Syslog.Write(ErrorLevel.WARNING, "NRIC incorrect match: " + child_passportnric); return(AdmissionStatus.INCORRECT_NRIC_PASSPORT); } } if (student == null) { // student student = new ioschools.DB.user(); student.usergroup = (int)UserGroup.STUDENT; student.settings = (int)UserSettings.INACTIVE; student.email = ""; student.name = child_name; student.gender = child_sex.ToString(); student.race = child_race; student.dialect = child_dialect; student.dob = new DateTime(child_dob_year, child_dob_month, child_dob_day); student.pob = child_pob; student.citizenship = child_citizenship; student.birthcertno = child_birthcertno; student.religion = child_religion; student.isbumi = child_bumi; student.address = child_address; var childidtype = GetIDType(child_passportnric); switch (childidtype) { case IdType.NEWIC: student.nric_new = child_passportnric; break; case IdType.PASSPORT: student.passportno = child_passportnric; break; default: throw new NotImplementedException(); } repository.AddUser(student); } // father password_father = tradelr.Crypto.Utility.GetRandomString(uppercase: true); if (!string.IsNullOrEmpty(parent1_name)) { // see if we can find this parent if (!string.IsNullOrEmpty(parent1_passportnric)) { father = repository.GetUserByNewNRIC(parent1_passportnric); } if (father == null && !string.IsNullOrEmpty(parent1_passportnric)) { father = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, parent1_passportnric, true) == 0); } if (father == null) { father = new ioschools.DB.user(); father.usergroup = (int)UserGroup.GUARDIAN; father.settings = (int)UserSettings.NONE; father.designation = parent1_designation; father.name = parent1_name; father.gender = Gender.MALE.ToString(); father.race = parent1_race; father.dialect = parent1_dialect; father.citizenship = parent1_citizenship; father.address = parent1_address; father.religion = parent1_religion; father.isbumi = parent1_bumi; var fatheridtype = GetIDType(parent1_passportnric); switch (fatheridtype) { case IdType.PASSPORT: father.passportno = parent1_passportnric; break; case IdType.NEWIC: father.nric_new = parent1_passportnric; father.dob = parent1_passportnric.ToDOB(); break; default: throw new NotImplementedException(); } if (!string.IsNullOrEmpty(parent1_email)) { // checks that email address is not in use if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent1_email, true) == 0) != null) { Syslog.Write(ErrorLevel.WARNING, "Enrolment using existing email " + parent1_email); return(AdmissionStatus.DUPLICATEEMAIL); } emails.Add(parent1_email); father.email = parent1_email; father.passwordhash = Utility.GeneratePasswordHash(parent1_email, password_father); noemail = false; } father.phone_home = parent1_homephone; father.phone_cell = parent1_handphone; father.user_parents = new user_parent(); father.marital_status = parent1_marital; father.user_parents.phone_office = parent1_officephone; father.user_parents.occupation = parent1_occupation; father.user_parents.employer = string.IsNullOrEmpty(parent1_employer)?"":parent1_employer.Trim(); repository.AddUser(father); } else { if (string.IsNullOrEmpty(father.email)) { // let's see if we can update email information if (!string.IsNullOrEmpty(parent1_email)) { // checks that email address is not in use if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent1_email, true) == 0) != null) { Syslog.Write(ErrorLevel.WARNING, "Enrolment using existing email " + parent1_email); return(AdmissionStatus.DUPLICATEEMAIL); } emails.Add(parent1_email); father.email = parent1_email; father.passwordhash = Utility.GeneratePasswordHash(parent1_email, password_father); noemail = false; } } else { noemail = false; } } } password_mother = tradelr.Crypto.Utility.GetRandomString(uppercase: true); if (!string.IsNullOrEmpty(parent2_name)) { // see if we can find this parent if (!string.IsNullOrEmpty(parent2_passportnric)) { mother = repository.GetUserByNewNRIC(parent2_passportnric); } if (mother == null && !string.IsNullOrEmpty(parent2_passportnric)) { mother = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, parent2_passportnric, true) == 0); } if (mother == null) { mother = new ioschools.DB.user(); mother.usergroup = (int)UserGroup.GUARDIAN; mother.settings = (int)UserSettings.NONE; mother.designation = parent2_designation; mother.name = parent2_name; mother.gender = Gender.FEMALE.ToString(); mother.race = parent2_race; mother.dialect = parent2_dialect; mother.citizenship = parent2_citizenship; mother.address = parent2_address; mother.religion = parent2_religion; mother.isbumi = parent2_bumi; var motheridtype = GetIDType(parent2_passportnric); switch (motheridtype) { case IdType.PASSPORT: mother.passportno = parent2_passportnric; break; case IdType.NEWIC: mother.nric_new = parent2_passportnric; mother.dob = parent2_passportnric.ToDOB(); break; default: throw new NotImplementedException(); } if (!string.IsNullOrEmpty(parent2_email)) { // checks that email address is not in use if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent2_email, true) == 0) != null) { Syslog.Write(ErrorLevel.WARNING, "Enrolment using existing email " + parent2_email); return(AdmissionStatus.DUPLICATEEMAIL); } if (!emails.Contains(parent2_email)) { emails.Add(parent2_email); mother.email = parent2_email; mother.passwordhash = Utility.GeneratePasswordHash(parent2_email, password_mother); noemail = false; } } mother.phone_home = parent2_homephone; mother.phone_cell = parent2_handphone; mother.user_parents = new user_parent(); mother.marital_status = parent2_marital; mother.user_parents.phone_office = parent2_officephone; mother.user_parents.occupation = parent2_occupation; mother.user_parents.employer = string.IsNullOrEmpty(parent2_employer) ? "" : parent2_employer.Trim(); repository.AddUser(mother); } else { if (string.IsNullOrEmpty(mother.email)) { // let's see if we can update email information if (!string.IsNullOrEmpty(parent2_email)) { // checks that email address is not in use if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent2_email, true) == 0) != null) { Syslog.Write(ErrorLevel.WARNING, "Enrolment using existing email " + parent2_email); return(AdmissionStatus.DUPLICATEEMAIL); } emails.Add(parent2_email); mother.email = parent2_email; mother.passwordhash = Utility.GeneratePasswordHash(parent2_email, password_mother); noemail = false; } } else { noemail = false; } } } password_guardian = tradelr.Crypto.Utility.GetRandomString(uppercase: true); if (!string.IsNullOrEmpty(guardian_name)) { // see if we can find this parent if (!string.IsNullOrEmpty(guardian_passportnric)) { guardian = repository.GetUserByNewNRIC(guardian_passportnric); } if (guardian == null && !string.IsNullOrEmpty(guardian_passportnric)) { guardian = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, guardian_passportnric) == 0); } if (guardian == null) { guardian = new ioschools.DB.user(); guardian.usergroup = (int)UserGroup.GUARDIAN; guardian.settings = (int)UserSettings.NONE; guardian.designation = guardian_designation; guardian.name = guardian_name; guardian.gender = guardian_sex.ToString(); guardian.race = guardian_race; guardian.dialect = guardian_dialect; guardian.citizenship = guardian_citizenship; guardian.address = guardian_address; guardian.religion = guardian_religion; guardian.isbumi = guardian_bumi; var guardianidtype = GetIDType(guardian_passportnric); switch (guardianidtype) { case IdType.NEWIC: guardian.nric_new = guardian_passportnric; guardian.dob = guardian_passportnric.ToDOB(); break; case IdType.PASSPORT: guardian.passportno = guardian_passportnric; break; default: throw new NotImplementedException(); } if (!string.IsNullOrEmpty(guardian_email)) { // checks that email address is not in use if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, guardian_email) == 0) != null) { Syslog.Write(ErrorLevel.WARNING, "Enrolment using existing email " + guardian_email); return(AdmissionStatus.DUPLICATEEMAIL); } if (!emails.Contains(guardian_email)) { guardian.email = guardian_email; guardian.passwordhash = Utility.GeneratePasswordHash(guardian_email, password_guardian); noemail = false; } } guardian.phone_home = guardian_homephone; guardian.phone_cell = guardian_handphone; guardian.user_parents = new user_parent(); guardian.marital_status = guardian_marital; guardian.user_parents.phone_office = guardian_officephone; guardian.user_parents.occupation = guardian_occupation; guardian.user_parents.employer = string.IsNullOrEmpty(guardian_employer) ? "" : guardian_employer.Trim(); repository.AddUser(guardian); } else { if (string.IsNullOrEmpty(guardian.email)) { // let's see if we can update email information if (!string.IsNullOrEmpty(guardian_email)) { // checks that email address is not in use if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, guardian_email, true) == 0) != null) { Syslog.Write(ErrorLevel.WARNING, "Enrolment using existing email " + guardian_email); return(AdmissionStatus.DUPLICATEEMAIL); } emails.Add(guardian_email); guardian.email = guardian_email; guardian.passwordhash = Utility.GeneratePasswordHash(guardian_email, password_guardian); noemail = false; } } else { noemail = false; } } } // check that there's an email if (noemail && !internalsubmission) { Syslog.Write(ErrorLevel.WARNING, string.Format("No email specified: 1:{0} 2:{1} 3:{2}", parent1_email, parent2_email, guardian_email)); return(AdmissionStatus.NOEMAIL); } // check that student is not already enrol for the same year // should we? possiblity that student may leave and come back in the same year /////////////////////// SAVE //////////////////// repository.Save(); // save photo if (child_photo != null) { var photouploader = new FileHandler(child_photo.FileName, UploaderType.PHOTO, null); photouploader.Save(child_photo.InputStream); var image = new user_image(); image.url = photouploader.url; student.user_image = image; } // save child report if (child_report != null) { var reportuploader = new FileHandler(child_report.FileName, UploaderType.REGISTRATION, student.id); reportuploader.Save(child_report.InputStream); var file = new user_file(); file.filename = child_report.FileName; file.url = reportuploader.url; student.user_files.Add(file); } // siblings for (int i = 0; i < sibling_name.Length; i++) { var name = sibling_name[i]; var nric = sibling_nric[i]; if (!string.IsNullOrEmpty(nric)) { nric = nric.Trim().Replace("-", ""); // try to find user var sibling = repository.GetUserByNewNRIC(nric); if ((sibling != null && sibling.usergroup != (int)UserGroup.STUDENT) || sibling == null) { // try pasport sibling = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, nric, true) == 0); } if (sibling != null) { var s = new sibling(); s.otherid = student.id; sibling.siblings1.Add(s); } } } // relationship // parent if (father != null) { var f = new students_guardian(); f.parentid = father.id; f.type = (byte)GuardianType.FATHER; if (!student.students_guardians.Any(x => x.parentid == f.parentid && x.type == f.type)) { student.students_guardians.Add(f); } } if (mother != null) { var m = new students_guardian(); m.parentid = mother.id; m.type = (byte)GuardianType.MOTHER; if (!student.students_guardians.Any(x => x.parentid == m.parentid && x.type == m.type)) { student.students_guardians.Add(m); } } if (guardian != null) { var g = new students_guardian(); g.parentid = guardian.id; g.type = (byte)GuardianType.GUARDIAN; if (!student.students_guardians.Any(x => x.parentid == g.parentid && x.type == g.type)) { student.students_guardians.Add(g); } } // registration var r = new registration(); r.enrollingYear = enrol_year; r.created = DateTime.Now; r.schoolid = school; r.schoolyearid = year; r.studentid = student.id; r.status = RegistrationStatus.PENDING.ToString(); r.schoolid = school; r.schoolyearid = year; r.previous_school = child_previous_school; r.leaving_reason = child_leaving_reason; r.disability_details = child_disability_details; r.hasLearningProblem = child_learning_problems; r.isHandicap = child_handicap; r.previous_class = child_previous_class; if (applicant_relationship.HasValue) { switch (applicant_relationship) { case GuardianType.FATHER: r.applicantid = father.id; break; case GuardianType.MOTHER: r.applicantid = mother.id; break; case GuardianType.GUARDIAN: r.applicantid = guardian.id; break; } } repository.AddRegistration(r); // success try { repository.Save(); } catch (Exception ex) { Syslog.Write(ex); return(AdmissionStatus.UNKNOWN); } return(AdmissionStatus.SUCCESS); }
public void DeleteProduct(long id, long subdomainid) { var p = db.products.SingleOrDefault(x => x.id == id && x.subdomainid == subdomainid); if (p == null) { Syslog.Write(string.Concat("can't find product to delete: ", id, ",", subdomainid)); return; } // break circular reference p.thumb = null; Save(); // remove gbase if (p.gbase_product != null) { db.gbase_products.DeleteOnSubmit(p.gbase_product); } // remove any wordpress posts if (p.wordpressPosts != null) { db.wordpressPosts.DeleteOnSubmit(p.wordpressPosts); } // remove any tumblr posts if (p.tumblrPosts != null) { db.tumblrPosts.DeleteOnSubmit(p.tumblrPosts); } // remove product collections db.productCollectionMembers.DeleteAllOnSubmit(p.productCollectionMembers); // remove group pricing var grouppricings = p.contactGroupPricings; db.contactGroupPricings.DeleteAllOnSubmit(grouppricings); // remove facebook imports var fbImports = p.facebook_imports; db.facebook_imports.DeleteAllOnSubmit(fbImports); // remove ebay entries if (p.ebayID.HasValue) { db.ebay_products.DeleteOnSubmit(p.ebay_product); } // remove product images if (p.product_images != null) { db.product_images.DeleteAllOnSubmit(p.product_images); } // update counters UpdateCounters(subdomainid, -1, CounterType.PRODUCTS_MINE); // delete tags if (p.tags1 != null) { db.tags.DeleteAllOnSubmit(p.tags1); } // update other friends counters var domainids = new List <long>(); var excludedomainids = new HashSet <long>(); var friendids = GetFriends(subdomainid).Select(x => x.id).ToList(); foreach (var friendid in friendids) { if (!excludedomainids.Contains(friendid)) { domainids.Add(friendid); } } // delete variants db.product_variants.DeleteAllOnSubmit(p.product_variants); db.products.DeleteOnSubmit(p); try { // because thumbnail is set to NULL Save(); } catch (Exception ex) { var resultString = "DeleteProduct:" + ex.Message; foreach (var conflict in db.ChangeConflicts) { var cstr = ""; foreach (var mc in conflict.MemberConflicts) { cstr += string.Concat("name:", mc.Member.Name, ","); } resultString += cstr; } Syslog.Write(resultString); } CacheHelper.Instance.invalidate_dependency(DependencyType.products_subdomain, subdomainid.ToString()); CacheHelper.Instance.invalidate_dependency(DependencyType.products_single, id.ToString()); }
public void ImportFacebookContacts() { var query = string.Format( "SELECT uid, first_name, last_name, current_location, pic_big, profile_url, proxied_email, sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = {0})", api.Application.Session.UserId); var rows = api.Fql.Query <users_getInfo_response>(query); foreach (var row in rows.user) { try { var usr = repository.GetUserByFBID(row.uid.Value.ToString(), subdomainid); if (usr != null) { continue; } var firstname = row.first_name; var lastname = row.last_name; if (string.IsNullOrEmpty(firstname) && string.IsNullOrEmpty(lastname)) { continue; } var org = new organisation { subdomain = subdomainid, name = string.Format("{0} {1}", firstname, lastname) }; var friend = new user() { role = UserRole.USER.ToInt(), email = "", proxiedEmail = row.proxied_email, firstName = firstname, lastName = lastname, gender = row.sex, organisation = repository.AddOrganisation(org), externalProfilePhoto = row.pic_big, externalProfileUrl = row.profile_url, FBID = row.uid.Value.ToString(), viewid = Crypto.Utility.GetRandomString(), permissions = (int)UserPermission.USER }; repository.UpdateCounters(subdomainid, 1, CounterType.CONTACTS_PRIVATE); repository.AddUser(friend); friend.externalProfilePhoto.ReadAndSaveFromUrl(subdomainid, friend.id, friend.id, PhotoType.PROFILE); } catch (Exception ex) { Syslog.Write(ex); } } // mail user var owner = repository.GetUserById(ownerid, subdomainid); var msg = new message.Message(owner, null, subdomainid); msg.SendMessage(null, repository, EmailViewType.GENERIC, "Your Facebook contacts have been successfully imported", "Import Contacts"); }
public static void SetStudentInactiveIfLeavingDateSet() { var date = DateTime.Now; var myLock = new object(); lock (myLock) { using (var db = new ioschoolsDBDataContext()) { bool hasChange = false; // check for expired students var groups = db.registrations.GroupBy(x => x.user); foreach (var g in groups) { var activeRow = g.Where(x => x.admissionDate.HasValue) .OrderBy(x => x.admissionDate).LastOrDefault(); if (activeRow != null) { var currentStatus = (UserSettings)activeRow.user.settings; if (activeRow.leftDate.HasValue) { if (date > activeRow.leftDate.Value && !currentStatus.HasFlag(UserSettings.INACTIVE)) { activeRow.user.settings = activeRow.user.SetFlag(UserSettings.INACTIVE); hasChange = true; } } else { if (date > activeRow.admissionDate.Value && currentStatus.HasFlag(UserSettings.INACTIVE)) { activeRow.user.settings = activeRow.user.UnsetFlag(UserSettings.INACTIVE); hasChange = true; } } } } // check for expired staff var staffgroups = db.employments.GroupBy(x => x.user); foreach (var g in staffgroups) { var activeRow = g.Where(x => x.start_date.HasValue) .OrderBy(x => x.start_date).LastOrDefault(); if (activeRow != null) { var currentStatus = (UserSettings)activeRow.user.settings; if (activeRow.end_date.HasValue) { if (date > activeRow.end_date.Value && !currentStatus.HasFlag(UserSettings.INACTIVE)) { activeRow.user.settings = activeRow.user.SetFlag(UserSettings.INACTIVE); hasChange = true; } } else { if (date > activeRow.start_date.Value && currentStatus.HasFlag(UserSettings.INACTIVE)) { activeRow.user.settings = activeRow.user.UnsetFlag(UserSettings.INACTIVE); hasChange = true; } } } } if (hasChange) { try { db.SubmitChanges(); } catch (Exception ex) { Syslog.Write(ex); } } } } }
public override void Load() { System.Net.WebClient wx = new System.Net.WebClient(); string key = Configuration.RetrieveConfig("yandex"); key = System.Web.HttpUtility.UrlEncode(key); if (key == null) { Syslog.ErrorLog("Unable to load translate module because there is no valid key"); this.IsWorking = false; return; } while (IsWorking) { if (Ring.data.Count > 0) { List <Buffer.Item> data = new List <Buffer.Item>(); lock (Ring.data) { data.AddRange(Ring.data); Ring.data.Clear(); } foreach (Buffer.Item request in data) { try { // get a translation for this item string result = wx.DownloadString(this.URL + "translate?key=" + key + "&lang=" + System.Web.HttpUtility.UrlEncode(request.SourceLang) + "-" + System.Web.HttpUtility.UrlEncode(request.TargetLang) + "&text=" + System.Web.HttpUtility.UrlEncode(request.Message)); XmlDocument xd = new XmlDocument(); xd.LoadXml(result); bool ok = false; foreach (XmlNode n1 in xd.ChildNodes) { if (n1.Name == "Translation" && n1.ChildNodes.Count > 0) { foreach (XmlNode n2 in n1.ChildNodes) { if (n2.Name == "text") { ok = true; if (request.TargetName == null) { IRC.DeliverMessage("Translating from " + request.SourceLang + " to " + request.TargetLang + ": " + n2.InnerText + " (powered by Yandex)", request.Channel); } else { IRC.DeliverMessage(request.TargetName + ": " + n2.InnerText + " (powered by Yandex)", request.Channel); } } } } } if (!ok) { DebugLog(result); IRC.DeliverMessage("Error - unable to translate the message (wrong language?) check debug logs for more information", request.Channel); } } catch (ThreadAbortException) { return; } catch (System.Exception fail) { HandleException(fail); } } } Thread.Sleep(100); } }
public override void Init() { try { if (usingRegistry) { if (!reg_flag) { if (!Read_Registry()) { L.Log(LogType.FILE, LogLevel.ERROR, "Error on Reading the Registry "); return; } else if (!Initialize_Logger()) { L.Log(LogType.FILE, LogLevel.ERROR, "Error on Intialize Logger on Syslog Recorder functions may not be running"); return; } reg_flag = true; } } else { if (!reg_flag) { if (!Get_logDir()) { L.Log(LogType.FILE, LogLevel.ERROR, "Error on Getting the log dir"); return; } else if (!Initialize_Logger()) { L.Log(LogType.FILE, LogLevel.ERROR, "Error on Intialize Logger on Syslog Recorder functions may not be running"); return; } reg_flag = true; } if (location.Length > 1) { if (location.Contains(':'.ToString())) { protocol = location.Split(':')[0]; Syslog_Port = Convert.ToInt32(location.Split(':')[1]); if (protocol.ToLower() == "tcp") pro = ProtocolType.Tcp; else pro = ProtocolType.Udp; } else { protocol = location; Syslog_Port = 514; } } else { pro = ProtocolType.Udp; Syslog_Port = 514; } } if (usingRegistry) { L.Log(LogType.FILE, LogLevel.INFORM, "Start listening Syslogs on ip: " + Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString() + " port: " + Syslog_Port.ToString()); slog = new Syslog(Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString(), Syslog_Port, pro); } else { L.Log(LogType.FILE, LogLevel.INFORM, "Start listening Syslogs on ip: " + remote_host + " port: " + Syslog_Port.ToString()); slog = new Syslog(remote_host, Syslog_Port, pro); } slog.Start(); slog.SyslogEvent += new Syslog.SyslogEventDelegate(slog_SyslogEvent); L.Log(LogType.FILE, LogLevel.INFORM, "Finish initializing Syslog Event"); } catch (Exception er) { EventLog.WriteEntry("Security Manager Syslog Recorder Init", er.ToString(), EventLogEntryType.Error); } }
public void ipn(string txn_id, string custom, string mc_gross, string payment_status, string receiver_email) { //Per PayPal Order Management / Integration Guide Pg.25 //we have to validate message by sending message back to paypal //Post back to either sandbox or live HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PaymentConstants.PaypalPostAddress); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://url:port#")); //req.Proxy = proxy; //Send the request to PayPal and get the response StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII); streamOut.Write(strRequest); streamOut.Close(); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string strResponse = streamIn.ReadToEnd(); streamIn.Close(); string response; Request.InputStream.Position = 0; using (var sr = new StreamReader(Request.InputStream)) { response = sr.ReadToEnd(); } var subdomainid = long.Parse(custom); try { if (strResponse == "VERIFIED") { using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); if (payment_status.ToLower() == "completed" && receiver_email == PaymentConstants.PaypalSubscribeEmail) { // payment verified sd.accountTypeStatus = (int)AccountPlanPaymentStatus.NONE; sd.accountTransactionID = txn_id; Syslog.Write(string.Concat("SUBSCRIBE:", subdomainid, ":oldplan:", sd.accountType, ":newplan:", sd.accountTypeNew)); if (sd.accountType != sd.accountTypeNew) { sd.accountType = sd.accountTypeNew; } else { Syslog.Write("Payment received for subdomain ID:" + subdomainid); } repository.Save(); } } Syslog.Write("VALID IPN:" + HttpUtility.HtmlEncode(response)); } else { if (strResponse == "INVALID") { Syslog.Write("INVALID IPN:" + HttpUtility.HtmlEncode(response)); } else { Syslog.Write("UNKNOWN IPN:" + HttpUtility.HtmlEncode(response)); } } } catch (Exception ex) { Syslog.Write(ex); Syslog.Write(string.Format("Exception {0}: {1}", subdomainid, HttpUtility.HtmlEncode(response))); } }
static void Main(string[] args) { var syslogInstance = new Syslog("172.16.91.172", 514, ProtocolType.Udp); Console.WriteLine("test"); }
/// <summary> /// Generate a dump file /// </summary> public void Make() { try { Dictionary <string, string> ModuleData = new Dictionary <string, string>(); foreach (Module xx in ExtensionHandler.ExtensionList) { try { if (xx.IsWorking) { string html = xx.Extension_DumpHtml(_Channel); if (!string.IsNullOrEmpty(html)) { ModuleData.Add(xx.Name.ToLower(), html); } } } catch (Exception fail) { Syslog.Log("Unable to retrieve web data", true); Core.HandleException(fail, "HtmlDump"); } } StringBuilder text = new StringBuilder(CreateHeader(_Channel.Name)); if (ModuleData.ContainsKey("infobot core")) { if (Module.GetConfig(_Channel, "Infobot.Enabled", true)) { text.Append("<h4>Infobot</h4>\n"); if (_Channel.SharedDB != "" && _Channel.SharedDB != "local") { Channel temp = Core.GetChannel(_Channel.SharedDB); if (temp != null) { text.Append("Linked to <a href=" + HttpUtility.UrlEncode(temp.Name) + ".htm>" + temp.Name + "</a>\n"); } else { text.AppendLine("Channel is linked to " + _Channel.SharedDB + " which isn't in my db, that's weird"); } } else { text.AppendLine(ModuleData["infobot core"]); } } ModuleData.Remove("infobot core"); } if (ModuleData.ContainsKey("rc")) { if (Module.GetConfig(_Channel, "RC.Enabled", false)) { text.AppendLine("\n<br /><h4>Recent changes</h4>"); text.AppendLine(ModuleData["rc"]); ModuleData.Remove("rc"); } } if (ModuleData.ContainsKey("statistics") && ModuleData["statistics"] != null) { if (Module.GetConfig(_Channel, "Statistics.Enabled", false)) { text.AppendLine(ModuleData["statistics"]); ModuleData.Remove("statistics"); } } if (ModuleData.ContainsKey("feed")) { if (Module.GetConfig(_Channel, "Rss.Enable", false)) { text.AppendLine(ModuleData["feed"]); ModuleData.Remove("feed"); } } foreach (KeyValuePair <string, string> item in ModuleData) { if (!string.IsNullOrEmpty(item.Value)) { text.AppendLine(item.Value); } } text.Append(CreateFooter()); File.WriteAllText(dumpname, text.ToString()); } catch (Exception b) { Core.HandleException(b, "HtmlDump"); } }
protected ActionResult ReturnError(string message) { Syslog.Write(new Exception(message)); return RedirectToAction("Index","error"); }
public void Count(string key, Syslog.HAProxySyslogDatagram datagram) { HAProxyCounter counter; if (!counters.TryGetValue(key, out counter)) { counters.TryAdd(key, new HAProxyCounter(key)); counters.TryGetValue(key, out counter); } counter.Increment(datagram); }
public override void Init() { try { RegistryProcess rp = new RegistryProcess(); InitializeLogger logger = new InitializeLogger(rp.TRC_LEVEL); EventLog.WriteEntry("Security Manager Syslog Recorder", "Recorder init start", EventLogEntryType.Information); if (usingRegistry) // agent için geldi { if (!reg_flag) { if (!rp.get_regisryforAgent()) { return; } else if (!logger.Initialize(rp)) { return; } reg_flag = true; } } else // remote recorder için geldi { if (!reg_flag) { if (!rp.get_registryforRemoteRecorder(Id, location, trc_level)) { return; } else if (!logger.Initialize(rp)) { return; } reg_flag = true; } } if (usingRegistry) { InitializeLogger.L.Log(LogType.FILE, LogLevel.INFORM, "Start listening Syslogs on ip: " + Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString() + " port: " + rp.SYSLOG_PORT.ToString()); try { slog = new Syslog(Dns.GetHostEntry(Environment.MachineName.Trim()).AddressList[0].ToString(), rp.SYSLOG_PORT, rp.PRO); } catch (Exception er) { InitializeLogger.L.Log(LogType.FILE, LogLevel.ERROR, "An error accuered while creating a syslog object for agent :" + er.Message); } } else { InitializeLogger.L.Log(LogType.FILE, LogLevel.INFORM, "Start listening Syslogs on ip: " + remote_host + " port: " + rp.SYSLOG_PORT.ToString()); try { slog = new Syslog(remote_host, rp.SYSLOG_PORT, rp.PRO); } catch (Exception er) { InitializeLogger.L.Log(LogType.FILE, LogLevel.ERROR, "An error accuered while creating a syslog object for remote recorder : " + er.Message); } } slog.Start(); slog.SyslogEvent += new Syslog.SyslogEventDelegate(slog_SyslogEvent); InitializeLogger.L.Log(LogType.FILE, LogLevel.INFORM, "Finish initializing Syslog Event"); EventLog.WriteEntry("Security Manager Syslog Recorder", "Recorder init start", EventLogEntryType.Information); } catch (Exception er) { EventLog.WriteEntry("Security Manager Syslog Recorder Init", er.ToString(), EventLogEntryType.Error); } }