From 320171b9dd51b52c0becf6c1057e1dc6668fa12b Mon Sep 17 00:00:00 2001 From: Nils Maier Date: Mon, 20 Oct 2014 04:30:35 +0200 Subject: [PATCH] Code cleanup --- .../ToolStripRealSystemRenderer.cs | 16 +- SimpleDLNA/FormAbout.cs | 3 +- SimpleDLNA/FormMain.cs | 223 ++++++++++-------- SimpleDLNA/FormServer.cs | 22 +- SimpleDLNA/FormSettings.cs | 1 - SimpleDLNA/GlobalSuppressions.cs | 1 + SimpleDLNA/PathEnvironmentInstaller.cs | 25 +- SimpleDLNA/Program.cs | 14 +- fsserver/BackgroundCacher.cs | 3 +- fsserver/FileServer.cs | 67 ++++-- fsserver/Files/AudioFile.cs | 17 +- fsserver/Files/BaseFile.cs | 27 +-- fsserver/Files/Cover.cs | 3 +- fsserver/Files/FileReadStream.cs | 8 +- fsserver/Files/FileStore.cs | 18 +- fsserver/Files/ImageFile.cs | 17 +- fsserver/Files/VideoFile.cs | 18 +- fsserver/PlainFolder.cs | 10 +- fsserver/PlainRootFolder.cs | 3 +- sdlna/Options.cs | 17 +- sdlna/Program.cs | 30 ++- sdlna/ProgramIcon.cs | 20 +- sdlna/SafeNativeMethods.cs | 7 +- server/Comparers/FileSizeComparer.cs | 3 +- server/GlobalSuppressions.cs | 19 ++ server/Handlers/IconHandler.cs | 3 +- server/Handlers/MediaMount.cs | 27 ++- server/Handlers/MediaMount_HTML.cs | 25 +- server/Handlers/MediaMount_SOAP.cs | 77 ++++-- server/Http/HTTPServer.cs | 6 +- server/Http/HttpAuthorizationEventArgs.cs | 3 +- server/Http/HttpAuthorizer.cs | 3 +- server/Http/HttpClient.cs | 17 +- server/Http/HttpPhrases.cs | 23 +- server/Interfaces/IMediaItem.cs | 3 +- server/Interfaces/Metadata/IMetaAudioItem.cs | 3 +- server/Interfaces/Metadata/IMetaImageItem.cs | 3 +- server/Interfaces/Metadata/IMetaVideoItem.cs | 3 +- server/Responses/ItemResponse.cs | 3 +- server/Responses/ResourceResponse.cs | 3 +- server/Ssdp/Datagram.cs | 5 +- server/Ssdp/SsdpHandler.cs | 13 +- server/Types/AudioResourceDecorator.cs | 3 +- server/Types/DlnaMediaTypes.cs | 3 +- server/Types/Headers.cs | 8 +- server/Types/HtmlTools.cs | 7 +- server/Types/SubTitle.cs | 12 +- server/Types/UpnpDevice.cs | 3 +- server/Types/VirtualClonedFolder.cs | 10 +- server/Views/DimensionView.cs | 6 +- server/Views/FlattenView.cs | 13 +- server/Views/MusicView.cs | 19 +- server/Views/SeriesView.cs | 3 +- thumbs/ImageThumbnailLoader.cs | 6 +- thumbs/ThumbnailMaker.cs | 28 ++- thumbs/VideoThumbnailLoader.cs | 27 ++- util/AddressToMacResolver.cs | 6 +- util/Ffmpeg.cs | 82 ++++--- util/HttpStream.cs | 8 +- util/IP.cs | 4 +- util/LeastRecentlyUsedDictionary.cs | 3 +- util/Logging.cs | 46 ++-- util/MoreDom.cs | 6 +- util/RepositoryLookupException.cs | 6 +- util/SafeNativeMethods.cs | 4 +- util/Sqlite.cs | 3 +- util/StreamPumpCallback.cs | 3 +- util/StringSortPart.cs | 3 +- 68 files changed, 735 insertions(+), 399 deletions(-) diff --git a/NMaier.Windows.Forms/ToolStripRealSystemRenderer.cs b/NMaier.Windows.Forms/ToolStripRealSystemRenderer.cs index 802c7e08..8741c198 100644 --- a/NMaier.Windows.Forms/ToolStripRealSystemRenderer.cs +++ b/NMaier.Windows.Forms/ToolStripRealSystemRenderer.cs @@ -21,6 +21,7 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***/ + using System; using System.Collections.Generic; using System.Drawing; @@ -245,7 +246,8 @@ private Color GetItemTextColor(ToolStripItem item) return renderer.GetColor(ColorProperty.TextColor); } - private Padding GetThemeMargins(IDeviceContext dc, MarginProperty marginType) + private Padding GetThemeMargins(IDeviceContext dc, + MarginProperty marginType) { NativeMethods.MARGINS margins; try { @@ -299,7 +301,8 @@ protected override void InitializePanel(ToolStripPanel toolStripPanel) base.InitializePanel(toolStripPanel); } - protected static bool IsElementDefined(string className, int part, int state) + protected static bool IsElementDefined(string className, int part, + int state) { var el = new VSEInternal(className, part, state); bool rv; @@ -335,9 +338,11 @@ protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) var rect = e.AffectedBounds; rect.Y += 2; rect.Height -= 4; - var sepWidth = renderer.GetPartSize(e.Graphics, ThemeSizeType.True).Width; + var sepWidth = + renderer.GetPartSize(e.Graphics, ThemeSizeType.True).Width; if (e.ToolStrip.RightToLeft == RightToLeft.Yes) { - rect = new Rectangle(rect.X - extraWidth, rect.Y, sepWidth, rect.Height); + rect = new Rectangle( + rect.X - extraWidth, rect.Y, sepWidth, rect.Height); rect.X += sepWidth; } else { @@ -432,7 +437,8 @@ protected override void OnRenderOverflowButtonBackground( rebarClass, VisualStyleElement.Rebar.Chevron.Normal.Part, state); - renderer.DrawBackground(e.Graphics, new Rectangle(Point.Empty, e.Item.Size)); + renderer.DrawBackground( + e.Graphics, new Rectangle(Point.Empty, e.Item.Size)); } else { base.OnRenderOverflowButtonBackground(e); diff --git a/SimpleDLNA/FormAbout.cs b/SimpleDLNA/FormAbout.cs index b0beb60c..c624d56d 100644 --- a/SimpleDLNA/FormAbout.cs +++ b/SimpleDLNA/FormAbout.cs @@ -14,7 +14,8 @@ public FormAbout() Text = String.Format("About {0}", ProductInformation.Title); Product.Text = ProductInformation.Title; Product.Font = BoldFont; - Version.Text = String.Format("Version {0}", ProductInformation.ProductVersion); + Version.Text = String.Format( + "Version {0}", ProductInformation.ProductVersion); Copyright.Text = ProductInformation.Copyright; Copyright.Font = ItalicFont; License.Text = Encoding.UTF8.GetString(Properties.Resources.LICENSE); diff --git a/SimpleDLNA/FormMain.cs b/SimpleDLNA/FormMain.cs index bae50520..87c05769 100644 --- a/SimpleDLNA/FormMain.cs +++ b/SimpleDLNA/FormMain.cs @@ -8,7 +8,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.Drawing; using System.IO; using System.IO.Pipes; using System.Linq; @@ -25,21 +24,27 @@ public partial class FormMain : NMaier.Windows.Forms.Form, IAppender, IDisposabl private bool canClose = false; - private static readonly Properties.Settings Config = Properties.Settings.Default; + private static readonly Properties.Settings Config = + Properties.Settings.Default; - private readonly FileInfo cacheFile = new FileInfo(Path.Combine(cacheDir, "sdlna.cache")); + private readonly FileInfo cacheFile = + new FileInfo(Path.Combine(cacheDir, "sdlna.cache")); #if DEBUG - private readonly FileInfo logFile = new FileInfo(Path.Combine(cacheDir, "sdlna.dbg.log")); + private readonly FileInfo logFile = + new FileInfo(Path.Combine(cacheDir, "sdlna.dbg.log")); #else - private readonly FileInfo logFile = new FileInfo(Path.Combine(cacheDir, "sdlna.log")); - + private readonly FileInfo logFile = + new FileInfo(Path.Combine(cacheDir, "sdlna.log")); #endif + private readonly object appenderLock = new object(); - private readonly System.Timers.Timer appenderTimer = new System.Timers.Timer(2000); + private readonly System.Timers.Timer appenderTimer = + new System.Timers.Timer(2000); - private readonly ConcurrentQueue pendingLogEntries = new ConcurrentQueue(); + private readonly ConcurrentQueue pendingLogEntries = + new ConcurrentQueue(); private static readonly ILog log = LogManager.GetLogger(typeof(FormMain)); @@ -92,7 +97,8 @@ public FormMain() SetupServer(); } - private delegate void logDelegate(string level, string logger, string msg, string ex); + private delegate void logDelegate(string level, string logger, string msg, + string ex); private static string cacheDir { @@ -104,13 +110,15 @@ private static string cacheDir } try { try { - rv = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + rv = Environment.GetFolderPath( + Environment.SpecialFolder.LocalApplicationData); if (string.IsNullOrEmpty(rv)) { throw new IOException("Cannot get LocalAppData"); } } catch (Exception) { - rv = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + rv = Environment.GetFolderPath( + Environment.SpecialFolder.ApplicationData); if (string.IsNullOrEmpty(rv)) { throw new IOException("Cannot get LocalAppData"); } @@ -174,7 +182,8 @@ private void ButtonNewServer_Click(object sender, EventArgs e) using (var ns = new FormServer()) { var rv = ns.ShowDialog(); if (rv == DialogResult.OK) { - var item = new ServerListViewItem(httpServer, cacheFile, ns.Description); + var item = new ServerListViewItem( + httpServer, cacheFile, ns.Description); listDescriptions.Items.Add(item); item.Load(); SaveConfig(); @@ -188,7 +197,12 @@ private void buttonRemove_Click(object sender, EventArgs e) if (item == null) { return; } - if (MessageBox.Show(string.Format("Would you like to remove {0}?", item.Description.Name), "Remove Server", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { + var dr = MessageBox.Show( + string.Format("Would you like to remove {0}?", item.Description.Name), + "Remove Server", + MessageBoxButtons.YesNo, + MessageBoxIcon.Question); + if (dr != DialogResult.Yes) { return; } if (item.Description.Active) { @@ -208,7 +222,9 @@ private void buttonRescan_Click(object sender, EventArgs e) item.Rescan(); } catch (Exception ex) { - MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show( + this, ex.Message, "Error", MessageBoxButtons.OK, + MessageBoxIcon.Error); } } @@ -257,7 +273,9 @@ where item.Description.Active } } catch (Exception ex) { - log.Error(string.Format("Failed to remove cache file {0}", cacheFile.FullName), ex); + log.Error( + string.Format("Failed to remove cache file {0}", cacheFile.FullName), + ex); } foreach (var item in running) { item.Toggle(); @@ -286,13 +304,6 @@ private void FormMain_FormClosing(object sender, FormClosingEventArgs e) } } - private void SetupServer() - { - httpServer = new HttpServer((int)Config.port); - LoadConfig(); - Text = string.Format("{0} - Port {1}", Text, httpServer.RealPort); - } - private void FormMain_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) { @@ -312,7 +323,18 @@ private void homepageToolStripMenuItem_Click(object sender, EventArgs e) Process.Start("http://nmaier.github.io/simpleDLNA/"); } - private void ListDescriptions_SelectedIndexChanged(object sender, EventArgs e) + private void listDescriptions_DoubleClick(object sender, EventArgs e) + { + if (buttonEdit.Enabled) { + ButtonEdit_Click(sender, e); + } + else { + ButtonNewServer_Click(sender, e); + } + } + + private void ListDescriptions_SelectedIndexChanged(object sender, + EventArgs e) { var enable = listDescriptions.SelectedItems.Count != 0; ctxStartStop.Enabled = ctxRemove.Enabled = ctxEdit.Enabled = @@ -360,7 +382,8 @@ private ServerListViewItem[] LoadDescriptors() List rv; try { var serializer = new XmlSerializer(typeof(List)); - using (var reader = new StreamReader(Path.Combine(cacheDir, descriptorFile))) { + using (var reader = new StreamReader( + Path.Combine(cacheDir, descriptorFile))) { rv = serializer.Deserialize(reader) as List; } } @@ -372,6 +395,49 @@ private ServerListViewItem[] LoadDescriptors() select i).ToArray(); } + private void notifyContext_Opening(object sender, + System.ComponentModel.CancelEventArgs e) + { + var items = new List(); + foreach (ToolStripItem i in notifyContext.Items) { + if (i.Tag != null) { + items.Add(i); + } + } + foreach (var i in items) { + notifyContext.Items.Remove(i); + } + items.Clear(); + if (listDescriptions.Items.Count == 0) { + ContextSeperatorPre.Visible = false; + return; + } + ContextSeperatorPre.Visible = true; + foreach (ServerListViewItem item in listDescriptions.Items) { + if (!item.Description.Active) { + continue; + } + var innerItem = item; + var sm = new ToolStripMenuItem(item.Text) { Tag = innerItem }; + var rescan = sm.DropDownItems.Add("Rescan"); + rescan.Click += (s, a) => + { + try { + innerItem.Rescan(); + } + catch (Exception) { + // no op + } + }; + items.Add(sm); + } + items.Reverse(); + var idx = notifyContext.Items.IndexOf(ContextSeperatorPre) + 1; + foreach (var i in items) { + notifyContext.Items.Insert(idx, i); + } + } + private void notifyIcon_DoubleClick(object sender, EventArgs e) { minimized = false; @@ -383,9 +449,23 @@ private void notifyIcon_DoubleClick(object sender, EventArgs e) } } - private void openInBrowserToolStripMenuItem_Click(object sender, EventArgs e) + private void openInBrowserToolStripMenuItem_Click(object sender, + EventArgs e) + { + Process.Start(string.Format( + "http://localhost:{0}/", httpServer.RealPort)); + } + + private void rescanAllContextMenuItem_Click(object sender, EventArgs e) { - Process.Start(string.Format("http://localhost:{0}/", httpServer.RealPort)); + foreach (ServerListViewItem l in listDescriptions.Items) { + try { + l.Rescan(); + } + catch (Exception) { + // no op + } + } } private void SaveConfig() @@ -394,7 +474,8 @@ private void SaveConfig() var descs = (from ServerListViewItem item in listDescriptions.Items select item.Description).ToArray(); var serializer = new XmlSerializer(descs.GetType()); - var file = new FileInfo(Path.Combine(cacheDir, descriptorFile + ".tmp")); + var file = new FileInfo( + Path.Combine(cacheDir, descriptorFile + ".tmp")); using (var writer = new StreamWriter(file.FullName)) { serializer.Serialize(writer, descs); } @@ -442,6 +523,13 @@ private void SetupLogging() BasicConfigurator.Configure(this, fileAppender); } + private void SetupServer() + { + httpServer = new HttpServer((int)Config.port); + LoadConfig(); + Text = string.Format("{0} - Port {1}", Text, httpServer.RealPort); + } + private void StartPipeNotification() { #if DEBUG @@ -455,7 +543,8 @@ private void StartPipeNotification() { for (; ; ) { try { - using (var pipe = new NamedPipeServerStream("simpledlnagui", PipeDirection.InOut)) { + using (var pipe = new NamedPipeServerStream( + "simpledlnagui", PipeDirection.InOut)) { pipe.WaitForConnection(); pipe.ReadByte(); BeginInvoke((Action)(() => @@ -518,7 +607,8 @@ public void DoAppend(LoggingEvent loggingEvent) } } - public void DoAppendInternal(object sender, System.Timers.ElapsedEventArgs e) + public void DoAppendInternal(object sender, + System.Timers.ElapsedEventArgs e) { lock (appenderLock) { appenderTimer.Enabled = false; @@ -534,10 +624,16 @@ public void DoAppendInternal(object sender, System.Timers.ElapsedEventArgs e) if (logger.Items.Count >= 300) { logger.Items.RemoveAt(0); } - last = logger.Items.Add(new ListViewItem(new string[] { entry.Time, entry.Class, entry.Message })); + last = logger.Items.Add( + new ListViewItem(new string[] { + entry.Time, entry.Class, entry.Message + })); last.ImageKey = entry.Key; if (!string.IsNullOrWhiteSpace(entry.Exception)) { - last = logger.Items.Add(new ListViewItem(new string[] { string.Empty, entry.Class, entry.Exception })); + last = logger.Items.Add( + new ListViewItem(new string[] { + string.Empty, entry.Class, entry.Exception + })); last.ImageKey = entry.Key; last.IndentCount = 1; } @@ -566,70 +662,5 @@ private struct LogEntry public string Time; } - - private void listDescriptions_DoubleClick(object sender, EventArgs e) - { - if (buttonEdit.Enabled) { - ButtonEdit_Click(sender, e); - } - else { - ButtonNewServer_Click(sender, e); - } - } - - private void rescanAllContextMenuItem_Click(object sender, EventArgs e) - { - foreach (ServerListViewItem l in listDescriptions.Items) { - try { - l.Rescan(); - } - catch (Exception) { - // no op - } - } - } - - private void notifyContext_Opening(object sender, System.ComponentModel.CancelEventArgs e) - { - var items = new List(); - foreach (ToolStripItem i in notifyContext.Items) { - if (i.Tag != null) { - items.Add(i); - } - } - foreach (var i in items) { - notifyContext.Items.Remove(i); - } - items.Clear(); - if (listDescriptions.Items.Count == 0) { - ContextSeperatorPre.Visible = false; - return; - } - ContextSeperatorPre.Visible = true; - foreach (ServerListViewItem item in listDescriptions.Items) { - if (!item.Description.Active) { - continue; - } - var innerItem = item; - var sm = new ToolStripMenuItem(item.Text); - sm.Tag = innerItem; - var rescan = sm.DropDownItems.Add("Rescan"); - rescan.Click += (s, a) => - { - try { - innerItem.Rescan(); - } - catch (Exception) { - // no op - } - }; - items.Add(sm); - } - items.Reverse(); - var idx = notifyContext.Items.IndexOf(ContextSeperatorPre) + 1; - foreach (var i in items) { - notifyContext.Items.Insert(idx, i); - } - } } } diff --git a/SimpleDLNA/FormServer.cs b/SimpleDLNA/FormServer.cs index c41c4d50..4b1132b7 100644 --- a/SimpleDLNA/FormServer.cs +++ b/SimpleDLNA/FormServer.cs @@ -28,9 +28,12 @@ public FormServer(ServerDescription description) textName.Text = description.Name; - checkVideo.Checked = (description.Types & DlnaMediaTypes.Video) == DlnaMediaTypes.Video; - checkAudio.Checked = (description.Types & DlnaMediaTypes.Audio) == DlnaMediaTypes.Audio; - checkImages.Checked = (description.Types & DlnaMediaTypes.Image) == DlnaMediaTypes.Image; + checkVideo.Checked = + (description.Types & DlnaMediaTypes.Video) == DlnaMediaTypes.Video; + checkAudio.Checked = + (description.Types & DlnaMediaTypes.Audio) == DlnaMediaTypes.Audio; + checkImages.Checked = + (description.Types & DlnaMediaTypes.Image) == DlnaMediaTypes.Image; foreach (var i in comboOrder.Items) { if (((IItemComparer)i).Name == description.Order) { @@ -41,7 +44,9 @@ public FormServer(ServerDescription description) checkOrderDescending.Checked = description.OrderDescending; foreach (var v in description.Views) { - var i = new ListViewItem(new string[] { v, ViewRepository.Lookup(v).Description }); + var i = new ListViewItem(new string[] { + v, ViewRepository.Lookup(v).Description + }); listViews.Items.Add(i); } foreach (var d in description.Directories) { @@ -169,7 +174,8 @@ private void buttonAddRestriction_Click(object sender, EventArgs e) break; } if (!valid) { - errorProvider.SetError(textRestriction, "You must provide a valid value"); + errorProvider.SetError( + textRestriction, "You must provide a valid value"); return; } var item = listRestrictions.Items.Add(re); @@ -184,7 +190,8 @@ private void buttonAddView_Click(object sender, EventArgs e) if (i == null) { return; } - listViews.Items.Add(new ListViewItem(new string[] { i.Name, i.Description })); + listViews.Items.Add( + new ListViewItem(new string[] { i.Name, i.Description })); SizeColumns(listViews); } @@ -244,7 +251,8 @@ private void Init() private void listDirectories_Validating(object sender, CancelEventArgs e) { if (listDirectories.Items.Count == 0) { - errorProvider.SetError(listDirectoriesAnchor, "Must specify at least one directory"); + errorProvider.SetError( + listDirectoriesAnchor, "Must specify at least one directory"); e.Cancel = true; } else { diff --git a/SimpleDLNA/FormSettings.cs b/SimpleDLNA/FormSettings.cs index d75fc1f4..00e51fd5 100644 --- a/SimpleDLNA/FormSettings.cs +++ b/SimpleDLNA/FormSettings.cs @@ -1,5 +1,4 @@ using System; -using System.Drawing; using System.Windows.Forms; namespace NMaier.SimpleDlna.GUI diff --git a/SimpleDLNA/GlobalSuppressions.cs b/SimpleDLNA/GlobalSuppressions.cs index 20302321..667cee0d 100644 --- a/SimpleDLNA/GlobalSuppressions.cs +++ b/SimpleDLNA/GlobalSuppressions.cs @@ -22,3 +22,4 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Scope = "member", Target = "NMaier.SimpleDlna.GUI.ServerListViewItem.#StartFileServer()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Scope = "type", Target = "NMaier.SimpleDlna.GUI.FormMain")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Scope = "member", Target = "NMaier.SimpleDlna.GUI.FormMain.#LoadDescriptors()")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Scope = "member", Target = "NMaier.SimpleDlna.GUI.FormMain.#notifyContext_Opening(System.Object,System.ComponentModel.CancelEventArgs)")] diff --git a/SimpleDLNA/PathEnvironmentInstaller.cs b/SimpleDLNA/PathEnvironmentInstaller.cs index 09b7d72f..f6974845 100644 --- a/SimpleDLNA/PathEnvironmentInstaller.cs +++ b/SimpleDLNA/PathEnvironmentInstaller.cs @@ -18,7 +18,8 @@ public class PathEnvironmentInstaller : Installer private const string REG_PATH = "PATH"; - private readonly DirectoryInfo directory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory; + private readonly DirectoryInfo directory = + new FileInfo(Assembly.GetExecutingAssembly().Location).Directory; public override void Install(IDictionary stateSaver) { @@ -28,12 +29,15 @@ public override void Install(IDictionary stateSaver) } using (var registry = Registry.CurrentUser.OpenSubKey(REG_ENV, true)) { - var path = registry.GetValue(REG_PATH, string.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames) as string; + var path = registry.GetValue( + REG_PATH, string.Empty, + RegistryValueOptions.DoNotExpandEnvironmentNames) as string; if (path == null) { return; } + var c = StringComparer.CurrentCultureIgnoreCase; var exists = from p in path.Split(';') - where StringComparer.CurrentCultureIgnoreCase.Equals(p, directory.FullName) + where c.Equals(p, directory.FullName) select p; if (exists.Count() > 0) { return; @@ -54,7 +58,8 @@ public override void Rollback(IDictionary savedState) return; } using (var registry = Registry.CurrentUser.OpenSubKey(REG_ENV, true)) { - registry.SetValue(REG_PATH, savedState[ENV_PATH], registry.GetValueKind(REG_PATH)); + registry.SetValue( + REG_PATH, savedState[ENV_PATH], registry.GetValueKind(REG_PATH)); } } @@ -66,13 +71,17 @@ public override void Uninstall(IDictionary savedState) } using (var registry = Registry.CurrentUser.OpenSubKey(REG_ENV, true)) { - var path = registry.GetValue(REG_PATH, string.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames) as string; + var path = registry.GetValue( + REG_PATH, string.Empty, + RegistryValueOptions.DoNotExpandEnvironmentNames) as string; if (string.IsNullOrEmpty(path)) { return; } - var cleaned = string.Join(";", from p in path.Split(';') - where !StringComparer.CurrentCultureIgnoreCase.Equals(p, directory.FullName) - select p); + var c = StringComparer.CurrentCultureIgnoreCase; + var paths = from p in path.Split(';') + where !c.Equals(p, directory.FullName) + select p; + var cleaned = string.Join(";", paths); if (StringComparer.CurrentCultureIgnoreCase.Equals(path, cleaned)) { return; } diff --git a/SimpleDLNA/Program.cs b/SimpleDLNA/Program.cs index d1eb3332..0376fd23 100644 --- a/SimpleDLNA/Program.cs +++ b/SimpleDLNA/Program.cs @@ -1,9 +1,7 @@ -using NMaier.Windows.Forms; -using System; +using System; using System.IO.Pipes; using System.Threading; using System.Windows.Forms; -using System.Windows.Forms.VisualStyles; namespace NMaier.SimpleDlna.GUI { @@ -15,7 +13,8 @@ private static void Main() using (var mutex = new Mutex(false, @"Global\simpledlnaguilock")) { #if !DEBUG if (!mutex.WaitOne(0, false)) { - using (var pipe = new NamedPipeClientStream(".", "simpledlnagui", PipeDirection.Out)) { + using (var pipe = new NamedPipeClientStream( + ".", "simpledlnagui", PipeDirection.Out)) { try { pipe.Connect(10000); pipe.WriteByte(1); @@ -33,9 +32,12 @@ private static void Main() Application.Run(main); } catch (Exception ex) { - log4net.LogManager.GetLogger(typeof(Program)).Fatal("Encountered fatal unhandled exception", ex); + log4net.LogManager.GetLogger(typeof(Program)).Fatal( + "Encountered fatal unhandled exception", ex); MessageBox.Show( - string.Format("Encountered an unhandled error. Will exit now.\n\n{0}\n{1}", ex.Message, ex.StackTrace), + string.Format( + "Encountered an unhandled error. Will exit now.\n\n{0}\n{1}", + ex.Message, ex.StackTrace), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error diff --git a/fsserver/BackgroundCacher.cs b/fsserver/BackgroundCacher.cs index 94169400..c58312a0 100644 --- a/fsserver/BackgroundCacher.cs +++ b/fsserver/BackgroundCacher.cs @@ -55,7 +55,8 @@ private static void Run() } } - public static void AddFiles(FileStore store, IEnumerable items) + public static void AddFiles(FileStore store, + IEnumerable items) { var storeRef = new WeakReference(store); foreach (var i in items) { diff --git a/fsserver/FileServer.cs b/fsserver/FileServer.cs index c396232d..4fb85f8a 100644 --- a/fsserver/FileServer.cs +++ b/fsserver/FileServer.cs @@ -11,29 +11,38 @@ namespace NMaier.SimpleDlna.FileMediaServer { - public sealed class FileServer : Logging, IMediaServer, IVolatileMediaServer, IDisposable + public sealed class FileServer + : Logging, IMediaServer, IVolatileMediaServer, IDisposable { private readonly DirectoryInfo[] directories; - private readonly static StringComparer icomparer = StringComparer.CurrentCultureIgnoreCase; + private readonly static StringComparer icomparer = + StringComparer.CurrentCultureIgnoreCase; - private readonly Timer changeTimer = new Timer(TimeSpan.FromSeconds(20).TotalMilliseconds); + private readonly Timer changeTimer = + new Timer(TimeSpan.FromSeconds(20).TotalMilliseconds); private readonly Guid uuid = Guid.NewGuid(); - private readonly Timer watchTimer = new Timer(TimeSpan.FromMinutes(10).TotalMilliseconds); + private readonly Timer watchTimer = + new Timer(TimeSpan.FromMinutes(10).TotalMilliseconds); - private readonly Regex re_sansitizeExt = new Regex(@"[^\w\d]+", RegexOptions.Compiled); + private readonly Regex re_sansitizeExt = + new Regex(@"[^\w\d]+", RegexOptions.Compiled); private DateTime lastChanged = DateTime.Now; - private static readonly double ChangeDefaultTime = TimeSpan.FromSeconds(30).TotalMilliseconds; + private static readonly double ChangeDefaultTime = + TimeSpan.FromSeconds(30).TotalMilliseconds; - private static readonly double ChangeRenamedTime = TimeSpan.FromSeconds(10).TotalMilliseconds; + private static readonly double ChangeRenamedTime = + TimeSpan.FromSeconds(10).TotalMilliseconds; - private static readonly double ChangeDeleteTime = TimeSpan.FromSeconds(2).TotalMilliseconds; + private static readonly double ChangeDeleteTime = + TimeSpan.FromSeconds(2).TotalMilliseconds; - private readonly List pendingFiles = new List(); + private readonly List pendingFiles = + new List(); private readonly Identifiers ids; @@ -43,7 +52,8 @@ public sealed class FileServer : Logging, IMediaServer, IVolatileMediaServer, ID private readonly FileSystemWatcher[] watchers; - public FileServer(DlnaMediaTypes types, Identifiers ids, params DirectoryInfo[] directories) + public FileServer(DlnaMediaTypes types, Identifiers ids, + params DirectoryInfo[] directories) { this.types = types; this.ids = ids; @@ -172,16 +182,24 @@ private void DoRoot() private void OnChanged(Object source, FileSystemEventArgs e) { try { - if (store != null && icomparer.Equals(e.FullPath, store.StoreFile.FullName)) { + if (store != null && + icomparer.Equals(e.FullPath, store.StoreFile.FullName)) { return; } - var ext = string.IsNullOrEmpty(e.FullPath) ? Path.GetExtension(e.FullPath) : string.Empty; + var ext = string.IsNullOrEmpty(e.FullPath) ? + Path.GetExtension(e.FullPath) : + string.Empty; if (!string.IsNullOrEmpty(ext) && - !types.GetExtensions().Contains(ext.Substring(1), StringComparer.OrdinalIgnoreCase)) { - DebugFormat("Skipping name {0} {1} {2}", e.Name, Path.GetExtension(e.FullPath), string.Join(", ", types.GetExtensions())); + !types.GetExtensions().Contains( + ext.Substring(1), StringComparer.OrdinalIgnoreCase)) { + DebugFormat( + "Skipping name {0} {1} {2}", + e.Name, Path.GetExtension(e.FullPath), + string.Join(", ", types.GetExtensions())); return; } - DebugFormat("File System changed ({1}): {0}", e.FullPath, e.ChangeType); + DebugFormat( + "File System changed ({1}): {0}", e.FullPath, e.ChangeType); DelayedRescan(e.ChangeType); } catch (Exception ex) { @@ -193,14 +211,20 @@ private void OnRenamed(Object source, RenamedEventArgs e) { try { var exts = types.GetExtensions(); - var ext = string.IsNullOrEmpty(e.FullPath) ? Path.GetExtension(e.FullPath) : string.Empty; + var ext = string.IsNullOrEmpty(e.FullPath) ? + Path.GetExtension(e.FullPath) : + string.Empty; + var c = StringComparer.OrdinalIgnoreCase; if (!string.IsNullOrEmpty(ext) && - !exts.Contains(ext.Substring(1), StringComparer.OrdinalIgnoreCase) && - !exts.Contains(ext.Substring(1), StringComparer.OrdinalIgnoreCase)) { - DebugFormat("Skipping name {0} {1} {2}", e.Name, Path.GetExtension(e.FullPath), string.Join(", ", exts)); + !exts.Contains(ext.Substring(1), c) && + !exts.Contains(ext.Substring(1), c)) { + DebugFormat( + "Skipping name {0} {1} {2}", + e.Name, Path.GetExtension(e.FullPath), string.Join(", ", exts)); return; } - DebugFormat("File System changed ({1}): {0}", e.FullPath, e.ChangeType); + DebugFormat( + "File System changed ({1}): {0}", e.FullPath, e.ChangeType); DelayedRescan(e.ChangeType); } catch (Exception ex) { @@ -247,7 +271,8 @@ private void Thumbnail() return; } lock (this) { - DebugFormat("Passing {0} files to background cacher", pendingFiles.Count); + DebugFormat( + "Passing {0} files to background cacher", pendingFiles.Count); BackgroundCacher.AddFiles(store, pendingFiles); pendingFiles.Clear(); } diff --git a/fsserver/Files/AudioFile.cs b/fsserver/Files/AudioFile.cs index a2e99136..fb3a0bf9 100644 --- a/fsserver/Files/AudioFile.cs +++ b/fsserver/Files/AudioFile.cs @@ -6,7 +6,8 @@ namespace NMaier.SimpleDlna.FileMediaServer { [Serializable] - internal sealed class AudioFile : BaseFile, IMediaAudioResource, ISerializable + internal sealed class AudioFile + : BaseFile, IMediaAudioResource, ISerializable { private string album; @@ -248,15 +249,19 @@ private void MaybeInit() Server.UpdateFileCache(this); } catch (TagLib.CorruptFileException ex) { - Debug("Failed to read metadata via taglib for file " + Item.FullName, ex); + Debug( + "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (TagLib.UnsupportedFormatException ex) { - Debug("Failed to read metadata via taglib for file " + Item.FullName, ex); + Debug( + "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (Exception ex) { - Warn("Unhandled exception reading metadata for file " + Item.FullName, ex); + Warn( + "Unhandled exception reading meta data for file " + Item.FullName, + ex); } } @@ -334,9 +339,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext ctx) info.AddValue("ti", title); info.AddValue("tr", track); info.AddValue( - "d", - duration.GetValueOrDefault(EmptyDuration).Ticks - ); + "d", duration.GetValueOrDefault(EmptyDuration).Ticks); } public override void LoadCover() diff --git a/fsserver/Files/BaseFile.cs b/fsserver/Files/BaseFile.cs index 9878ea0a..df4907f1 100644 --- a/fsserver/Files/BaseFile.cs +++ b/fsserver/Files/BaseFile.cs @@ -27,19 +27,20 @@ internal class BaseFile : Logging, IMediaResource, IMediaCover, IMetaInfo private static readonly StringComparer comparer = new NaturalStringComparer(false); - protected BaseFile(FileServer server, FileInfo aFile, DlnaMime aType, DlnaMediaTypes aMediaType) + protected BaseFile(FileServer server, FileInfo file, DlnaMime type, + DlnaMediaTypes mediaType) { if (server == null) { throw new ArgumentNullException("server"); } this.server = server; - Item = aFile; + Item = file; length = Item.Length; lastModified = Item.LastWriteTimeUtc; - Type = aType; - MediaType = aMediaType; + Type = type; + MediaType = mediaType; title = System.IO.Path.GetFileNameWithoutExtension(Item.Name); if (string.IsNullOrEmpty(title)) { @@ -193,22 +194,18 @@ protected bool LoadCoverFromCache() return cover != null; } - internal static BaseFile GetFile(PlainFolder aParentFolder, FileInfo aFile, DlnaMime aType, DlnaMediaTypes aMediaType) + internal static BaseFile GetFile(PlainFolder parentFolder, FileInfo file, + DlnaMime type, DlnaMediaTypes mediaType) { - switch (aMediaType) { + switch (mediaType) { case DlnaMediaTypes.Video: - return new VideoFile(aParentFolder.Server, aFile, aType); + return new VideoFile(parentFolder.Server, file, type); case DlnaMediaTypes.Audio: - return new AudioFile(aParentFolder.Server, aFile, aType); + return new AudioFile(parentFolder.Server, file, type); case DlnaMediaTypes.Image: - return new ImageFile(aParentFolder.Server, aFile, aType); + return new ImageFile(parentFolder.Server, file, type); default: - return new BaseFile( - aParentFolder.Server, - aFile, - aType, - aMediaType - ); + return new BaseFile(parentFolder.Server, file, type, mediaType); } } diff --git a/fsserver/Files/Cover.cs b/fsserver/Files/Cover.cs index 4ceccf15..a41ba15a 100644 --- a/fsserver/Files/Cover.cs +++ b/fsserver/Files/Cover.cs @@ -9,7 +9,8 @@ namespace NMaier.SimpleDlna.FileMediaServer { [Serializable] - internal sealed class Cover : Logging, IMediaCoverResource, IMetaInfo, ISerializable + internal sealed class Cover + : Logging, IMediaCoverResource, IMetaInfo, ISerializable { private byte[] bytes; diff --git a/fsserver/Files/FileReadStream.cs b/fsserver/Files/FileReadStream.cs index 010a81d9..ee8b1de0 100644 --- a/fsserver/Files/FileReadStream.cs +++ b/fsserver/Files/FileReadStream.cs @@ -9,10 +9,14 @@ internal sealed class FileReadStream : FileStream private readonly FileInfo info; - private readonly static ILog logger = LogManager.GetLogger(typeof(FileReadStream)); + private readonly static ILog logger = + LogManager.GetLogger(typeof(FileReadStream)); public FileReadStream(FileInfo info) - : base(info.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BUFFER_SIZE, FileOptions.Asynchronous | FileOptions.SequentialScan) + : base(info.FullName, FileMode.Open, + FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, + BUFFER_SIZE, + FileOptions.Asynchronous | FileOptions.SequentialScan) { this.info = info; logger.DebugFormat("Opened file {0}", this.info.FullName); diff --git a/fsserver/Files/FileStore.cs b/fsserver/Files/FileStore.cs index 372149e1..e9127ea9 100644 --- a/fsserver/Files/FileStore.cs +++ b/fsserver/Files/FileStore.cs @@ -61,7 +61,8 @@ internal FileStore(FileInfo storeFile) SetupDatabase(); select = connection.CreateCommand(); - select.CommandText = "SELECT data FROM store WHERE key = ? AND size = ? AND time = ?"; + select.CommandText = + "SELECT data FROM store WHERE key = ? AND size = ? AND time = ?"; select.Parameters.Add(selectKey = select.CreateParameter()); selectKey.DbType = DbType.String; select.Parameters.Add(selectSize = select.CreateParameter()); @@ -70,7 +71,8 @@ internal FileStore(FileInfo storeFile) selectTime.DbType = DbType.Int64; selectCover = connection.CreateCommand(); - selectCover.CommandText = "SELECT cover FROM store WHERE key = ? AND size = ? AND time = ?"; + selectCover.CommandText = + "SELECT cover FROM store WHERE key = ? AND size = ? AND time = ?"; selectCover.Parameters.Add(selectCoverKey = select.CreateParameter()); selectCoverKey.DbType = DbType.String; selectCover.Parameters.Add(selectCoverSize = select.CreateParameter()); @@ -103,7 +105,8 @@ internal FileStore(FileInfo storeFile) vacuumer.Add(connection); } - private void OpenConnection(FileInfo storeFile, out IDbConnection newConnection) + private void OpenConnection(FileInfo storeFile, + out IDbConnection newConnection) { lock (globalLock) { newConnection = Sqlite.GetDatabaseConnection(storeFile); @@ -144,11 +147,13 @@ private void SetupDatabase() { using (var transaction = connection.BeginTransaction()) { using (var pragma = connection.CreateCommand()) { - pragma.CommandText = string.Format("PRAGMA user_version = {0}", SCHEMA); + pragma.CommandText = string.Format( + "PRAGMA user_version = {0}", SCHEMA); pragma.ExecuteNonQuery(); } using (var create = connection.CreateCommand()) { - create.CommandText = "CREATE TABLE IF NOT EXISTS store (key TEXT PRIMARY KEY ON CONFLICT REPLACE, size INT, time INT, data BINARY, cover BINARY)"; + create.CommandText = + "CREATE TABLE IF NOT EXISTS store (key TEXT PRIMARY KEY ON CONFLICT REPLACE, size INT, time INT, data BINARY, cover BINARY)"; create.ExecuteNonQuery(); } transaction.Commit(); @@ -224,7 +229,8 @@ internal Cover MaybeGetCover(BaseFile file) } } - internal BaseFile MaybeGetFile(FileServer server, FileInfo info, DlnaMime type) + internal BaseFile MaybeGetFile(FileServer server, FileInfo info, + DlnaMime type) { if (connection == null) { return null; diff --git a/fsserver/Files/ImageFile.cs b/fsserver/Files/ImageFile.cs index 507958b5..f4f9ca1b 100644 --- a/fsserver/Files/ImageFile.cs +++ b/fsserver/Files/ImageFile.cs @@ -6,7 +6,8 @@ namespace NMaier.SimpleDlna.FileMediaServer { [Serializable] - internal sealed class ImageFile : BaseFile, IMediaImageResource, ISerializable + internal sealed class ImageFile : + BaseFile, IMediaImageResource, ISerializable { private string creator; @@ -21,7 +22,9 @@ internal sealed class ImageFile : BaseFile, IMediaImageResource, ISerializable height; private ImageFile(SerializationInfo info, StreamingContext context) - : this((context.Context as DeserializeInfo).Server, (context.Context as DeserializeInfo).Info, (context.Context as DeserializeInfo).Type) + : this((context.Context as DeserializeInfo).Server, + (context.Context as DeserializeInfo).Info, + (context.Context as DeserializeInfo).Type) { } @@ -153,15 +156,19 @@ private void MaybeInit() Server.UpdateFileCache(this); } catch (TagLib.CorruptFileException ex) { - Debug("Failed to read metadata via taglib for file " + Item.FullName, ex); + Debug( + "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (TagLib.UnsupportedFormatException ex) { - Debug("Failed to read metadata via taglib for file " + Item.FullName, ex); + Debug( + "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (Exception ex) { - Warn("Unhandled exception reading metadata for file " + Item.FullName, ex); + Warn( + "Unhandled exception reading meta data for file " + Item.FullName, + ex); } } diff --git a/fsserver/Files/VideoFile.cs b/fsserver/Files/VideoFile.cs index ab15aa0d..0ce826e5 100644 --- a/fsserver/Files/VideoFile.cs +++ b/fsserver/Files/VideoFile.cs @@ -7,7 +7,8 @@ namespace NMaier.SimpleDlna.FileMediaServer { [Serializable] - internal sealed class VideoFile : BaseFile, IMediaVideoResource, ISerializable, IBookmarkable + internal sealed class VideoFile + : BaseFile, IMediaVideoResource, ISerializable, IBookmarkable { private string[] actors; @@ -265,15 +266,19 @@ private void MaybeInit() Server.UpdateFileCache(this); } catch (TagLib.CorruptFileException ex) { - Debug("Failed to read metadata via taglib for file " + Item.FullName, ex); + Debug( + "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (TagLib.UnsupportedFormatException ex) { - Debug("Failed to read metadata via taglib for file " + Item.FullName, ex); + Debug( + "Failed to read meta data via taglib for file " + Item.FullName, ex); initialized = true; } catch (Exception ex) { - Warn("Unhandled exception reading metadata for file " + Item.FullName, ex); + Warn( + "Unhandled exception reading meta data for file " + Item.FullName, + ex); } } @@ -291,10 +296,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("w", width); info.AddValue("h", height); info.AddValue("b", bookmark); - info.AddValue( - "du", - duration.GetValueOrDefault(EmptyDuration).Ticks - ); + info.AddValue("du", duration.GetValueOrDefault(EmptyDuration).Ticks); info.AddValue("st", subTitle); } } diff --git a/fsserver/PlainFolder.cs b/fsserver/PlainFolder.cs index 12f75b87..c99ff974 100644 --- a/fsserver/PlainFolder.cs +++ b/fsserver/PlainFolder.cs @@ -11,7 +11,9 @@ internal class PlainFolder : VirtualFolder, IMetaInfo { private readonly DirectoryInfo dir; - private PlainFolder(FileServer server, DlnaMediaTypes types, VirtualFolder parent, DirectoryInfo dir, IEnumerable exts) + private PlainFolder(FileServer server, DlnaMediaTypes types, + VirtualFolder parent, DirectoryInfo dir, + IEnumerable exts) : base(parent, dir.Name) { Server = server; @@ -40,7 +42,8 @@ private PlainFolder(FileServer server, DlnaMediaTypes types, VirtualFolder paren resources.AddRange(files); } - protected PlainFolder(FileServer server, DlnaMediaTypes types, VirtualFolder parent, DirectoryInfo dir) + protected PlainFolder(FileServer server, DlnaMediaTypes types, + VirtualFolder parent, DirectoryInfo dir) : this(server, types, parent, dir, types.GetExtensions()) { } @@ -83,7 +86,8 @@ public override string Title } } - private PlainFolder TryGetFolder(FileServer server, DlnaMediaTypes types, DirectoryInfo d) + private PlainFolder TryGetFolder(FileServer server, DlnaMediaTypes types, + DirectoryInfo d) { try { return new PlainFolder(server, types, this, d); diff --git a/fsserver/PlainRootFolder.cs b/fsserver/PlainRootFolder.cs index 517bea12..6f2cb085 100644 --- a/fsserver/PlainRootFolder.cs +++ b/fsserver/PlainRootFolder.cs @@ -5,7 +5,8 @@ namespace NMaier.SimpleDlna.FileMediaServer { internal sealed class PlainRootFolder : PlainFolder { - internal PlainRootFolder(FileServer server, DlnaMediaTypes types, DirectoryInfo di) + internal PlainRootFolder(FileServer server, DlnaMediaTypes types, + DirectoryInfo di) : base(server, types, null, di) { Id = Identifiers.GeneralRoot; diff --git a/sdlna/Options.cs b/sdlna/Options.cs index 6edaff49..b1ac2ee9 100644 --- a/sdlna/Options.cs +++ b/sdlna/Options.cs @@ -22,12 +22,14 @@ internal class Options : GetOpt private string[] uas = new string[0]; [Parameters(HelpVar = "Directory")] - public DirectoryInfo[] Directories = new DirectoryInfo[] { new DirectoryInfo(".") }; + public DirectoryInfo[] Directories = + new DirectoryInfo[] { new DirectoryInfo(".") }; [Argument("type", HelpText = "Types to serv (IMAGE, VIDEO, AUDIO; default: all)")] [ArgumentAlias("what")] [ShortArgument('t')] - public DlnaMediaTypes[] Types = new DlnaMediaTypes[] { DlnaMediaTypes.Video, DlnaMediaTypes.Image, DlnaMediaTypes.Audio }; + public DlnaMediaTypes[] Types = + new DlnaMediaTypes[] { DlnaMediaTypes.Video, DlnaMediaTypes.Image, DlnaMediaTypes.Audio }; [Argument("view", HelpText = "Apply a view (default: no views applied)", HelpVar = "view")] [ShortArgument('v')] @@ -98,7 +100,8 @@ public string[] Ips IPAddress.Parse(ip); } catch (Exception) { - throw new GetOptException(string.Format("Not a valid IP address: {0}", ip)); + throw new GetOptException(string.Format( + "Not a valid IP address: {0}", ip)); } } ips = value; @@ -117,14 +120,15 @@ public string[] Macs { foreach (var mac in value) { if (!IP.IsAcceptedMAC(mac)) { - throw new GetOptException(string.Format("Not a valid mac address: {0}. Must have a form of 01:AF:BC:00:0A:FF!", mac)); + throw new GetOptException(string.Format( + "Not a valid mac address: {0}. Must have a form of 01:AF:BC:00:0A:FF!", mac)); } } macs = value; } } - [Argument("port", HelpVar = "port", HelpText = "Webserver listen port (default: 0, bind an available port)")] + [Argument("port", HelpVar = "port", HelpText = "Web server listen port (default: 0, bind an available port)")] [ShortArgument('p')] public int Port { @@ -135,7 +139,8 @@ public int Port set { if (value != 0 && (value < 1 || value > ushort.MaxValue)) { - throw new GetOptException("Port must be between 2 and " + ushort.MaxValue); + throw new GetOptException( + "Port must be between 2 and " + ushort.MaxValue); } port = value; } diff --git a/sdlna/Program.cs b/sdlna/Program.cs index f992db9b..59feb970 100644 --- a/sdlna/Program.cs +++ b/sdlna/Program.cs @@ -15,14 +15,17 @@ namespace NMaier.SimpleDlna { public static class Program { - private readonly static ManualResetEvent BlockEvent = new ManualResetEvent(false); + private readonly static ManualResetEvent BlockEvent = + new ManualResetEvent(false); private static uint CancelHitCount = 0; - private static void CancelKeyPressed(object sender, ConsoleCancelEventArgs e) + private static void CancelKeyPressed(object sender, + ConsoleCancelEventArgs e) { if (CancelHitCount++ == 3) { - LogManager.GetLogger(typeof(Program)).Fatal("Emergency exit commencing"); + LogManager.GetLogger(typeof(Program)).Fatal( + "Emergency exit commencing"); return; } e.Cancel = true; @@ -105,7 +108,8 @@ private static void Main(string[] args) authorizer.AddMethod(new MacAuthorizer(options.Macs)); } if (options.UserAgents.Length != 0) { - authorizer.AddMethod(new UserAgentAuthorizer(options.UserAgents)); + authorizer.AddMethod( + new UserAgentAuthorizer(options.UserAgents)); } Console.Title = "SimpleDLNA - starting ..."; @@ -121,18 +125,23 @@ private static void Main(string[] args) if (options.Seperate) { foreach (var d in options.Directories) { server.InfoFormat("Mounting FileServer for {0}", d.FullName); - var fs = SetupFileServer(options, types, new DirectoryInfo[] { d }); + var fs = SetupFileServer( + options, types, new DirectoryInfo[] { d }); friendlyName = fs.FriendlyName; server.RegisterMediaServer(fs); server.NoticeFormat("{0} mounted", d.FullName); } } else { - server.InfoFormat("Mounting FileServer for {0} ({1})", options.Directories[0], options.Directories.Length); + server.InfoFormat( + "Mounting FileServer for {0} ({1})", + options.Directories[0], options.Directories.Length); var fs = SetupFileServer(options, types, options.Directories); friendlyName = fs.FriendlyName; server.RegisterMediaServer(fs); - server.NoticeFormat("{0} ({1}) mounted", options.Directories[0], options.Directories.Length); + server.NoticeFormat( + "{0} ({1}) mounted", + options.Directories[0], options.Directories.Length); } Console.Title = String.Format("{0} - running ...", friendlyName); @@ -165,9 +174,12 @@ private static void Run(HttpServer server) server.Info("Closed!"); } - private static FileServer SetupFileServer(Options options, DlnaMediaTypes types, DirectoryInfo[] d) + private static FileServer SetupFileServer(Options options, + DlnaMediaTypes types, + DirectoryInfo[] d) { - var ids = new Identifiers(ComparerRepository.Lookup(options.Order), options.DescendingOrder); + var ids = new Identifiers( + ComparerRepository.Lookup(options.Order), options.DescendingOrder); foreach (var v in options.Views) { try { ids.AddView(v); diff --git a/sdlna/ProgramIcon.cs b/sdlna/ProgramIcon.cs index f11758ff..57aa37da 100644 --- a/sdlna/ProgramIcon.cs +++ b/sdlna/ProgramIcon.cs @@ -24,18 +24,22 @@ public ProgramIcon() if (window == IntPtr.Zero) { throw new Exception("Cannot get console window"); } - var inst = Marshal.GetHINSTANCE(Assembly.GetEntryAssembly().GetModules()[0]); + var inst = Marshal.GetHINSTANCE( + Assembly.GetEntryAssembly().GetModules()[0]); iconLg = SafeNativeMethods.LoadImage(inst, "#32512", 1, 0, 0, 0x40); if (iconLg == IntPtr.Zero) { throw new Exception("Failed to load large icon"); } var desired = SafeNativeMethods.GetSystemMetrics(49); - iconSm = SafeNativeMethods.LoadImage(inst, "#32512", 1, desired, desired, 0); + iconSm = SafeNativeMethods.LoadImage( + inst, "#32512", 1, desired, desired, 0); if (iconLg == IntPtr.Zero) { throw new Exception("Failed to load small icon"); } - oldLg = SafeNativeMethods.SendMessage(window, SafeNativeMethods.WM_SETICON, new IntPtr(1), iconLg); - oldSm = SafeNativeMethods.SendMessage(window, SafeNativeMethods.WM_SETICON, IntPtr.Zero, iconSm); + oldLg = SafeNativeMethods.SendMessage( + window, SafeNativeMethods.WM_SETICON, new IntPtr(1), iconLg); + oldSm = SafeNativeMethods.SendMessage( + window, SafeNativeMethods.WM_SETICON, IntPtr.Zero, iconSm); } catch (Exception ex) { Debug("Couldnd't set icon", ex); @@ -55,15 +59,17 @@ public void Dispose() return; } if (oldLg != IntPtr.Zero) { - SafeNativeMethods.SendMessage(window, SafeNativeMethods.WM_SETICON, new IntPtr(1), oldLg); + SafeNativeMethods.SendMessage( + window, SafeNativeMethods.WM_SETICON, new IntPtr(1), oldLg); } if (oldSm != IntPtr.Zero) { - SafeNativeMethods.SendMessage(window, SafeNativeMethods.WM_SETICON, IntPtr.Zero, oldSm); + SafeNativeMethods.SendMessage( + window, SafeNativeMethods.WM_SETICON, IntPtr.Zero, oldSm); } window = IntPtr.Zero; } catch (Exception ex) { - Debug("Couldnd't restore icon", ex); + Debug("Couldn't restore icon", ex); } } } diff --git a/sdlna/SafeNativeMethods.cs b/sdlna/SafeNativeMethods.cs index 04dbdf06..dc9cbfad 100644 --- a/sdlna/SafeNativeMethods.cs +++ b/sdlna/SafeNativeMethods.cs @@ -14,9 +14,12 @@ internal static class SafeNativeMethods public static extern int GetSystemMetrics(int index); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - public static extern IntPtr LoadImage(IntPtr inst, string name, uint type, int cxDesired, int cyDesired, uint fuLoad); + public static extern IntPtr LoadImage(IntPtr inst, string name, + uint type, int cxDesired, + int cyDesired, uint fuLoad); [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam); + public static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, + IntPtr wParam, IntPtr lParam); } } diff --git a/server/Comparers/FileSizeComparer.cs b/server/Comparers/FileSizeComparer.cs index 03449b77..6b9e0b53 100644 --- a/server/Comparers/FileSizeComparer.cs +++ b/server/Comparers/FileSizeComparer.cs @@ -24,7 +24,8 @@ public override int Compare(IMediaItem x, IMediaItem y) { var xm = x as IMetaInfo; var ym = y as IMetaInfo; - if (xm != null && ym != null && xm.InfoSize.HasValue && ym.InfoSize.HasValue) { + if (xm != null && ym != null && + xm.InfoSize.HasValue && ym.InfoSize.HasValue) { var rv = xm.InfoSize.Value.CompareTo(ym.InfoSize.Value); if (rv != 0) { return rv; diff --git a/server/GlobalSuppressions.cs b/server/GlobalSuppressions.cs index 2c1c613b..d0171662 100644 --- a/server/GlobalSuppressions.cs +++ b/server/GlobalSuppressions.cs @@ -73,3 +73,22 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMaps.#Mime")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "NMaier.SimpleDlna.Server.Redirect.#.ctor(NMaier.SimpleDlna.Server.HttpCode,System.Uri)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "NMaier.SimpleDlna.Server.Views.DimensionView")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMaps.#AllPN")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMaps.#AllPN")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMaps.#MainPN")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "AAC", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#AudioAAC")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "FLAC", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#AudioFLAC")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "RAW", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#AudioRAW")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "VORBIS", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#AudioVORBIS")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "GIF", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#ImageGIF")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "JPEG", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#ImageJPEG")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "PNG", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#ImagePNG")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SRT", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#SubtitleSRT")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "GPP", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#Video3GPP")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "AVC", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoAVC")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "AVI", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoAVI")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "FLV", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoFLV")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "MATROSKA", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoMATROSKA")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "MPEG", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoMPEG")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OGV", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoOGV")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "WMV", Scope = "member", Target = "NMaier.SimpleDlna.Server.DlnaMime.#VideoWMV")] diff --git a/server/Handlers/IconHandler.cs b/server/Handlers/IconHandler.cs index 0921f7a2..ad216865 100644 --- a/server/Handlers/IconHandler.cs +++ b/server/Handlers/IconHandler.cs @@ -13,7 +13,8 @@ public string Prefix public IResponse HandleRequest(IRequest req) { var resource = req.Path.Substring(Prefix.Length); - var isPng = resource.EndsWith(".png", System.StringComparison.OrdinalIgnoreCase); + var isPng = resource.EndsWith( + ".png", System.StringComparison.OrdinalIgnoreCase); return new ResourceResponse( HttpCode.Ok, isPng ? "image/png" : "image/jpeg", diff --git a/server/Handlers/MediaMount.cs b/server/Handlers/MediaMount.cs index 4782c28a..e33bee53 100644 --- a/server/Handlers/MediaMount.cs +++ b/server/Handlers/MediaMount.cs @@ -8,7 +8,8 @@ namespace NMaier.SimpleDlna.Server { - internal sealed partial class MediaMount : Logging, IMediaServer, IPrefixHandler + internal sealed partial class MediaMount + : Logging, IMediaServer, IPrefixHandler { private readonly Dictionary guidsForAddresses = new Dictionary(); @@ -91,25 +92,33 @@ private string GenerateDescriptor(IPAddress source) doc.SelectSingleNode("//*[local-name() = 'friendlyName']").InnerText = FriendlyName + " — sdlna"; - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:ContentDirectory:1']/../*[local-name() = 'SCPDURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:ContentDirectory:1']/../*[local-name() = 'SCPDURL']").InnerText = String.Format("{0}contentDirectory.xml", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:ContentDirectory:1']/../*[local-name() = 'controlURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:ContentDirectory:1']/../*[local-name() = 'controlURL']").InnerText = String.Format("{0}control", prefix); doc.SelectSingleNode("//*[local-name() = 'eventSubURL']").InnerText = String.Format("{0}events", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:ConnectionManager:1']/../*[local-name() = 'SCPDURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:ConnectionManager:1']/../*[local-name() = 'SCPDURL']").InnerText = String.Format("{0}connectionManager.xml", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:ConnectionManager:1']/../*[local-name() = 'controlURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:ConnectionManager:1']/../*[local-name() = 'controlURL']").InnerText = String.Format("{0}control", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:ConnectionManager:1']/../*[local-name() = 'eventSubURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:ConnectionManager:1']/../*[local-name() = 'eventSubURL']").InnerText = String.Format("{0}events", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:X_MS_MediaReceiverRegistrar:1']/../*[local-name() = 'SCPDURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:X_MS_MediaReceiverRegistrar:1']/../*[local-name() = 'SCPDURL']").InnerText = String.Format("{0}MSMediaReceiverRegistrar.xml", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:X_MS_MediaReceiverRegistrar:1']/../*[local-name() = 'controlURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:X_MS_MediaReceiverRegistrar:1']/../*[local-name() = 'controlURL']").InnerText = String.Format("{0}control", prefix); - doc.SelectSingleNode("//*[text() = 'urn:schemas-upnp-org:service:X_MS_MediaReceiverRegistrar:1']/../*[local-name() = 'eventSubURL']").InnerText = + doc.SelectSingleNode( + "//*[text() = 'urn:schemas-upnp-org:service:X_MS_MediaReceiverRegistrar:1']/../*[local-name() = 'eventSubURL']").InnerText = String.Format("{0}events", prefix); return doc.OuterXml; diff --git a/server/Handlers/MediaMount_HTML.cs b/server/Handlers/MediaMount_HTML.cs index fb3b84d5..3bdcfef8 100644 --- a/server/Handlers/MediaMount_HTML.cs +++ b/server/Handlers/MediaMount_HTML.cs @@ -58,27 +58,36 @@ private IResponse ProcessHtmlRequest(IMediaItem aItem) article.AppendChild(folders); var items = (XmlNode)null; - article.AppendChild(items = document.EL("ul", new AttributeCollection() { { "class", "items" } })); + article.AppendChild(items = document.EL( + "ul", new AttributeCollection() { { "class", "items" } })); foreach (var i in item.ChildItems) { items.AppendChild(e = document.EL("li")); var link = document.EL( "a", new AttributeCollection() { - { "href", string.Format("{0}file/{1}/{2}.{3}", prefix, i.Id, i.Title, DlnaMaps.Dlna2Ext[i.Type][0]) } + { "href", string.Format( + "{0}file/{1}/{2}.{3}", prefix, i.Id, i.Title, + DlnaMaps.Dlna2Ext[i.Type][0]) } } ); var details = document.EL("section"); link.AppendChild(details); e.AppendChild(link); - details.AppendChild(document.EL("h3", new AttributeCollection { { "title", i.Title } }, i.Title)); + details.AppendChild(document.EL( + "h3", new AttributeCollection { { "title", i.Title } }, i.Title)); var props = i.Properties; if (props.ContainsKey("HasCover")) { details.AppendChild(document.EL( - "img", - new AttributeCollection { { "title", "Cover image" }, { "alt", "Cover image" }, { "src", String.Format("{0}cover/{1}/{2}.{3}", prefix, i.Id, i.Title, DlnaMaps.Dlna2Ext[i.Type][0]) } } - )); + "img", + new AttributeCollection { + { "title", "Cover image" }, + { "alt", "Cover image" }, + { "src", String.Format( + "{0}cover/{1}/{2}.{3}", prefix, i.Id, i.Title, + DlnaMaps.Dlna2Ext[i.Type][0]) } + })); } var table = document.EL("table"); @@ -96,7 +105,9 @@ private IResponse ProcessHtmlRequest(IMediaItem aItem) string description; if (props.TryGetValue("Description", out description)) { - link.AppendChild(document.EL("p", new AttributeCollection() { { "class", "desc" } }, description)); + link.AppendChild(document.EL( + "p", new AttributeCollection() { { "class", "desc" } }, + description)); } } diff --git a/server/Handlers/MediaMount_SOAP.cs b/server/Handlers/MediaMount_SOAP.cs index b0648be6..0a641890 100644 --- a/server/Handlers/MediaMount_SOAP.cs +++ b/server/Handlers/MediaMount_SOAP.cs @@ -11,23 +11,30 @@ internal partial class MediaMount { private const string NS_DC = "http://purl.org/dc/elements/1.1/"; - private const string NS_DIDL = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"; + private const string NS_DIDL = + "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"; - private const string NS_DLNA = "urn:schemas-dlna-org:metadata-1-0/"; + private const string NS_DLNA = + "urn:schemas-dlna-org:metadata-1-0/"; private const string NS_SEC = "http://www.sec.co.kr/"; - private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; + private const string NS_SOAPENV = + "http://schemas.xmlsoap.org/soap/envelope/"; private const string NS_UPNP = "urn:schemas-upnp-org:metadata-1-0/upnp/"; - private static readonly string featureList = Encoding.UTF8.GetString(Properties.Resources.ResourceManager.GetObject("x_featurelist") as byte[]); + private static readonly string featureList = + Encoding.UTF8.GetString(Properties.Resources.ResourceManager.GetObject("x_featurelist") as byte[]); - private readonly static IDictionary soapCache = new LeastRecentlyUsedDictionary(200); + private readonly static IDictionary soapCache = + new LeastRecentlyUsedDictionary(200); - private readonly static XmlNamespaceManager namespaceMgr = CreateNamespaceManager(); + private readonly static XmlNamespaceManager namespaceMgr = + CreateNamespaceManager(); - private static void AddBookmarkInfo(IMediaResource resource, XmlElement item) + private static void AddBookmarkInfo(IMediaResource resource, + XmlElement item) { var bookmarkable = resource as IBookmarkable; if (bookmarkable == null) { @@ -35,13 +42,15 @@ private static void AddBookmarkInfo(IMediaResource resource, XmlElement item) } var bookmark = bookmarkable.Bookmark; if (bookmark.HasValue) { - var dcmInfo = item.OwnerDocument.CreateElement("sec", "dcmInfo", NS_SEC); + var dcmInfo = item.OwnerDocument.CreateElement( + "sec", "dcmInfo", NS_SEC); dcmInfo.InnerText = string.Format("BM={0}", bookmark.Value); item.AppendChild(dcmInfo); } } - private void AddCover(IRequest request, IMediaResource resource, XmlElement item) + private void AddCover(IRequest request, IMediaResource resource, + XmlElement item) { var result = item.OwnerDocument; var cover = resource as IMediaCover; @@ -135,7 +144,8 @@ private static void AddGeneralProperties(IHeaders props, XmlElement item) item.AppendChild(e); } if (props.TryGetValue("Track", out prop)) { - var e = item.OwnerDocument.CreateElement("upnp", "originalTrackNumber", NS_UPNP); + var e = item.OwnerDocument.CreateElement( + "upnp", "originalTrackNumber", NS_UPNP); e.InnerText = prop; item.AppendChild(e); } @@ -152,7 +162,9 @@ private static void AddGeneralProperties(IHeaders props, XmlElement item) } } - private static void AddVideoProperties(IRequest request, IMediaResource resource, XmlElement item) + private static void AddVideoProperties(IRequest request, + IMediaResource resource, + XmlElement item) { var mvi = resource as IMetaVideoItem; if (mvi == null) { @@ -171,9 +183,10 @@ private static void AddVideoProperties(IRequest request, IMediaResource resource catch (Exception) { } #if ANNOUNCE_SUBTITLE_IN_SOAP - // This is a kind of costly operation, as getting subtitles in general for the - // first time is costly. Most Samsung TVs seem to query the subtitle when actually - // playing a file anyway (see ItemResponse), and that should be enough. + // This is a kind of costly operation, as getting subtitles in general + // for the first time is costly. Most Samsung TVs seem to query the + // subtitle when actually playing a file anyway (see ItemResponse), and + // that should be enough. if (mvi.SubTitle.HasSubtitle) { var surl = String.Format( "http://{0}:{1}{2}subtitle/{3}/st.srt", @@ -223,7 +236,8 @@ private static void Browse_AddFolder(XmlDocument result, IMediaFolder f) result.DocumentElement.AppendChild(container); } - private void Browse_AddItem(IRequest request, XmlDocument result, IMediaResource resource) + private void Browse_AddItem(IRequest request, XmlDocument result, + IMediaResource resource) { var props = resource.Properties; @@ -274,7 +288,9 @@ private void Browse_AddItem(IRequest request, XmlDocument result, IMediaResource result.DocumentElement.AppendChild(item); } - private int BrowseFolder_AddItems(IRequest request, XmlDocument result, IMediaFolder root, int start, int requested) + private int BrowseFolder_AddItems(IRequest request, XmlDocument result, + IMediaFolder root, int start, + int requested) { var provided = 0; foreach (var i in root.ChildFolders) { @@ -309,7 +325,8 @@ private static XmlNamespaceManager CreateNamespaceManager() return rv; } - private static XmlElement CreateObjectClass(XmlDocument result, IMediaResource resource) + private static XmlElement CreateObjectClass(XmlDocument result, + IMediaResource resource) { var objectClass = result.CreateElement("upnp", "class", NS_UPNP); switch (resource.MediaType) { @@ -328,7 +345,8 @@ private static XmlElement CreateObjectClass(XmlDocument result, IMediaResource r return objectClass; } - private IEnumerable> HandleBrowse(IRequest request, IHeaders sparams) + private IEnumerable> HandleBrowse( + IRequest request, IHeaders sparams) { var key = Prefix + sparams.HeaderBlock; AttributeCollection rv; @@ -343,7 +361,8 @@ private IEnumerable> HandleBrowse(IRequest request, var provided = 0; var start = 0; try { - if (int.TryParse(sparams["RequestedCount"], out requested) && requested <= 0) { + if (int.TryParse(sparams["RequestedCount"], out requested) && + requested <= 0) { requested = 20; } if (int.TryParse(sparams["StartingIndex"], out start) && start <= 0) { @@ -369,7 +388,8 @@ private IEnumerable> HandleBrowse(IRequest request, provided++; } else { - provided = BrowseFolder_AddItems(request, result, root, start, requested); + provided = BrowseFolder_AddItems( + request, result, root, start, requested); } var resXML = result.OuterXml; rv = new AttributeCollection() { @@ -452,7 +472,8 @@ private IHeaders HandleXSetBookmark(IHeaders sparams) if (newbookmark > 30) { newbookmark -= 5; } - if (newbookmark > 30 || !item.Bookmark.HasValue || item.Bookmark.Value < 60) { + if (newbookmark > 30 || !item.Bookmark.HasValue || + item.Bookmark.Value < 60) { item.Bookmark = newbookmark; soapCache.Clear(); } @@ -478,7 +499,9 @@ private IResponse ProcessSoapRequest(IRequest request) env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", "yes")); var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV); env.AppendChild(envelope); - envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/"); + envelope.SetAttribute( + "encodingStyle", NS_SOAPENV, + "http://schemas.xmlsoap.org/soap/encoding/"); var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV); env.DocumentElement.AppendChild(rbody); @@ -526,7 +549,8 @@ private IResponse ProcessSoapRequest(IRequest request) default: throw new HttpStatusException(HttpCode.NotFound); } - var response = env.CreateElement(String.Format("u:{0}Response", method.LocalName), method.NamespaceURI); + var response = env.CreateElement(String.Format( + "u:{0}Response", method.LocalName), method.NamespaceURI); rbody.AppendChild(response); foreach (var i in result) { @@ -545,10 +569,13 @@ private IResponse ProcessSoapRequest(IRequest request) faultString.InnerText = ex.ToString(); fault.AppendChild(faultString); var detail = env.CreateDocumentFragment(); - detail.InnerXml = "401Invalid Action"; + detail.InnerXml = + "401Invalid Action"; fault.AppendChild(detail); rbody.AppendChild(fault); - WarnFormat("Invalid call: Action: {0}, Params: {1}, Problem {2}", method.LocalName, sparams, ex.Message); + WarnFormat( + "Invalid call: Action: {0}, Params: {1}, Problem {2}", + method.LocalName, sparams, ex.Message); } var rv = new StringResponse(code, "text/xml", env.OuterXml); diff --git a/server/Http/HTTPServer.cs b/server/Http/HTTPServer.cs index 8896f2fe..8bbe6e33 100644 --- a/server/Http/HTTPServer.cs +++ b/server/Http/HTTPServer.cs @@ -59,7 +59,8 @@ public HttpServer(int port) RealPort = (listener.LocalEndpoint as IPEndPoint).Port; - NoticeFormat("Running HTTP Server: {0} on port {1}", Signature, RealPort); + NoticeFormat( + "Running HTTP Server: {0} on port {1}", Signature, RealPort); ssdpServer = new SsdpHandler(); timeouter.Elapsed += TimeouterCallback; @@ -169,7 +170,8 @@ internal bool AuthorizeClient(HttpClient client) if (IPAddress.IsLoopback(client.RemoteEndpoint.Address)) { return true; } - var e = new HttpAuthorizationEventArgs(client.Headers, client.RemoteEndpoint); + var e = new HttpAuthorizationEventArgs( + client.Headers, client.RemoteEndpoint); OnAuthorizeClient(this, e); return !e.Cancel; } diff --git a/server/Http/HttpAuthorizationEventArgs.cs b/server/Http/HttpAuthorizationEventArgs.cs index eab78a02..22bcab6d 100644 --- a/server/Http/HttpAuthorizationEventArgs.cs +++ b/server/Http/HttpAuthorizationEventArgs.cs @@ -9,7 +9,8 @@ private HttpAuthorizationEventArgs() { } - internal HttpAuthorizationEventArgs(IHeaders headers, IPEndPoint remoteEndpoint) + internal HttpAuthorizationEventArgs(IHeaders headers, + IPEndPoint remoteEndpoint) { Headers = headers; RemoteEndpoint = remoteEndpoint; diff --git a/server/Http/HttpAuthorizer.cs b/server/Http/HttpAuthorizer.cs index 84d6f1fa..ef93c1ec 100644 --- a/server/Http/HttpAuthorizer.cs +++ b/server/Http/HttpAuthorizer.cs @@ -5,7 +5,8 @@ namespace NMaier.SimpleDlna.Server { - public sealed class HttpAuthorizer : Logging, IHttpAuthorizationMethod, IDisposable + public sealed class HttpAuthorizer + : Logging, IHttpAuthorizationMethod, IDisposable { private readonly List methods = new List(); diff --git a/server/Http/HttpClient.cs b/server/Http/HttpClient.cs index 32394f78..4889220d 100644 --- a/server/Http/HttpClient.cs +++ b/server/Http/HttpClient.cs @@ -22,7 +22,8 @@ internal sealed class HttpClient : Logging, IRequest, IDisposable private readonly byte[] buffer = new byte[2048]; - private static readonly Regex bytes = new Regex(@"^bytes=(\d+)(?:-(\d+)?)?$", RegexOptions.Compiled); + private static readonly Regex bytes = + new Regex(@"^bytes=(\d+)(?:-(\d+)?)?$", RegexOptions.Compiled); private readonly static IHandler Error403 = new StaticHandler(new StringResponse( @@ -220,8 +221,9 @@ private Stream ProcessRanges(IResponse rangedResponse, ref HttpCode status) if (!long.TryParse(m.Groups[1].Value, out start) || start < 0) { throw new InvalidDataException("Not parsed"); } - if (m.Groups.Count != 3 || !long.TryParse(m.Groups[2].Value, out end) || - end <= start || end >= totalLength) { + if (m.Groups.Count != 3 || + !long.TryParse(m.Groups[2].Value, out end) || + end <= start || end >= totalLength) { end = totalLength - 1; } if (start >= end) { @@ -242,7 +244,8 @@ private Stream ProcessRanges(IResponse rangedResponse, ref HttpCode status) status = HttpCode.Partial; } catch (Exception ex) { - Warn(String.Format("{0} - Failed to process range request!", this), ex); + Warn(String.Format( + "{0} - Failed to process range request!", this), ex); } return responseBody; } @@ -321,7 +324,8 @@ private void ReadCallback(IAsyncResult result) } } if (bodyBytes != 0 && bodyBytes > readStream.Length) { - DebugFormat("{0} - Bytes to go {1}", this, bodyBytes - readStream.Length); + DebugFormat( + "{0} - Bytes to go {1}", this, bodyBytes - readStream.Length); Read(); return; } @@ -465,7 +469,8 @@ internal void Close() { State = HttpStates.CLOSED; - DebugFormat("{0} - Closing connection after {1} requests", this, requestCount); + DebugFormat( + "{0} - Closing connection after {1} requests", this, requestCount); try { client.Close(); } diff --git a/server/Http/HttpPhrases.cs b/server/Http/HttpPhrases.cs index f7786da9..09266ea0 100644 --- a/server/Http/HttpPhrases.cs +++ b/server/Http/HttpPhrases.cs @@ -4,16 +4,17 @@ namespace NMaier.SimpleDlna.Server { internal static class HttpPhrases { - public static readonly IDictionary Phrases = new Dictionary() { - { HttpCode.Ok, "OK" }, - { HttpCode.Partial, "Partial Content" }, - { HttpCode.MovedPermanently, "Moved Permanently" }, - { HttpCode.NotModified, "Not Modified" }, - { HttpCode.TemporaryRedirect, "Temprary Redirect" }, - { HttpCode.Denied, "Forbidden" }, - { HttpCode.NotFound, "Not Found" }, - { HttpCode.RangeNotSatisfiable, "Requested Range not satisfiable" }, - { HttpCode.InternalError, "Internal Server Error" } - }; + public static readonly IDictionary Phrases = + new Dictionary() { + { HttpCode.Ok, "OK" }, + { HttpCode.Partial, "Partial Content" }, + { HttpCode.MovedPermanently, "Moved Permanently" }, + { HttpCode.NotModified, "Not Modified" }, + { HttpCode.TemporaryRedirect, "Temprary Redirect" }, + { HttpCode.Denied, "Forbidden" }, + { HttpCode.NotFound, "Not Found" }, + { HttpCode.RangeNotSatisfiable, "Requested Range not satisfiable" }, + { HttpCode.InternalError, "Internal Server Error" } + }; } } diff --git a/server/Interfaces/IMediaItem.cs b/server/Interfaces/IMediaItem.cs index 6d233e4e..b71a627a 100644 --- a/server/Interfaces/IMediaItem.cs +++ b/server/Interfaces/IMediaItem.cs @@ -2,7 +2,8 @@ namespace NMaier.SimpleDlna.Server { - public interface IMediaItem : IComparable, IEquatable, ITitleComparable + public interface IMediaItem + : IComparable, IEquatable, ITitleComparable { string Id { get; set; } diff --git a/server/Interfaces/Metadata/IMetaAudioItem.cs b/server/Interfaces/Metadata/IMetaAudioItem.cs index bd7a2228..f9d22023 100644 --- a/server/Interfaces/Metadata/IMetaAudioItem.cs +++ b/server/Interfaces/Metadata/IMetaAudioItem.cs @@ -1,6 +1,7 @@ namespace NMaier.SimpleDlna.Server.Metadata { - public interface IMetaAudioItem : IMetaInfo, IMetaDescription, IMetaDuration, IMetaGenre + public interface IMetaAudioItem + : IMetaInfo, IMetaDescription, IMetaDuration, IMetaGenre { string MetaAlbum { get; } diff --git a/server/Interfaces/Metadata/IMetaImageItem.cs b/server/Interfaces/Metadata/IMetaImageItem.cs index 3c8631c1..d84db3e7 100644 --- a/server/Interfaces/Metadata/IMetaImageItem.cs +++ b/server/Interfaces/Metadata/IMetaImageItem.cs @@ -1,6 +1,7 @@ namespace NMaier.SimpleDlna.Server.Metadata { - public interface IMetaImageItem : IMetaInfo, IMetaResolution, IMetaDescription + public interface IMetaImageItem + : IMetaInfo, IMetaResolution, IMetaDescription { string MetaCreator { get; } } diff --git a/server/Interfaces/Metadata/IMetaVideoItem.cs b/server/Interfaces/Metadata/IMetaVideoItem.cs index 7dba6cb5..c92af98e 100644 --- a/server/Interfaces/Metadata/IMetaVideoItem.cs +++ b/server/Interfaces/Metadata/IMetaVideoItem.cs @@ -2,7 +2,8 @@ namespace NMaier.SimpleDlna.Server.Metadata { - public interface IMetaVideoItem : IMetaInfo, IMetaDescription, IMetaGenre, IMetaDuration, IMetaResolution + public interface IMetaVideoItem + : IMetaInfo, IMetaDescription, IMetaGenre, IMetaDuration, IMetaResolution { IEnumerable MetaActors { get; } diff --git a/server/Responses/ItemResponse.cs b/server/Responses/ItemResponse.cs index 3d5798f5..0d625bcc 100644 --- a/server/Responses/ItemResponse.cs +++ b/server/Responses/ItemResponse.cs @@ -13,7 +13,8 @@ internal sealed class ItemResponse : Logging, IResponse private readonly HttpCode status = HttpCode.Ok; - public ItemResponse(string prefix, IRequest request, IMediaResource item, string transferMode = "Streaming") + public ItemResponse(string prefix, IRequest request, IMediaResource item, + string transferMode = "Streaming") { this.item = item; headers = new ResponseHeaders(noCache: !(item is IMediaCoverResource)); diff --git a/server/Responses/ResourceResponse.cs b/server/Responses/ResourceResponse.cs index 96a38a1b..e2b43f27 100644 --- a/server/Responses/ResourceResponse.cs +++ b/server/Responses/ResourceResponse.cs @@ -18,7 +18,8 @@ public ResourceResponse(HttpCode aStatus, string type, string aResource) { } - public ResourceResponse(HttpCode aStatus, string type, ResourceManager aResourceManager, string aResource) + public ResourceResponse(HttpCode aStatus, string type, + ResourceManager aResourceManager, string aResource) { status = aStatus; try { diff --git a/server/Ssdp/Datagram.cs b/server/Ssdp/Datagram.cs index a23b3c3d..505666a0 100644 --- a/server/Ssdp/Datagram.cs +++ b/server/Ssdp/Datagram.cs @@ -16,10 +16,11 @@ internal sealed class Datagram : Logging public readonly bool Sticky; - public Datagram(IPEndPoint endPoint, IPAddress localAddresss, string message, bool sticky) + public Datagram(IPEndPoint endPoint, IPAddress localAddress, + string message, bool sticky) { EndPoint = endPoint; - LocalAddress = localAddresss; + LocalAddress = localAddress; Message = message; Sticky = sticky; SendCount = 0; diff --git a/server/Ssdp/SsdpHandler.cs b/server/Ssdp/SsdpHandler.cs index b921ea21..7ece095a 100644 --- a/server/Ssdp/SsdpHandler.cs +++ b/server/Ssdp/SsdpHandler.cs @@ -129,7 +129,8 @@ private void ReceiveCallback(IAsyncResult result) #if DUMP_ALL_SSDP DebugFormat("{0} - SSDP Received a datagram", endpoint); #endif - using (var reader = new StreamReader(new MemoryStream(received), Encoding.ASCII)) { + using (var reader = new StreamReader( + new MemoryStream(received), Encoding.ASCII)) { var proto = reader.ReadLine(); if (proto == null) { throw new IOException("Couldn't read protocol line"); @@ -167,7 +168,8 @@ private void ReceiveCallback(IAsyncResult result) Receive(); } - private void SendDatagram(IPEndPoint endpoint, IPAddress address, string message, bool sticky) + private void SendDatagram(IPEndPoint endpoint, IPAddress address, + string message, bool sticky) { if (!running) { return; @@ -197,7 +199,9 @@ private void SendSearchResponse(IPEndPoint endpoint, UpnpDevice dev) String.Format("HTTP/1.1 200 OK\r\n{0}\r\n", headers.HeaderBlock), false ); - InfoFormat("{2}, {1} - Responded to a {0} request", dev.Type, endpoint, dev.Address); + InfoFormat( + "{2}, {1} - Responded to a {0} request", dev.Type, endpoint, + dev.Address); } private void Tick(object sender, Timers.ElapsedEventArgs e) @@ -236,7 +240,8 @@ internal void NotifyDevice(UpnpDevice dev, string type, bool sticky) DebugFormat("{0} said {1}", dev.USN, type); } - internal void RegisterNotification(Guid UUID, Uri Descriptor, IPAddress address) + internal void RegisterNotification(Guid UUID, Uri Descriptor, + IPAddress address) { List list; lock (devices) { diff --git a/server/Types/AudioResourceDecorator.cs b/server/Types/AudioResourceDecorator.cs index a55cba14..2758d0e8 100644 --- a/server/Types/AudioResourceDecorator.cs +++ b/server/Types/AudioResourceDecorator.cs @@ -2,7 +2,8 @@ namespace NMaier.SimpleDlna.Server { - internal class AudioResourceDecorator : MediaResourceDecorator + internal class AudioResourceDecorator + : MediaResourceDecorator { public AudioResourceDecorator(IMediaAudioResource resource) : base(resource) diff --git a/server/Types/DlnaMediaTypes.cs b/server/Types/DlnaMediaTypes.cs index 269c7a3a..a524770a 100644 --- a/server/Types/DlnaMediaTypes.cs +++ b/server/Types/DlnaMediaTypes.cs @@ -7,6 +7,7 @@ public enum DlnaMediaTypes : int { Audio = 1 << 2, Image = 1 << 1, - Video = 1 << 0 + Video = 1 << 0, + All = ~(-1 << 3) } } diff --git a/server/Types/Headers.cs b/server/Types/Headers.cs index 6b277466..be6d2761 100644 --- a/server/Types/Headers.cs +++ b/server/Types/Headers.cs @@ -14,8 +14,9 @@ public class Headers : IHeaders private readonly Dictionary dict = new Dictionary(); - private readonly static Regex validator = - new Regex(@"^[a-z\d][a-z\d_.-]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly static Regex validator = new Regex( + @"^[a-z\d][a-z\d_.-]+$", + RegexOptions.Compiled | RegexOptions.IgnoreCase); protected Headers(bool asIs) { @@ -125,7 +126,8 @@ public void Clear() public bool Contains(KeyValuePair item) { - var p = new KeyValuePair(Normalize(item.Key), item.Value); + var p = new KeyValuePair( + Normalize(item.Key), item.Value); return dict.Contains(p); } diff --git a/server/Types/HtmlTools.cs b/server/Types/HtmlTools.cs index 6bad149a..6ecc6148 100644 --- a/server/Types/HtmlTools.cs +++ b/server/Types/HtmlTools.cs @@ -11,7 +11,8 @@ public static XmlElement CreateHtmlArticle(string title) title += " – SimpleDLNA"; var document = new XmlDocument(); - document.AppendChild(document.CreateDocumentType("html", null, null, null)); + document.AppendChild(document.CreateDocumentType( + "html", null, null, null)); document.AppendChild(document.EL("html")); @@ -53,7 +54,9 @@ public static XmlElement CreateHtmlArticle(string title) "A simple, zero-config DLNA media server, that you can just fire up and be done with it." )); footer.AppendChild(document.EL("a", - new AttributeCollection() { { "href", "https://github.com/nmaier/simpleDLNA/" } }, + new AttributeCollection() { + { "href", "https://github.com/nmaier/simpleDLNA/" } + }, "Fork me on GitHub" )); body.AppendChild(footer); diff --git a/server/Types/SubTitle.cs b/server/Types/SubTitle.cs index 26b548db..89587ff9 100644 --- a/server/Types/SubTitle.cs +++ b/server/Types/SubTitle.cs @@ -153,7 +153,8 @@ private void Load(FileInfo file) try { // Try external foreach (var i in exts) { - var sti = new FileInfo(System.IO.Path.ChangeExtension(file.FullName, i)); + var sti = new FileInfo( + System.IO.Path.ChangeExtension(file.FullName, i)); try { if (!sti.Exists) { sti = new FileInfo(file.FullName + i); @@ -166,7 +167,8 @@ private void Load(FileInfo file) catch (NotSupportedException) { } catch (Exception ex) { - logger.Debug(string.Format("Failed to get subtitle from {0}", sti.FullName), ex); + logger.Debug(string.Format( + "Failed to get subtitle from {0}", sti.FullName), ex); } } try { @@ -175,11 +177,13 @@ private void Load(FileInfo file) catch (NotSupportedException) { } catch (Exception ex) { - logger.Debug(string.Format("Failed to get subtitle from {0}", file.FullName), ex); + logger.Debug(string.Format( + "Failed to get subtitle from {0}", file.FullName), ex); } } catch (Exception ex) { - logger.Error(string.Format("Failed to load subtitle for {0}", file.FullName), ex); + logger.Error(string.Format( + "Failed to load subtitle for {0}", file.FullName), ex); } } diff --git a/server/Types/UpnpDevice.cs b/server/Types/UpnpDevice.cs index 9c6da339..91e24c6c 100644 --- a/server/Types/UpnpDevice.cs +++ b/server/Types/UpnpDevice.cs @@ -15,7 +15,8 @@ internal sealed class UpnpDevice public readonly Guid Uuid; - public UpnpDevice(Guid uuid, string type, Uri descriptor, IPAddress address) + public UpnpDevice(Guid uuid, string type, Uri descriptor, + IPAddress address) { Uuid = uuid; Type = type; diff --git a/server/Types/VirtualClonedFolder.cs b/server/Types/VirtualClonedFolder.cs index cd712383..bf1a71d1 100644 --- a/server/Types/VirtualClonedFolder.cs +++ b/server/Types/VirtualClonedFolder.cs @@ -6,7 +6,8 @@ public sealed class VirtualClonedFolder : VirtualFolder private readonly DlnaMediaTypes types; - private VirtualClonedFolder(IMediaFolder parent, string name, string id, DlnaMediaTypes types) + private VirtualClonedFolder(IMediaFolder parent, string name, string id, + DlnaMediaTypes types) : base(parent, name, id) { this.types = types; @@ -17,16 +18,17 @@ private VirtualClonedFolder(IMediaFolder parent, string name, string id, DlnaMed } public VirtualClonedFolder(IMediaFolder parent) - : this(parent, parent.Id, parent.Id, DlnaMediaTypes.Audio | DlnaMediaTypes.Image | DlnaMediaTypes.Video) + : this(parent, parent.Id, parent.Id, DlnaMediaTypes.All) { } public VirtualClonedFolder(IMediaFolder parent, string name) - : this(parent, name, name, DlnaMediaTypes.Audio | DlnaMediaTypes.Image | DlnaMediaTypes.Video) + : this(parent, name, name, DlnaMediaTypes.All) { } - public VirtualClonedFolder(IMediaFolder parent, string name, DlnaMediaTypes types) + public VirtualClonedFolder(IMediaFolder parent, string name, + DlnaMediaTypes types) : this(parent, name, name, types) { } diff --git a/server/Views/DimensionView.cs b/server/Views/DimensionView.cs index ce68e90f..318956ee 100644 --- a/server/Views/DimensionView.cs +++ b/server/Views/DimensionView.cs @@ -78,7 +78,8 @@ public override void SetParameters(AttributeCollection parameters) maxHeight = SetParametersFor(parameters, "maxheight"); } - public static uint? SetParametersFor(AttributeCollection parameters, string key) + public static uint? SetParametersFor(AttributeCollection parameters, + string key) { var val = (uint?)null; foreach (var v in parameters.GetValuesForKey(key)) { @@ -92,7 +93,8 @@ public override void SetParameters(AttributeCollection parameters) public override IMediaFolder Transform(IMediaFolder root) { - if (!min.HasValue && !max.HasValue && !minWidth.HasValue && !maxWidth.HasValue && !minHeight.HasValue && !maxHeight.HasValue) { + if (!min.HasValue && !max.HasValue && !minWidth.HasValue && + !maxWidth.HasValue && !minHeight.HasValue && !maxHeight.HasValue) { return root; } return base.Transform(root); diff --git a/server/Views/FlattenView.cs b/server/Views/FlattenView.cs index e083d7bf..fbefcc8d 100644 --- a/server/Views/FlattenView.cs +++ b/server/Views/FlattenView.cs @@ -25,7 +25,10 @@ private static void MergeFolders(VirtualFolder aFrom, VirtualFolder aTo) var merges = from f in aFrom.ChildFolders join t in aTo.ChildFolders on f.Title equals t.Title where f != t - select new { f = f as VirtualFolder, t = t as VirtualFolder }; + select new { + f = f as VirtualFolder, + t = t as VirtualFolder + }; foreach (var m in merges.ToList()) { MergeFolders(m.f, m.t); foreach (var c in m.f.ChildFolders.ToList()) { @@ -39,7 +42,8 @@ join t in aTo.ChildFolders on f.Title equals t.Title } } - private static bool TransformInternal(VirtualFolder root, VirtualFolder current) + private static bool TransformInternal(VirtualFolder root, + VirtualFolder current) { foreach (var f in current.ChildFolders.ToList()) { var vf = f as VirtualFolder; @@ -77,7 +81,10 @@ public override IMediaFolder Transform(IMediaFolder Root) from t in r.ChildFolders where f != t orderby f.Title, t.Title - select new { f = f as VirtualFolder, t = t as VirtualFolder }; + select new { + f = f as VirtualFolder, + t = t as VirtualFolder + }; foreach (var c in cross) { MergeFolders(c.f, c.t); } diff --git a/server/Views/MusicView.cs b/server/Views/MusicView.cs index b124b550..b259e0e3 100644 --- a/server/Views/MusicView.cs +++ b/server/Views/MusicView.cs @@ -22,7 +22,9 @@ public override string Name } } - private static void LinkTriple(TripleKeyedVirtualFolder folder, IMediaAudioResource r, string key1, string key2) + private static void LinkTriple(TripleKeyedVirtualFolder folder, + IMediaAudioResource r, string key1, + string key2) { if (string.IsNullOrWhiteSpace(key1)) { return; @@ -31,7 +33,8 @@ private static void LinkTriple(TripleKeyedVirtualFolder folder, IMediaAudioResou return; } var targetFolder = folder - .GetFolder(key1.StemCompareBase().First().ToString().ToUpper(CultureInfo.CurrentUICulture)) + .GetFolder(key1.StemCompareBase().First().ToString() + .ToUpper(CultureInfo.CurrentUICulture)) .GetFolder(key1.StemNameBase()); targetFolder .GetFolder(key2.StemNameBase()) @@ -42,7 +45,11 @@ private static void LinkTriple(TripleKeyedVirtualFolder folder, IMediaAudioResou .AddResource(allRes); } - private static void SortFolder(VirtualFolder folder, TripleKeyedVirtualFolder artists, TripleKeyedVirtualFolder performers, DoubleKeyedVirtualFolder albums, SimpleKeyedVirtualFolder genres) + private static void SortFolder(VirtualFolder folder, + TripleKeyedVirtualFolder artists, + TripleKeyedVirtualFolder performers, + DoubleKeyedVirtualFolder albums, + SimpleKeyedVirtualFolder genres) { foreach (var f in folder.ChildFolders.ToList()) { SortFolder(f as VirtualFolder, artists, performers, albums, genres); @@ -108,7 +115,8 @@ public override string Title } } - private class DoubleKeyedVirtualFolder : KeyedVirtualFolder + private class DoubleKeyedVirtualFolder + : KeyedVirtualFolder { public DoubleKeyedVirtualFolder() { @@ -132,7 +140,8 @@ public SimpleKeyedVirtualFolder(IMediaFolder aParent, string aName) } } - private class TripleKeyedVirtualFolder : KeyedVirtualFolder + private class TripleKeyedVirtualFolder + : KeyedVirtualFolder { public TripleKeyedVirtualFolder() { diff --git a/server/Views/SeriesView.cs b/server/Views/SeriesView.cs index 0782d915..0762c398 100644 --- a/server/Views/SeriesView.cs +++ b/server/Views/SeriesView.cs @@ -32,7 +32,8 @@ public override string Name } } - private static void SortFolder(IMediaFolder folder, SimpleKeyedVirtualFolder series) + private static void SortFolder(IMediaFolder folder, + SimpleKeyedVirtualFolder series) { foreach (var f in folder.ChildFolders.ToList()) { SortFolder(f, series); diff --git a/thumbs/ImageThumbnailLoader.cs b/thumbs/ImageThumbnailLoader.cs index 76a6f3ac..71532fcc 100644 --- a/thumbs/ImageThumbnailLoader.cs +++ b/thumbs/ImageThumbnailLoader.cs @@ -16,7 +16,8 @@ public DlnaMediaTypes Handling } } - public MemoryStream GetThumbnail(object item, ref int width, ref int height) + public MemoryStream GetThumbnail(object item, ref int width, + ref int height) { Image img = null; var stream = item as Stream; @@ -33,7 +34,8 @@ public MemoryStream GetThumbnail(object item, ref int width, ref int height) } } using (img) { - using (var scaled = ThumbnailMaker.ResizeImage(img, width, height, ThumbnailMakerBorder.Borderless)) { + using (var scaled = ThumbnailMaker.ResizeImage( + img, width, height, ThumbnailMakerBorder.Borderless)) { width = scaled.Width; height = scaled.Height; var rv = new MemoryStream(); diff --git a/thumbs/ThumbnailMaker.cs b/thumbs/ThumbnailMaker.cs index e1d5c1f8..a73ca093 100644 --- a/thumbs/ThumbnailMaker.cs +++ b/thumbs/ThumbnailMaker.cs @@ -48,7 +48,8 @@ private static Dictionary> BuildThumbnail return thumbers; } - private static bool GetThumbnailFromCache(ref string key, ref int width, ref int height, out byte[] rv) + private static bool GetThumbnailFromCache(ref string key, ref int width, + ref int height, out byte[] rv) { key = string.Format("{0}x{1} {2}", width, height, key); CacheItem ci; @@ -64,7 +65,9 @@ private static bool GetThumbnailFromCache(ref string key, ref int width, ref int return false; } - private byte[] GetThumbnailInternal(string key, object item, DlnaMediaTypes type, ref int width, ref int height) + private byte[] GetThumbnailInternal(string key, object item, + DlnaMediaTypes type, ref int width, + ref int height) { var thumbnailers = thumbers[type]; var rw = width; @@ -80,14 +83,16 @@ private byte[] GetThumbnailInternal(string key, object item, DlnaMediaTypes type } } catch (Exception ex) { - Debug(String.Format("{0} failed to thumbnail a resource", thumber.GetType()), ex); + Debug(String.Format( + "{0} failed to thumbnail a resource", thumber.GetType()), ex); continue; } } throw new ArgumentException("Not a supported resource"); } - internal static Image ResizeImage(Image image, int width, int height, ThumbnailMakerBorder border) + internal static Image ResizeImage(Image image, int width, int height, + ThumbnailMakerBorder border) { var nw = (float)image.Width; var nh = (float)image.Height; @@ -113,11 +118,14 @@ internal static Image ResizeImage(Image image, int width, int height, ThumbnailM } using (var graphics = Graphics.FromImage(result)) { if (result.Width > image.Width && result.Height > image.Height) { - graphics.CompositingQuality = Drawing2D.CompositingQuality.HighQuality; - graphics.InterpolationMode = Drawing2D.InterpolationMode.High; + graphics.CompositingQuality = + Drawing2D.CompositingQuality.HighQuality; + graphics.InterpolationMode = + Drawing2D.InterpolationMode.High; } else { - graphics.CompositingQuality = Drawing2D.CompositingQuality.HighSpeed; + graphics.CompositingQuality = + Drawing2D.CompositingQuality.HighSpeed; graphics.InterpolationMode = Drawing2D.InterpolationMode.Bicubic; } var rect = new Rectangle( @@ -126,7 +134,8 @@ internal static Image ResizeImage(Image image, int width, int height, ThumbnailM (int)nw, (int)nh ); graphics.SmoothingMode = Drawing2D.SmoothingMode.HighSpeed; - graphics.FillRectangle(Brushes.Black, new Rectangle(0, 0, result.Width, result.Height)); + graphics.FillRectangle( + Brushes.Black, new Rectangle(0, 0, result.Width, result.Height)); graphics.DrawImage(image, rect); } return result; @@ -156,7 +165,8 @@ public IThumbnail GetThumbnail(FileSystemInfo file, int width, int height) return new Thumbnail(width, height, rv); } - public IThumbnail GetThumbnail(string key, DlnaMediaTypes type, Stream stream, int width, int height) + public IThumbnail GetThumbnail(string key, DlnaMediaTypes type, + Stream stream, int width, int height) { byte[] rv; if (GetThumbnailFromCache(ref key, ref width, ref height, out rv)) { diff --git a/thumbs/VideoThumbnailLoader.cs b/thumbs/VideoThumbnailLoader.cs index ac586a3c..ad275e65 100644 --- a/thumbs/VideoThumbnailLoader.cs +++ b/thumbs/VideoThumbnailLoader.cs @@ -9,7 +9,8 @@ namespace NMaier.SimpleDlna.Thumbnails { - internal sealed class VideoThumbnailLoader : Logging, IThumbnailLoader, IDisposable + internal sealed class VideoThumbnailLoader + : Logging, IThumbnailLoader, IDisposable { private Semaphore semaphore = new Semaphore(2, 2); @@ -28,10 +29,13 @@ public DlnaMediaTypes Handling } } - private static MemoryStream GetThumbnailFromProcess(Process p, ref int width, ref int height) + private static MemoryStream GetThumbnailFromProcess(Process p, + ref int width, + ref int height) { using (var thumb = new MemoryStream()) { - using (var pump = new StreamPump(p.StandardOutput.BaseStream, thumb, 4096)) { + using (var pump = new StreamPump( + p.StandardOutput.BaseStream, thumb, 4096)) { pump.Pump(null); if (!p.WaitForExit(20000)) { p.Kill(); @@ -48,7 +52,8 @@ private static MemoryStream GetThumbnailFromProcess(Process p, ref int width, re } using (var img = Image.FromStream(thumb)) { - using (var scaled = ThumbnailMaker.ResizeImage(img, width, height, ThumbnailMakerBorder.Bordered)) { + using (var scaled = ThumbnailMaker.ResizeImage(img, width, height, + ThumbnailMakerBorder.Bordered)) { width = scaled.Width; height = scaled.Height; var rv = new MemoryStream(); @@ -66,7 +71,9 @@ private static MemoryStream GetThumbnailFromProcess(Process p, ref int width, re } } - private static MemoryStream GetThumbnailInternal(Stream stream, ref int width, ref int height) + private static MemoryStream GetThumbnailInternal(Stream stream, + ref int width, + ref int height) { using (var p = new Process()) { var pos = 20L; @@ -113,10 +120,13 @@ private static MemoryStream GetThumbnailInternal(Stream stream, ref int width, r } } - private MemoryStream GetThumbnailInternal(FileInfo file, ref int width, ref int height) + private MemoryStream GetThumbnailInternal(FileInfo file, ref int width, + ref int height) { Exception last = null; - for (var best = IdentifyBestCapturePosition(file); best >= 0; best -= Math.Max(best / 2, 5)) { + for (var best = IdentifyBestCapturePosition(file); + best >= 0; + best -= Math.Max(best / 2, 5)) { try { using (var p = new Process()) { var sti = p.StartInfo; @@ -184,7 +194,8 @@ public void Dispose() } } - public MemoryStream GetThumbnail(object item, ref int width, ref int height) + public MemoryStream GetThumbnail(object item, ref int width, + ref int height) { semaphore.WaitOne(); try { diff --git a/util/AddressToMacResolver.cs b/util/AddressToMacResolver.cs index e92ab90c..1b675b6f 100644 --- a/util/AddressToMacResolver.cs +++ b/util/AddressToMacResolver.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Net; using System.Text.RegularExpressions; +using System.Net.Sockets; namespace NMaier.SimpleDlna.Utilities { @@ -25,7 +26,7 @@ public static bool IsAcceptedMac(string mac) public string Resolve(IPAddress ip) { try { - if (ip.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { + if (ip.AddressFamily != AddressFamily.InterNetwork) { throw new NotSupportedException( "Addresses other than IPV4 are not supported"); } @@ -50,8 +51,7 @@ public string Resolve(IPAddress ip) catch (DllNotFoundException) { // ignore } - cache.TryAdd(ip, new MACInfo() - { + cache.TryAdd(ip, new MACInfo() { MAC = mac, Fresh = DateTime.Now.AddMinutes(mac != null ? 10 : 1) }); diff --git a/util/Ffmpeg.cs b/util/Ffmpeg.cs index 7de66a27..7ac97cd5 100644 --- a/util/Ffmpeg.cs +++ b/util/Ffmpeg.cs @@ -14,13 +14,21 @@ namespace NMaier.SimpleDlna.Utilities public static class FFmpeg { + private static DirectoryInfo GetFFMpegFolder( + Environment.SpecialFolder folder) + { + return new DirectoryInfo( + Path.Combine(Environment.GetFolderPath(folder), "ffmpeg")); + } + private static readonly DirectoryInfo[] specialLocations = new DirectoryInfo[] { - new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles), "ffmpeg")), - new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86), "ffmpeg")), - new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "ffmpeg")), - new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "ffmpeg")), - new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "ffmpeg")), - new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)) + GetFFMpegFolder(Environment.SpecialFolder.CommonProgramFiles), + GetFFMpegFolder(Environment.SpecialFolder.CommonProgramFilesX86), + GetFFMpegFolder(Environment.SpecialFolder.ProgramFiles), + GetFFMpegFolder(Environment.SpecialFolder.ProgramFilesX86), + GetFFMpegFolder(Environment.SpecialFolder.UserProfile), + new DirectoryInfo(Environment.GetFolderPath( + Environment.SpecialFolder.UserProfile)) }; private readonly static InfoCache infoCache = new InfoCache(500); @@ -28,18 +36,20 @@ public static class FFmpeg private static readonly Regex regAssStrip = new Regex(@"^,+", RegexOptions.Compiled); - private static readonly Regex regDuration = - new Regex(@"Duration: ([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?", RegexOptions.Compiled); + private static readonly Regex regDuration = new Regex( + @"Duration: ([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?", + RegexOptions.Compiled); - private static readonly Regex regDimensions = - new Regex(@"Video: .+ ([0-9]{2,})x([0-9]{2,}) ", RegexOptions.Compiled); + private static readonly Regex regDimensions = new Regex( + @"Video: .+ ([0-9]{2,})x([0-9]{2,}) ", RegexOptions.Compiled); - public static readonly string FFmpegExecutable = FindExecutable("ffmpeg"); + public static readonly string FFmpegExecutable = + FindExecutable("ffmpeg"); private static string FindExecutable(string executable) { - var isWin = Environment.OSVersion.Platform.ToString().ToUpperInvariant(). - Contains("WIN"); + var os = Environment.OSVersion.Platform.ToString().ToUpperInvariant(); + var isWin = os.Contains("WIN"); if (isWin) { executable += ".exe"; } @@ -71,11 +81,16 @@ private static string FindExecutable(string executable) } foreach (var i in places) { - LogManager.GetLogger(typeof(FFmpeg)).DebugFormat("Searching {0}", i.FullName); + LogManager.GetLogger(typeof(FFmpeg)).DebugFormat( + "Searching {0}", i.FullName); if (!i.Exists) { continue; } - foreach (var di in new[] { i, new DirectoryInfo(Path.Combine(i.FullName, "bin")) }) { + var folders = new[] { + i, + new DirectoryInfo(Path.Combine(i.FullName, "bin")) + }; + foreach (var di in folders) { try { var r = di.GetFiles(executable, SearchOption.TopDirectoryOnly); if (r.Length != 0) { @@ -98,7 +113,8 @@ private static string FindExecutable(string executable) return null; } - private static IDictionary IdentifyFileInternal(FileInfo file) + private static IDictionary IdentifyFileInternal( + FileInfo file) { if (FFmpeg.FFmpegExecutable == null) { throw new NotSupportedException(); @@ -118,7 +134,8 @@ private static IDictionary IdentifyFileInternal(FileInfo file) } } - private static IDictionary IdentifyInternalFromProcess(FileInfo file) + private static IDictionary IdentifyInternalFromProcess( + FileInfo file) { IDictionary rv; @@ -136,7 +153,8 @@ private static IDictionary IdentifyInternalFromProcess(FileInfo rv = new Dictionary(); using (var reader = new StreamReader(new MemoryStream())) { - using (var pump = new StreamPump(p.StandardError.BaseStream, reader.BaseStream, 4096)) { + using (var pump = new StreamPump( + p.StandardError.BaseStream, reader.BaseStream, 4096)) { pump.Pump(null); if (!p.WaitForExit(3000)) { throw new NotSupportedException("ffmpeg timed out"); @@ -153,11 +171,13 @@ private static IDictionary IdentifyInternalFromProcess(FileInfo if (int.TryParse(match.Groups[1].Value, out h) && int.TryParse(match.Groups[2].Value, out m) && int.TryParse(match.Groups[3].Value, out s)) { - if (match.Groups.Count < 5 || !int.TryParse(match.Groups[4].Value, out ms)) { + if (match.Groups.Count < 5 || + !int.TryParse(match.Groups[4].Value, out ms)) { ms = 0; } var ts = new TimeSpan(0, h, m, s, ms * 10); - var tss = ts.TotalSeconds.ToString(CultureInfo.InvariantCulture); + var tss = ts.TotalSeconds.ToString( + CultureInfo.InvariantCulture); rv.Add("LENGTH", tss); } } @@ -196,11 +216,14 @@ public static Size GetFileDimensions(FileInfo file) public static double GetFileDuration(FileInfo file) { string sl; - double dur; - if (FFmpeg.IdentifyFile(file).TryGetValue("LENGTH", out sl) - && Double.TryParse(sl, NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("en-US", "en"), out dur) - && dur > 0) { - return dur; + if (FFmpeg.IdentifyFile(file).TryGetValue("LENGTH", out sl)) { + double dur; + bool valid = Double.TryParse( + sl, NumberStyles.AllowDecimalPoint, + CultureInfo.GetCultureInfo("en-US", "en"), out dur); + if (valid && dur > 0) { + return dur; + } } throw new NotSupportedException(); } @@ -221,13 +244,15 @@ public static string GetSubtitleSubrip(FileInfo file) #endif sti.UseShellExecute = false; sti.FileName = FFmpeg.FFmpegExecutable; - sti.Arguments = String.Format("-i \"{0}\" -map s:0 -f srt pipe:", file.FullName); + sti.Arguments = String.Format( + "-i \"{0}\" -map s:0 -f srt pipe:", file.FullName); sti.LoadUserProfile = false; sti.RedirectStandardOutput = true; p.Start(); using (var reader = new StreamReader(new MemoryStream())) { - using (var pump = new StreamPump(p.StandardOutput.BaseStream, reader.BaseStream, 40960)) { + using (var pump = new StreamPump( + p.StandardOutput.BaseStream, reader.BaseStream, 40960)) { pump.Pump(null); if (!p.WaitForExit(10000)) { throw new NotSupportedException("ffmpeg timed out"); @@ -252,7 +277,8 @@ public static string GetSubtitleSubrip(FileInfo file) catch (Exception ex) { throw new NotSupportedException(ex.Message, ex); } - throw new NotSupportedException("File does not contain a valid subtitle"); + throw new NotSupportedException( + "File does not contain a valid subtitle"); } public static IDictionary IdentifyFile(FileInfo file) diff --git a/util/HttpStream.cs b/util/HttpStream.cs index e0836356..14237603 100644 --- a/util/HttpStream.cs +++ b/util/HttpStream.cs @@ -198,7 +198,8 @@ protected void OpenAt(long offset, HttpMethod method) throw new IOException("Position cannot be negative"); } if (offset > 0 && method == HttpMethod.HEAD) { - throw new ArgumentException("Cannot use a position (seek) with HEAD request"); + throw new ArgumentException( + "Cannot use a position (seek) with HEAD request"); } Close(); Dispose(); @@ -220,7 +221,8 @@ protected void OpenAt(long offset, HttpMethod method) bufferedStream = new BufferedStream(responseStream, BUFFER_SIZE); } if (offset > 0 && response.StatusCode != HttpStatusCode.PartialContent) { - throw new IOException("Failed to open the http stream at a specific position"); + throw new IOException( + "Failed to open the http stream at a specific position"); } else { if (offset == 0 && response.StatusCode != HttpStatusCode.OK) { @@ -306,7 +308,7 @@ public override long Seek(long offset, SeekOrigin origin) } } position = np; - logger.DebugFormat("Successfully seeked to {0}", position); + logger.DebugFormat("Successfully sought to {0}", position); return position; } diff --git a/util/IP.cs b/util/IP.cs index eef3cc3b..e8abb665 100644 --- a/util/IP.cs +++ b/util/IP.cs @@ -26,7 +26,9 @@ public static IEnumerable AllIPAddresses } catch (Exception ex) { if (!warned) { - logger.Warn("Failed to retrieve IP addresses the usual way, falling back to naive mode", ex); + logger.Warn( + "Failed to retrieve IP addresses the usual way, falling back to naive mode", + ex); warned = true; } return GetIPsFallback(); diff --git a/util/LeastRecentlyUsedDictionary.cs b/util/LeastRecentlyUsedDictionary.cs index aa895df1..2c19ead8 100644 --- a/util/LeastRecentlyUsedDictionary.cs +++ b/util/LeastRecentlyUsedDictionary.cs @@ -7,7 +7,8 @@ namespace NMaier.SimpleDlna.Utilities { - public sealed class LeastRecentlyUsedDictionary : IDictionary + public sealed class LeastRecentlyUsedDictionary + : IDictionary { private readonly uint capacity; diff --git a/util/Logging.cs b/util/Logging.cs index b9d59e95..b7c7ae78 100644 --- a/util/Logging.cs +++ b/util/Logging.cs @@ -100,12 +100,14 @@ public void DebugFormat(string format, object arg0, object arg1) logger.DebugFormat(format, arg0, arg1); } - public void DebugFormat(IFormatProvider provider, string format, params object[] args) + public void DebugFormat(IFormatProvider provider, string format, + params object[] args) { logger.DebugFormat(provider, format, args); } - public void DebugFormat(string format, object arg0, object arg1, object arg2) + public void DebugFormat(string format, object arg0, object arg1, + object arg2) { logger.DebugFormat(format, arg0, arg1, arg2); } @@ -135,12 +137,14 @@ public void ErrorFormat(string format, object arg0, object arg1) logger.ErrorFormat(format, arg0, arg1); } - public void ErrorFormat(IFormatProvider provider, string format, params object[] args) + public void ErrorFormat(IFormatProvider provider, string format, + params object[] args) { logger.ErrorFormat(provider, format, args); } - public void ErrorFormat(string format, object arg0, object arg1, object arg2) + public void ErrorFormat(string format, object arg0, object arg1, + object arg2) { logger.ErrorFormat(format, arg0, arg1, arg2); } @@ -170,12 +174,14 @@ public void FatalFormat(string format, object arg0, object arg1) logger.FatalFormat(format, arg0, arg1); } - public void FatalFormat(IFormatProvider provider, string format, params object[] args) + public void FatalFormat(IFormatProvider provider, string format, + params object[] args) { logger.FatalFormat(provider, format, args); } - public void FatalFormat(string format, object arg0, object arg1, object arg2) + public void FatalFormat(string format, object arg0, object arg1, + object arg2) { logger.FatalFormat(format, arg0, arg1, arg2); } @@ -205,12 +211,14 @@ public void InfoFormat(string format, object arg0, object arg1) logger.InfoFormat(format, arg0, arg1); } - public void InfoFormat(IFormatProvider provider, string format, params object[] args) + public void InfoFormat(IFormatProvider provider, string format, + params object[] args) { logger.InfoFormat(provider, format, args); } - public void InfoFormat(string format, object arg0, object arg1, object arg2) + public void InfoFormat(string format, object arg0, object arg1, + object arg2) { logger.InfoFormat(format, arg0, arg1, arg2); } @@ -237,17 +245,23 @@ public void NoticeFormat(string format, object arg0) public void NoticeFormat(string format, object arg0, object arg1) { - Logger.Log(GetType(), Level.Notice, string.Format(format, arg0, arg1), null); + Logger.Log( + GetType(), Level.Notice, string.Format(format, arg0, arg1), null); } - public void NoticeFormat(IFormatProvider provider, string format, params object[] args) + public void NoticeFormat(IFormatProvider provider, string format, + params object[] args) { - Logger.Log(GetType(), Level.Notice, string.Format(provider, format, args), null); + Logger.Log( + GetType(), Level.Notice, string.Format(provider, format, args), null); } - public void NoticeFormat(string format, object arg0, object arg1, object arg2) + public void NoticeFormat(string format, object arg0, object arg1, + object arg2) { - Logger.Log(GetType(), Level.Notice, string.Format(format, arg0, arg1, arg2), null); + Logger.Log( + GetType(), Level.Notice, string.Format(format, arg0, arg1, arg2), + null); } public void Warn(object message) @@ -275,12 +289,14 @@ public void WarnFormat(string format, object arg0, object arg1) logger.WarnFormat(format, arg0, arg1); } - public void WarnFormat(IFormatProvider provider, string format, params object[] args) + public void WarnFormat(IFormatProvider provider, string format, + params object[] args) { logger.WarnFormat(provider, format, args); } - public void WarnFormat(string format, object arg0, object arg1, object arg2) + public void WarnFormat(string format, object arg0, object arg1, + object arg2) { logger.WarnFormat(format, arg0, arg1, arg2); } diff --git a/util/MoreDom.cs b/util/MoreDom.cs index c9b09470..3a7a7239 100644 --- a/util/MoreDom.cs +++ b/util/MoreDom.cs @@ -10,7 +10,8 @@ public static XmlElement EL(this XmlDocument doc, string name) return EL(doc, name, null, null); } - public static XmlElement EL(this XmlDocument doc, string name, AttributeCollection attributes) + public static XmlElement EL(this XmlDocument doc, string name, + AttributeCollection attributes) { return EL(doc, name, attributes, null); } @@ -20,7 +21,8 @@ public static XmlElement EL(this XmlDocument doc, string name, string text) return EL(doc, name, null, text); } - public static XmlElement EL(this XmlDocument doc, string name, AttributeCollection attributes, string text) + public static XmlElement EL(this XmlDocument doc, string name, + AttributeCollection attributes, string text) { if (doc == null) { throw new ArgumentNullException("doc"); diff --git a/util/RepositoryLookupException.cs b/util/RepositoryLookupException.cs index f623480f..8ca08eb6 100644 --- a/util/RepositoryLookupException.cs +++ b/util/RepositoryLookupException.cs @@ -6,7 +6,8 @@ namespace NMaier.SimpleDlna.Utilities [Serializable] public sealed class RepositoryLookupException : ArgumentException { - private RepositoryLookupException(SerializationInfo info, StreamingContext context) + private RepositoryLookupException(SerializationInfo info, + StreamingContext context) : base(info, context) { } @@ -32,7 +33,8 @@ public string Key private set; } - public override void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, + StreamingContext context) { base.GetObjectData(info, context); } diff --git a/util/SafeNativeMethods.cs b/util/SafeNativeMethods.cs index 73dc14ea..b1ae3f88 100644 --- a/util/SafeNativeMethods.cs +++ b/util/SafeNativeMethods.cs @@ -9,6 +9,8 @@ internal static class SafeNativeMethods internal static extern int StrCmpLogicalW(string psz1, string psz2); [DllImport("iphlpapi.dll")] - public static extern UInt32 SendARP(UInt32 DestIP, UInt32 SrcIP, [Out] byte[] pMacAddr, ref UInt32 PhyAddrLen); + public static extern UInt32 SendARP( + UInt32 DestIP, UInt32 SrcIP, [Out] byte[] pMacAddr, + ref UInt32 PhyAddrLen); } } diff --git a/util/Sqlite.cs b/util/Sqlite.cs index aabd011e..b21fb611 100644 --- a/util/Sqlite.cs +++ b/util/Sqlite.cs @@ -55,7 +55,8 @@ private static IDbConnection GetDatabaseConnectionSDS(string cs) rv.SetChunkSize(GROW_SIZE); } catch (Exception ex) { - log4net.LogManager.GetLogger(typeof(Sqlite)).Error("Failed to sqlite control", ex); + log4net.LogManager.GetLogger(typeof(Sqlite)).Error( + "Failed to sqlite control", ex); } if (clearPool == null) { diff --git a/util/StreamPumpCallback.cs b/util/StreamPumpCallback.cs index 4c86c470..1ed416a7 100644 --- a/util/StreamPumpCallback.cs +++ b/util/StreamPumpCallback.cs @@ -1,4 +1,5 @@ namespace NMaier.SimpleDlna.Utilities { - public delegate void StreamPumpCallback(StreamPump pump, StreamPumpResult result); + public delegate void StreamPumpCallback( + StreamPump pump, StreamPumpResult result); } diff --git a/util/StringSortPart.cs b/util/StringSortPart.cs index b88eba73..b1dae762 100644 --- a/util/StringSortPart.cs +++ b/util/StringSortPart.cs @@ -2,7 +2,8 @@ namespace NMaier.SimpleDlna.Utilities { - internal sealed class StringSortPart : BaseSortPart, IComparable + internal sealed class StringSortPart + : BaseSortPart, IComparable { private readonly StringComparer comparer;