private IExportTable GetTableExportTask(string path, bool remote) { var source = new SourceTableQuery() { Dataset = new Jhu.Graywulf.Schema.SqlServer.SqlServerDataset(Jhu.Graywulf.Test.Constants.TestDatasetName, Jhu.Graywulf.Test.AppSettings.IOTestConnectionString), Query = "SELECT * FROM SampleData" }; var destination = new DelimitedTextDataFile() { Uri = Util.UriConverter.FromFilePath(path) }; IExportTable te = null; if (remote) { te = RemoteServiceHelper.CreateObject <IExportTable>(Test.Constants.Localhost); } else { te = new ExportTable(); } te.Source = source; te.Destination = destination; return(te); }
internal static TransactionTransactNamedPipeResponse GetSubcommandResponse(SMBHeader header, TransactionTransactNamedPipeRequest subcommand, NamedPipeShare share, StateObject state) { string openedFilePath = state.GetOpenedFilePath(subcommand.FID); if (openedFilePath == null) { header.Status = NTStatus.STATUS_INVALID_HANDLE; return(null); } TransactionTransactNamedPipeResponse response = new TransactionTransactNamedPipeResponse(); RemoteService service = share.GetService(openedFilePath); if (service != null) { RPCPDU rpcRequest = RPCPDU.GetPDU(subcommand.WriteData); RPCPDU rpcReply = RemoteServiceHelper.GetRPCReply(rpcRequest, service); response.ReadData = rpcReply.GetBytes(); return(response); } // This code should not execute unless the request sequence is invalid header.Status = NTStatus.STATUS_INVALID_SMB; return(null); }
public object Status() { var errorsPrices = 0; if (Directory.Exists(Config.ErrorFilesPath)) { errorsPrices = Directory.GetFiles(Config.ErrorFilesPath).Length; } var priceProcessorStat = ""; RemoteServiceHelper.RemotingCall(s => { var itemList = s.GetPriceItemList(); var downloadedCount = itemList.Count(i => i.Downloaded); priceProcessorStat = $"Всего: {itemList.Length}, загруженные: {downloadedCount}, перепроводимые: {itemList.Length - downloadedCount}, ошибок: {errorsPrices}"; }); var orderProcStatus = BindingHelper.GetDescription(RemoteServiceHelper .GetServiceStatus(Config.OrderServiceHost, Config.OrderServiceName)); var priceProcessorStatus = BindingHelper.GetDescription(RemoteServiceHelper .GetServiceStatus(Config.PriceServiceHost, Config.PriceServiceName)); return(new { OrderProcStatus = orderProcStatus, IsOrderProcUnavailable = RemoteServiceHelper.IsUnavailable(orderProcStatus), PriceProcessorStatus = priceProcessorStatus, IsPriceProcessorUnavailable = RemoteServiceHelper.IsUnavailable(priceProcessorStatus), IsPriceProcessorStatUnavailable = String.IsNullOrEmpty(priceProcessorStat), PriceProcessorStat = String.IsNullOrEmpty(priceProcessorStat) ? "Недоступна" : priceProcessorStat }); }
public IExportTableArchive GetInitializedTableExportTask() { // Determine server name from connection string // This is required, because bulk copy can go into databases that are only known // by their connection string // Get server name from data source name (requires trimming the sql server instance name) string host = ((Jhu.Graywulf.Schema.SqlServer.SqlServerDataset)sources[0].Dataset).Host; var ss = new SourceTableQuery[sources.Length]; for (int i = 0; i < sources.Length; i++) { ss[i] = new SourceTableQuery() { Dataset = sources[i].Dataset, Query = String.Format("SELECT t.* FROM [{0}].[{1}] AS t", sources[i].SchemaName, sources[i].ObjectName) }; } // Create bulk operation var te = RemoteServiceHelper.CreateObject <IExportTableArchive>(host); te.Sources = ss; te.Destinations = destinations; te.Uri = uri; te.FileFormatFactoryType = fileFormatFactoryType; te.StreamFactoryType = streamFactoryType; te.Timeout = timeout; return(te); }
public void Index(DateTime?from, DateTime?to, bool full = false) { RemoteServiceHelper.Try(() => { PropertyBag["expirationDate"] = ADHelper.GetPasswordExpirationDate(Admin.UserName); }); if (from == null || to == null) { from = DateTime.Today; to = DateTime.Today; } GetStatistics(from.Value, to.Value, full); }
protected override void OnStart(string[] args) { // Initialize WCF service controlServiceHost = new ServiceHost( typeof(RemoteServiceControl), RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), "")); controlEndpoint = controlServiceHost.AddServiceEndpoint( typeof(IRemoteServiceControl), RemoteServiceHelper.CreateNetTcpBinding(), RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), "Control")); controlServiceHost.Open(); }
public void TopInInboundList(int hashCode) { var result = false; RemoteServiceHelper.RemotingCall(s => { result = s.TopInInboundList(hashCode); }); if (result) { Notify("Прайс лист перемещен вверх"); } else { Error("Ошибка при перемещении прайс листа"); } RedirectToReferrer(); }
public void DeleteItemInInboundList(int hashCode) { var result = false; RemoteServiceHelper.RemotingCall(s => { result = s.DeleteItemInInboundList(hashCode); }); if (result) { Notify("Прайс лист удален из очереди"); } else { Error("Ошибка при удалении прайс листа"); } RedirectToReferrer(); }
private ICopyFile GetFileCopy(string name, bool remote) { ICopyFile fc; if (remote) { fc = RemoteServiceHelper.CreateObject <ICopyFile>(Test.Constants.Localhost); } else { fc = new CopyFile(); } fc.Source = String.Format(@"\\{0}\{1}\{2}.txt", Test.Constants.RemoteHost1, Test.Constants.TestDirectory, name); fc.Destination = String.Format(@"\\{0}\{1}\{2}_2.txt", Test.Constants.RemoteHost1, Test.Constants.TestDirectory, name); return(fc); }
/// <summary> /// Creates and initializes a remote or local table copy task /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="local"></param> /// <returns></returns> protected ICopyTable CreateTableCopyTask(SourceTableQuery source, DestinationTable destination, bool local) { var desthost = GetHostnameFromSqlConnectionString(destination.Dataset.ConnectionString); ICopyTable qi; if (local) { qi = new CopyTable(); } else { qi = RemoteServiceHelper.CreateObject <ICopyTable>(desthost); } qi.Source = source; qi.Destination = destination; return(qi); }
private ICopyTable GetTableCopy(string tableName, bool remote) { ICopyTable q = null; if (remote) { q = RemoteServiceHelper.CreateObject <ICopyTable>(Test.Constants.Localhost); } else { q = new CopyTable(); } var ds = new Jhu.Graywulf.Schema.SqlServer.SqlServerDataset(Jhu.Graywulf.Test.Constants.TestDatasetName, Jhu.Graywulf.Test.AppSettings.IOTestConnectionString) { IsMutable = true }; var source = new SourceTableQuery() { Dataset = ds, Query = "SELECT 1 AS one, 2 AS two, 3 AS three" }; q.Source = new SourceTableQuery[] { source }; var destination = new Jhu.Graywulf.Schema.Table() { Dataset = ds, SchemaName = "dbo", TableName = tableName }; q.Destination = new Schema.Table[] { destination }; q.Options = TableInitializationOptions.Create; return(q); }
private DiagnosticMessage PingBulkOpService() { DiagnosticMessage msg = new DiagnosticMessage() { EntityName = GetFullyQualifiedName(), NetworkName = hostName.ResolvedValue, ServiceName = "RemoteService" }; try { var c = RemoteServiceHelper.GetControlObject(hostName.ResolvedValue); string res = c.Hello(); msg.Status = DiagnosticMessageStatus.OK; } catch (System.Exception ex) { msg.Status = DiagnosticMessageStatus.Error; msg.ErrorMessage = ex.Message; } return(msg); }
private void OnAsyncExecute(Guid workflowInstanceGuid, string activityInstanceId, string hostName, string sourceFilename, string destinationFilename) { // Check if destination file exists and has the same size as the source if (!File.Exists(destinationFilename) || new FileInfo(sourceFilename).Length != new FileInfo(destinationFilename).Length) { var fc = RemoteServiceHelper.CreateObject <ICopyFile>(hostName); fc.Source = sourceFilename; fc.Destination = destinationFilename; fc.Overwrite = true; RegisterCancelable(workflowInstanceGuid, activityInstanceId, fc); var start = DateTime.Now; Console.WriteLine("copying {0}", Path.GetFileName(sourceFilename)); fc.Execute(); Console.WriteLine("copied {0} in {1}", Path.GetFileName(sourceFilename), (start - DateTime.Now).TotalSeconds); UnregisterCancelable(workflowInstanceGuid, activityInstanceId, fc); } }
public void InboundPriceItemsList() { var items = new WcfPriceProcessItem[0]; #if !DEBUG RemoteServiceHelper.RemotingCall(s => { items = s.GetPriceItemList(); }); #else items = new[] { new WcfPriceProcessItem(1, false, "jjj.AAA", 2983, null, DateTime.Now.AddMinutes(50), 0), new WcfPriceProcessItem(2, true, "jjj.123", 384, null, DateTime.Now.AddMinutes(10), 0), new WcfPriceProcessItem(3, false, "jjj.BBB", 0, null, DateTime.Now.AddMinutes(100), 0) { FormalizedNow = true }, new WcfPriceProcessItem(4, true, "jjj.789", 1264, null, DateTime.Now.AddMinutes(500), 0) }; #endif var codes = items.Select(i => Convert.ToUInt32(i.PriceCode)).ToList(); var prices = DbSession.Query <Price>().Where(p => codes.Contains(p.Id)).ToList().ToDictionary(k => k.Id); var itemsCodes = items.Select(i => (uint)i.PriceItemId).ToList(); var priceItems = DbSession.Query <PriceItem>().Where(i => itemsCodes.Contains(i.Id)).ToList().ToDictionary(k => k.Id); #if DEBUG prices = new Dictionary <uint, Price>() { { 1u, new Price { Supplier = new Supplier { HomeRegion = new Region("test") } } }, { 4, new Price() { Supplier = new Supplier { HomeRegion = new Region("test2") } } } }; #endif var result = items.Select(i => { if (prices.Keys.Contains((uint)i.PriceCode)) { var price = prices[(uint)i.PriceCode]; DateTime?log = null; if (priceItems.Keys.Contains((uint)i.PriceItemId) && i.Downloaded) { var logs = priceItems[(uint)i.PriceItemId].DownloadLogs; if (logs.Count > 0) { log = logs.Max(d => d.LogTime); } } return(new InboundPriceItems(i.Downloaded, price, i.FilePath, log ?? (i.FileTime ?? i.CreateTime), i.HashCode, i.FormalizedNow)); } return(null); }).Where(p => p != null).ToList(); if (Directory.Exists(Config.ErrorFilesPath)) { var errorsItems = Directory.GetFiles(Config.ErrorFilesPath).Select(f => new { name = Path.GetFileNameWithoutExtension(f), time = File.GetCreationTime(f), file = f, priceItemId = ParseId(Path.GetFileNameWithoutExtension(f)) }); var itemIds = errorsItems.Select(e => e.priceItemId).ToList(); var errorPrices = DbSession.Query <Cost>().Where(p => itemIds.Contains(p.PriceItem.Id)).Select(p => p.Price).Distinct().ToList(); result.AddRange(errorsItems.Select(e => { var price = errorPrices.FirstOrDefault(p => p.Costs.Select(c => c.PriceItem.Id).Contains(e.priceItemId)); if (price != null) { return new InboundPriceItems(false, price, e.file, e.time, 0, false) { Error = true } } ; return(null); })); } result = result.Where(r => r != null).ToList(); var sortable = new Sortable(); BindObjectInstance(sortable, "filter"); var sortBy = sortable.SortBy; var direction = sortable.SortDirection == "asc" ? "ascending" : "descending"; if (string.IsNullOrEmpty(sortable.SortDirection)) { direction = "ascending"; } var retranse = result.Where(r => !r.Downloaded).Sort(ref sortBy, ref direction, "PriceTime").ToList(); var form = result.Where(r => r.Downloaded).Sort(ref sortBy, ref direction, "PriceTime").ToList(); form.AddRange(retranse); form = form.OrderBy(f => f.Error).ToList(); PropertyBag["items"] = form.ToList(); PropertyBag["filter"] = sortable; }
public static Uri RegisterService(Type contract) { // See if contractType is decorated with the RemoteServiceClassAttribute var attr = contract.GetCustomAttributes(typeof(RemoteServiceClassAttribute), false); if (attr == null || attr.Length != 1) { // TODO throw new InvalidOperationException("Contracts must be decorated with the RemoteServiceClassAttribute for automatic service registration."); } var serviceType = ((RemoteServiceClassAttribute)attr[0]).Type.AssemblyQualifiedName; // Attempt to load type var service = Type.GetType(serviceType); if (!service.IsSubclassOf(typeof(RemoteServiceBase))) { // TODO throw new InvalidOperationException("Service class must derive from Jhu.Graywulf.RemoteService.RemoteServiceBase"); } if (service == null || contract == null) { throw new Exception("Type not found."); // TODO } // Everything is OK, initialize service lock (syncRoot) { var host = new ServiceHost( service, RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), "")); // Turn on detailed debug info var sdb = host.Description.Behaviors.Find <ServiceDebugBehavior>(); if (sdb == null) { sdb = new ServiceDebugBehavior(); host.Description.Behaviors.Add(sdb); } sdb.IncludeExceptionDetailInFaults = true; // Turn on impersonation /* * var sab = host.Description.Behaviors.Find<ServiceAuthorizationBehavior>(); * if (sab == null) * { * sab = new ServiceAuthorizationBehavior(); * host.Description.Behaviors.Add(sab); * } * sab.ImpersonateCallerForAllOperations = true; */ // Unthrottle service to increase throughput // Service is behind a firewall, no DOS attacks will happen // TODO: copy these settings to the control endpoint var tb = host.Description.Behaviors.Find <ServiceThrottlingBehavior>(); if (tb == null) { tb = new ServiceThrottlingBehavior(); host.Description.Behaviors.Add(tb); } tb.MaxConcurrentCalls = 1024; tb.MaxConcurrentInstances = Int32.MaxValue; tb.MaxConcurrentSessions = 1024; var endpoint = host.AddServiceEndpoint( contract, RemoteServiceHelper.CreateNetTcpBinding(), RemoteServiceHelper.CreateEndpointUri(RemoteServiceHelper.GetFullyQualifiedDnsName(), service.FullName)); host.Open(); registeredServiceHosts.Add(contract.FullName, host); registeredEndpoints.Add(contract.FullName, endpoint); return(endpoint.Address.Uri); } }
public static uint PerformWrite(SMBHeader header, object share, ushort FID, ulong offset, byte[] data, StateObject state) { OpenedFileObject openedFile = state.GetOpenedFileObject(FID); if (openedFile == null) { header.Status = NTStatus.STATUS_INVALID_HANDLE; return(0); } string openedFilePath = openedFile.Path; if (share is NamedPipeShare) { RemoteService service = ((NamedPipeShare)share).GetService(openedFilePath); if (service != null) { RPCPDU rpcRequest = RPCPDU.GetPDU(data); RPCPDU rpcReply = RemoteServiceHelper.GetRPCReply(rpcRequest, service); byte[] replyData = rpcReply.GetBytes(); state.StoreNamedPipeReply(FID, replyData); return((uint)data.Length); } // This code should not execute unless the SMB request (sequence) is invalid header.Status = NTStatus.STATUS_INVALID_SMB; return(0); } else // FileSystemShare { FileSystemShare fileSystemShare = (FileSystemShare)share; IFileSystem fileSystem = fileSystemShare.FileSystem; if (openedFile.IsSequentialAccess && openedFile.Cache.Length > 0) { openedFile.Cache = new byte[0]; // Empty cache } try { Stream stream = fileSystem.OpenFile(openedFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); stream.Seek((long)offset, SeekOrigin.Begin); stream.Write(data, 0, data.Length); stream.Close(); return((uint)data.Length); } catch (IOException ex) { ushort errorCode = IOExceptionHelper.GetWin32ErrorCode(ex); if (errorCode == (ushort)Win32Error.ERROR_DISK_FULL) { header.Status = NTStatus.STATUS_DISK_FULL; return(0); } else if (errorCode == (ushort)Win32Error.ERROR_SHARING_VIOLATION) { // Returning STATUS_SHARING_VIOLATION is undocumented but apparently valid header.Status = NTStatus.STATUS_SHARING_VIOLATION; return(0); } else { header.Status = NTStatus.STATUS_DATA_ERROR; return(0); } } catch (ArgumentOutOfRangeException) { header.Status = NTStatus.STATUS_DATA_ERROR; return(0); } catch (UnauthorizedAccessException) { // The user may have tried to write to a readonly file header.Status = NTStatus.STATUS_ACCESS_DENIED; return(0); } } }
private void EnsureRoleAccess() { RemoteServiceHelper.EnsureRoleAccess(); }