Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6648989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T00:43:16+00:00 2026-05-26T00:43:16+00:00

I’m not sure what is happening with this app. It worked fine then one

  • 0

I’m not sure what is happening with this app. It worked fine then one day it stopped working. I’ve tried to eliminate individual elements in the code but as soon as I added a few enums (see code below) it broke – so I removed them but this did not reverse the issue. Then I started from a brand new win service (using VS2010 and VS2008), adding class level vars and once again after adding enums the service would not start.

Here is the code and I was wondering if someone can help me out. I really appreciate it.

using _Mail;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Net.Mail;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.SharePoint;

namespace Uploader
{

public partial class _UploaderService : ServiceBase
{
    private static string smtpServer = ConfigurationManager.AppSettings["smtpServer"];
    private static string sendTo = ConfigurationManager.AppSettings["sendTo"];
    private static string sendFrom = ConfigurationManager.AppSettings["sendFrom"];
    private static string portalURL = ConfigurationManager.AppSettings["portalURL"];
    private static string imageListFolder = ConfigurationManager.AppSettings["imageListFolder"];
    private static string remFolder = ConfigurationManager.AppSettings["remoteFolder"];
    private static string sourceFileName = ConfigurationManager.AppSettings["sourceFileName"];
    private static string remoteDriveLetter = ConfigurationManager.AppSettings["remoteDriveLetter"];
    private static string remoteShareName = ConfigurationManager.AppSettings["remoteShareName"];
    private static string userName = ConfigurationManager.AppSettings["userName"];
    private static string userPwd = ConfigurationManager.AppSettings["userPwd"];
    private static string statusMessage;
    private static string[] files;

    private static SPWeb _Web = new SPSite(portalURL).OpenWeb();
    private static NETRESOURCE res = new NETRESOURCE();

    public enum ResourceScope
    {
        RESOURCE_CONNECTED = 1,
        RESOURCE_GLOBALNET,
        RESOURCE_REMEMBERED,
        RESOURCE_RECENT,
        RESOURCE_CONTEXT
    };
    public enum ResourceType
    {
        RESOURCETYPE_ANY,
        RESOURCETYPE_DISK,
        RESOURCETYPE_PRINT,
        RESOURCETYPE_RESERVED
    };
    public enum ResourceUsage
    {
        RESOURCEUSAGE_CONNECTABLE = 0x00000001,
        RESOURCEUSAGE_CONTAINER = 0x00000002,
        RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
        RESOURCEUSAGE_SIBLING = 0x00000008,
        RESOURCEUSAGE_ATTACHED = 0x00000010
    };
    public enum ResourceDisplayType
    {
        RESOURCEDISPLAYTYPE_GENERIC,
        RESOURCEDISPLAYTYPE_DOMAIN,
        RESOURCEDISPLAYTYPE_SERVER,
        RESOURCEDISPLAYTYPE_SHARE,
        RESOURCEDISPLAYTYPE_FILE,
        RESOURCEDISPLAYTYPE_GROUP,
        RESOURCEDISPLAYTYPE_NETWORK,
        RESOURCEDISPLAYTYPE_ROOT,
        RESOURCEDISPLAYTYPE_SHAREADMIN,
        RESOURCEDISPLAYTYPE_DIRECTORY,
        RESOURCEDISPLAYTYPE_TREE,
        RESOURCEDISPLAYTYPE_NDSCONTAINER
    };
    [StructLayout(LayoutKind.Sequential)]
    public struct NETRESOURCE
    {
        public ResourceScope dwScope;
        public ResourceType dwType;
        public ResourceDisplayType dwDisplayType;
        public ResourceUsage dwUsage;
        public string lpLocalName;
        public string lpRemoteName;
        public string lpComment;
        public string lpProvider;
    };

    [DllImport("mpr.dll")]
    public static extern int WNetAddConnection2(ref NETRESOURCE
    netResource, string password, string username, int flags);

    public cisf_UploaderService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {            
        try
        {
            FileSystemWatcher fsWatcher = new FileSystemWatcher();
            fsWatcher.Created += new FileSystemEventHandler(fsw_Created);

            DisconnectDrive(remoteDriveLetter);
            res.dwType = ResourceType.RESOURCETYPE_DISK;
            res.lpLocalName = remoteDriveLetter;
            res.lpRemoteName = remoteShareName;
            int stat = WNetAddConnection2(ref res, null, null, 0);
            statusMessage += "Map Network Drive status - " + stat + ".";

            //MapDrive();

            CleanUp();
            fsWatcher.Path = remFolder;
            fsWatcher.Filter = sourceFileName;
            fsWatcher.EnableRaisingEvents = true;
        }
        catch (Exception ex1)
        {
            WriteException(ex1,"Ex1");
        }
    }

    protected override void OnStop()
    {
    }

    static void fsw_Created(object sender, FileSystemEventArgs e)
    {
        statusMessage += "\nNew PowerPoint file detected in directory.";

        ConvetToJpegs();
        AcquireFiles();
        CleanUp();
        DisconnectDrive(remoteDriveLetter);

        statusMessage += "\nOperation sucessfuly completed.";

        EventLog.WriteEntry("Conversion Service Status", statusMessage, EventLogEntryType.Information);

    }

    protected static void ConvetToJpegs()
    {
        Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
        Presentation pptPresentation = null;

        try
        {
            pptPresentation = app.Presentations.Open(remFolder + sourceFileName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
            pptPresentation.SaveAs(remFolder + ".", PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoFalse);

        }
        catch (Exception ex2)
        {
            WriteException(ex2, "Ex2");
        }
        finally
        {
            pptPresentation.Close();
            statusMessage += "\nFile conversion completed.";
        }
    }

    protected static void AcquireFiles()
    {
        files = null;

        try
        {
            files = Directory.GetFiles(remFolder, "*.jpg");
        }
        catch (Exception ex3)
        {
            WriteException(ex3, "Ex3");
        }
        finally
        {
            statusMessage += "\nFiles acquired.";
            if (files.Length > 0)
            {
                DeleteOldSlides();
            }
        }
    }

    protected static void DeleteOldSlides()
    {
        SPList imagesLibrary = _Web.Lists[imageListFolder];
        _Web.AllowUnsafeUpdates = true;
        try
        {
            while (imagesLibrary.Items.Count > 1)
            {
                imagesLibrary.Items[imagesLibrary.Items.Count - 1].File.Delete();
            }
        }
        catch (Exception ex4)
        {
            WriteException(ex4, "Ex4");
        }
        finally
        {
            statusMessage += "\nOld slides deleted.";
            UploadToSharePoint();
        }
    }

    protected static void UploadToSharePoint()
    {
        _Web.AllowUnsafeUpdates = true;

        FileStream fs = null;
        string fileName = string.Empty;

        try
        {
            foreach (string file in files)
            {

                fileName = file.Split(@"\".ToCharArray())[1].ToLower();
                fs = File.Open(file, FileMode.Open);
                _Web.Files.Add(imageListFolder + "/" + fileName, fs, true);
                fileName = string.Empty;
                fs.Close();
            }
        }
        catch (Exception ex5)
        {
            WriteException(ex5, fileName);
        }
        finally
        {
            statusMessage += "\nFiles uploaded to SharePoint.";
            _Web.AllowUnsafeUpdates = false;
        }
    }

    protected static void CleanUp()
    {
        string[] path = Directory.GetFiles(remFolder, "*.jpg");
        string[] path1 = Directory.GetFiles(remFolder, "*.pptx");

        try
        {
            foreach (string tempfiles in path1)
            {
                if (path != null)
                {
                    File.Delete(tempfiles);
                }
            }
            foreach (string tempfiles in path)
            {
                if (path != null)
                {
                    File.Delete(tempfiles);
                }
            }
        }
        catch (Exception ex6)
        {
            WriteException(ex6, "Ex6");
        }
        finally
        {
            statusMessage += "\nFiles deleted from temporary directory " + remoteShareName ;
        }
    }

    //public static bool MapDrive() 
    //{ 
    //    bool ReturnValue = false;
    //    if (System.IO.Directory.Exists(remoteDriveLetter + ":\\")) 
    //    {
    //        DisconnectDrive(remoteDriveLetter); 
    //    } 
    //    System.Diagnostics.Process p = new System.Diagnostics.Process(); 
    //    p.StartInfo.UseShellExecute = false; 
    //    p.StartInfo.CreateNoWindow = true; 
    //    p.StartInfo.RedirectStandardError = true; 
    //    p.StartInfo.RedirectStandardOutput = true; 
    //    p.StartInfo.FileName = "net.exe";
    //    p.StartInfo.Arguments = " use " + remoteDriveLetter + ": " + remoteShareName + " " + userPwd + " /user:" + userName; 
    //    p.Start(); 
    //    p.WaitForExit(); 
    //    string ErrorMessage = p.StandardError.ReadToEnd(); 
    //    string OuputMessage = p.StandardOutput.ReadToEnd(); 
    //    if (ErrorMessage.Length > 0) 
    //    { 
    //        throw new Exception("Error:" + ErrorMessage); 
    //    } else { ReturnValue = true; } return ReturnValue; }

    protected static void DisconnectDrive(string DriveLetter)
    {
        Process p = new Process();

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardOutput = true;

        try
        {
            p.StartInfo.FileName = "net.exe";
            p.StartInfo.Arguments = " use " + "Z" + ": /DELETE";
            p.Start();
        }
        catch (Exception ex7)
        {
            WriteException(ex7, "Ex7");
        }
        finally
        {
            p.WaitForExit();
        }
    }

    public static void WriteException(Exception ex, string source)
    {
        string err = "Uploader Error" +
                     "\n\nError Message from method " + source + ": " + ex.Message.ToString() +
                     "\n\nStack Trace: " + ex.StackTrace.ToString() + "\n";
        EventLog.WriteEntry("Conversion Service", err, EventLogEntryType.Warning);

        _Mail sendEmail = new _Mail();
        sendEmail.SMTPServer = smtpServer;
        sendEmail.MailTo = sendTo;
        sendEmail.MailFrom = sendFrom;
        sendEmail.MailSubject = "Uploader Error";
        sendEmail.MailBody = err;
        sendEmail.Send();
    }        
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T00:43:17+00:00Added an answer on May 26, 2026 at 12:43 am

    Type Initializer error means that the type couldn’t be created. This happens before the call to the constructor when the CLR initialized all the static fields. Since your initialization does something more than call a private constructor or set a literal value you’re opening yourself up to difficult to debug problems

    In this case its likely do to a problem with one of your AppSettings keys

    e.g.

    private static string smtpServer = ConfigurationManager.AppSettings["smtpServer"];
    private static string sendTo = ConfigurationManager.AppSettings["sendTo"];
    ...
    

    This looks suspicious as well.

    private static SPWeb _Web = new SPSite(portalURL).OpenWeb();
    private static NETRESOURCE res = new NETRESOURCE();
    

    Instead do what you need to do in the constructor. You might also want to add a helper method so that way you can raise a better exception (or instead you could as Marc Gravel comments just look at the Inner Exception)

    For example

     private string safeGetAppSetting(string key)
     {
    
       try 
       { 
             return ConfigurationManager.AppSettings["smtpServer"];
       }
       catch(ConfigurationErrorsException)
       {
            throw new InvalidOperationException(string.Format("key {0} is missing or misconfigured", key);
       }
     }
    
    
    
    
    public cisf_UploaderService()
    {
        InitializeComponent();
        smtpServer = safeGetAppSetting("smtpServer");
    }
    

    Update In hindsight adding Debugger.Launch() to Program.Main() as kzen mentioned may be worthwhile. If its not a local dev machine that’s the issue adding some additional logging at the root may help as well.

            try
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new SampleWindowsService() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            catch (Exception ex)
            {
                string SourceName = "YourService.ExceptionLog";
                if (!EventLog.SourceExists(SourceName))
                {
                    EventLog.CreateEventSource(SourceName, "Application");
                }
    
                EventLog eventLog = new EventLog();
                eventLog.Source = SourceName;
                string message = "";
                if (ex.InnerException  != null)
                    string message = string.Format("Exception: {0} \n\nStack: {1} \n\nInnerException: {2}", ex.Message, ex.StackTrace, ex.InnerException.Message);
                else
                    string message = string.Format("Exception: {0} \n\nStack: {1}", ex.Message, ex.StackTrace);
                eventLog.WriteEntry(message, EventLogEntryType.Error);
            }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I am reading a book about Javascript and jQuery and using one of the
I have this code to decode numeric html entities to the UTF8 equivalent character.
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.