Example #1
0
 private void ExecuteScript(
     DialPlanExecutingScript executingScript,
     DialPlanContext dialPlanContext,
     DialPlanScriptFacade planFacade,
     string script)
 {
     try
     {
         Thread.CurrentThread.Name = "dialplanscript-" + executingScript.ScriptNumber;
         if (m_impersonationUsername != null && m_impersonationPassword != null)
         {
             WrapperImpersonationContext impersonationConext = new WrapperImpersonationContext(null, m_impersonationUsername, m_impersonationPassword);
             impersonationConext.Enter();
         }
         //logger.Debug(Thread.CurrentThread.Name + " identity=" + WindowsIdentity.GetCurrent().Name + ".");
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dial plan execution starting on thread " + Thread.CurrentThread.Name + " for " + dialPlanContext.Owner + ".", null));
         executingScript.DialPlanScriptEngine.Execute(script, executingScript.DialPlanScriptScope);
         //FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dial plan execution finished after full script run on thread " + Thread.CurrentThread.Name + " for " + dialPlanContext.Owner + ".", null));
     }
     catch (ApplicationException appExcp)
     {
         if (appExcp.Message != "Script was halted by external intervention.")
         {
             logger.Error("ApplicationException ExecuteScript. " + appExcp.Message);
             FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was an exception executing your dial plan script: " + appExcp.Message, executingScript.Owner));
             FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "ApplicationException on user " + executingScript.Owner + "'s dial plan script. " + appExcp.Message, null));
             executingScript.ExecutionError = appExcp.Message;
         }
         else
         {
             FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dial plan execution finished after being halted due to execution interrupt on thread " + Thread.CurrentThread.Name + " for " + dialPlanContext.Owner + ".", null));
         }
     }
     //catch (System.Scripting.SyntaxErrorException)
     catch (SyntaxErrorException syntaxExcp)
     {
         logger.Warn("SyntaxErrorException. Owner=" + dialPlanContext.Owner + ", DialPlanName=" + dialPlanContext.SIPDialPlan.DialPlanName + ", Line=" + syntaxExcp.Line + ".");
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was a syntax error in your dial plan on line " + syntaxExcp.Line + ", please check.", executingScript.Owner));
         executingScript.ExecutionError = "Dial plan syntax error";
     }
     catch (MissingMethodException missingExcp)
     {
         logger.Warn("MissingMethodException. " + missingExcp.Message);
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was a missing method exception in your dial plan: " + missingExcp.Message + ".", executingScript.Owner));
         executingScript.ExecutionError = "Dial plan missing method";
     }
     catch (ThreadAbortException) { }
     catch (Exception excp)
     {
         logger.Error("Exception ExecuteScript (" + excp.GetType() + "). " + excp.Message);
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was an exception executing your dial plan script: " + excp.Message, executingScript.Owner));
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Exception on user " + executingScript.Owner + "'s dial plan script (" + excp.GetType() + "). " + excp.Message, null));
         executingScript.ExecutionError = "Dial plan exception";
     }
     finally
     {
         executingScript.StopExecution();
     }
 }
        public static void Main(string[] args)
        {
            try {
                //Based on the code from http://michiel.vanotegem.nl/2006/07/windowsimpersonationcontext-made-easy/

                Console.WriteLine("Current user: "******"GARNET", "TestAdmin1", "password123");
                context.Enter();
                // Execute code under other uses context
                Console.WriteLine("Current user: "******"sc \\GARNET stop W3SVC"

                //Also, make sure the user on the remote server has access for
                //services granted as described here: http://stackoverflow.com/a/5084563/201648
                //Otherwise you may see an error along the lines of:
                //Cannot open W3SVC service on computer '<SERVER>'. ---> System.ComponentModel.Win32Exception: Access is denied
                //For my configuration I had to run the command:
                // SUBINACL /SERVICE \\GARNET\W3SVC /GRANT=GARNET\TestAdmin=TO
                //It's entirely possible that running this command will allow your existing code to work without using impersonation.

                //You may need to install SUBINACL https://www.microsoft.com/en-au/download/details.aspx?id=23510
                //By default SUBINACL will install to C:\Program Files (x86)\Windows Resource Kits\Tools
                //so CD to that directory and then run the SUBINACL command above.

                //Also worked with the IP address of GARNET (which was the machine name).
                var sc = new ServiceController("W3SVC", "GARNET");
                sc.Start();

                sc.WaitForStatus(ServiceControllerStatus.Running);
                sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped);

                //END - code to execute.
                context.Leave();
                Console.WriteLine("Your code ran successfully. Current user: "******"An exception occured - details as follows: {0}", ex.Message);
                Console.WriteLine("The full stack trace is: {0}", ex);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
Example #3
0
        public void ShouldCreateLocalGroup()
        {
            var path = "WinNT://" + Environment.MachineName + ",computer";

            const string groupName = "Test";

            var imptCtxt = new WrapperImpersonationContext("MSHARONOV", "sdl.core", "P@ssw0rd");

            imptCtxt.Enter();

            var result = _target.CreateGroup(path, groupName).Sid;

            imptCtxt.Leave();

            result.Should().NotBeNullOrEmpty();
        }
        public void ShouldResolveImpersonated()
        {
            var currentUserName = WindowsIdentity.GetCurrent().Name;

            var imptCtxt = new WrapperImpersonationContext("MSHARONOV", "sdl.core", "P@ssw0rd");

            imptCtxt.Enter();

            var impersonatedUserName = WindowsIdentity.GetCurrent().Name;

            impersonatedUserName.Should().NotStartWith(currentUserName);

            var result = _target.Get(impersonatedUserName);

            imptCtxt.Leave();

            result.Should().NotBeNull();
        }
        public void ShouldResolveDomainUser()
        {
            var currentUserName = WindowsIdentity.GetCurrent().Name;

            var imptCtxt = new WrapperImpersonationContext("MSHARONOV", "sdl.core", "P@ssw0rd");

            imptCtxt.Enter();

            System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            var impersonatedUserName = WindowsIdentity.GetCurrent().Name;

            impersonatedUserName.Should().NotStartWith(currentUserName);

            var result = _target.Get(currentUserName);

            imptCtxt.Leave();

            result.Should().NotBeNull();
        }
        private static void ImpersonateCurrentProcess()
        {
            Console.WriteLine("WindowsIdentity.GetCurrent().Name: " + WindowsIdentity.GetCurrent().Name);

            Console.WriteLine();
            var context = new WrapperImpersonationContext("Nikolay-PC", UserName, Password);

            context.Enter();
            Console.WriteLine("... context.Enter(); ...");

            // Execute code under other uses context
            Console.WriteLine("WindowsIdentity.GetCurrent().Name: " + WindowsIdentity.GetCurrent().Name);
            Console.WriteLine("Environment.UserName: "******"SandboxExecutorProofOfConcept.exe.config");

            Console.WriteLine();
            context.Leave();
            Console.WriteLine("... context.Leave(); ...");
            Console.WriteLine("WindowsIdentity.GetCurrent().Name: " + WindowsIdentity.GetCurrent().Name);
        }
        public void EnterContextUnitTest()
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);

            Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + ".");
            using (StreamReader sr = new StreamReader(@"c:\temp\impersonationtest.txt"))
            {
                Console.WriteLine(sr.ReadToEnd());
            }

            WrapperImpersonationContext context = new WrapperImpersonationContext(null, "sipsorcery-appsvr", "password");

            context.Enter();
            Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + ".");

            using (StreamReader sr = new StreamReader(@"c:\temp\impersonationtest.txt"))
            {
                Console.WriteLine(sr.ReadToEnd());
            }

            context.Leave();
            Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + ".");
        }
        public void EnterContextUnitTest()
        {
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);

            Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + ".");
            using (StreamReader sr = new StreamReader(@"c:\temp\impersonationtest.txt"))
            {
                Console.WriteLine(sr.ReadToEnd());
            }

            WrapperImpersonationContext context = new WrapperImpersonationContext(null, "sipsorcery-appsvr", "password");
            context.Enter();
            Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + ".");

            using (StreamReader sr = new StreamReader(@"c:\temp\impersonationtest.txt"))
            {
                Console.WriteLine(sr.ReadToEnd());
            }

            context.Leave();
            Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + ".");
        }
Example #9
0
        public static string PutQueue(AVOAIALifeEntities entity, string RequestText, string strCorrelId, string callingFunc, string responseFunc)
        {
            WrapperImpersonationContext context = new WrapperImpersonationContext();

            context.Enter();
            string         MessageText = string.Empty;
            MQQueueManager mqQMgr;
            MQQueue        requestQueue;
            MQMessage      requestMessage;

            QueueModel.MQRCText mqrcText = new QueueModel.MQRCText();
            Hashtable           props    = new Hashtable();
            var queueInfo    = entity.tblSubFunctionMappings.Where(a => a.IntegrationFunctionName == callingFunc).FirstOrDefault();
            var resQueueInfo = entity.tblSubFunctionMappings.Where(a => a.IntegrationFunctionName == responseFunc).FirstOrDefault();

            string MQChannel      = queueInfo.MQChannel;
            string RequestQueue   = queueInfo.Queue;
            string ResponseQueue  = resQueueInfo.Queue;
            string strRequestText = RequestText;

            //Step 1. Connect Queue Manager Object on the remote host.
            try
            {
                props.Add(MQC.HOST_NAME_PROPERTY, _mqHostServer);
                props.Add(MQC.CHANNEL_PROPERTY, MQChannel);
                props.Add(MQC.PORT_PROPERTY, _portNumber); // port number
                props.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
                props.Add(MQC.USER_ID_PROPERTY, _userName);
                props.Add(MQC.PASSWORD_PROPERTY, _password);
                mqQMgr = new MQQueueManager(_mqManager, props);
            }
            catch (IBM.WMQAX.MQException mqe)
            {
                string strError = mqrcText.getMQRCText(mqe.Reason);
                MessageText = "Error trying to create Queue Manager Object. Error: " + mqe.Message + ", Details: " + strError;
                return(MessageText);
            }
            catch (Exception ex)
            {
                MessageText = "Error trying to create Queue Manager Object. Error: " + ex.Message;
                return(MessageText);
            }

            //Step 2. Open Request Queue for writing our request
            try
            {
                requestQueue = mqQMgr.AccessQueue(RequestQueue, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING);          // but not if MQM stopping
            }
            catch (MQException mqe)
            {
                string strError = mqrcText.getMQRCText(mqe.Reason);
                MessageText = "Error trying to open Request Queue for writing. Error: " + mqe.Message + ", Details: " + strError;
                if (mqQMgr.IsConnected)
                {
                    mqQMgr.Disconnect();
                }
                return(MessageText);
            }

            //Step 4. PUT Request Message in Request Queue. Note the options needed to be set.
            //Note that once PUT is successful, you can close the Request Queue. Note that you are
            //asking whoever receives this request to copy the MSG ID to CORREL ID so that
            //you can later "match" the response you get with the request you sent.

            requestMessage = new MQMessage();
            try
            {
                requestMessage.CharacterSet = 437;
                requestMessage.WriteString(RequestText);
                requestMessage.Format           = MQC.MQFMT_STRING;
                requestMessage.MessageType      = MQC.MQMT_REQUEST;
                requestMessage.Report           = MQC.MQRO_COPY_MSG_ID_TO_CORREL_ID;
                requestMessage.ReplyToQueueName = ResponseQueue;

                requestMessage.ReplyToQueueManagerName = _mqManager;

                //Damo: Fix for multi thread Q mode. Assign the Correlation and MSG ID to the same reference key for the retrival.
                //requestMessage.CorrelationId = System.Text.Encoding.UTF8.GetBytes(strCorrelId);
                //requestMessage.MessageId = requestMessage.CorrelationId;

                requestMessage.CorrelationId = System.Text.Encoding.UTF8.GetBytes(strCorrelId);
                requestMessage.MessageId     = requestMessage.CorrelationId;

                requestQueue.Put(requestMessage);
                if (requestQueue.OpenStatus)
                {
                    requestQueue.Close();
                }
            }


            catch (MQException mqe)
            {
                string strError = mqrcText.getMQRCText(mqe.Reason);
                MessageText = "Error trying to PUT Message to Request Queue. Error: " + mqe.Message + ", Details: " + strError;

                return(MessageText);
            }
            catch (Exception)
            {
            }

            context.Leave();
            return(MessageText);
        }
Example #10
0
        public static string GetQueue(AVOAIALifeEntities entity, byte[] CorId, string responseFunc)
        {
            WrapperImpersonationContext context = new WrapperImpersonationContext();

            context.Enter();
            MQQueueManager mqQMgr;
            MQQueue        requestQueue;

            QueueModel.MQRCText mqrcText = new QueueModel.MQRCText();
            MQMessage           requestMessage;
            var    respQueueInfo       = entity.tblSubFunctionMappings.Where(a => a.IntegrationFunctionName == responseFunc).FirstOrDefault();
            string Message             = string.Empty;
            string strRequestQueueName = respQueueInfo.Queue;

            Hashtable props     = new Hashtable();
            string    MQChannel = respQueueInfo.MQChannel;

            //Step 1. Create Queue Manager Object. This will also CONNECT the Queue Manager
            try
            {
                props.Add(MQC.HOST_NAME_PROPERTY, _mqHostServer);
                props.Add(MQC.CHANNEL_PROPERTY, MQChannel);
                props.Add(MQC.PORT_PROPERTY, _portNumber); // port number
                props.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
                props.Add(MQC.USER_ID_PROPERTY, _userName);
                props.Add(MQC.PASSWORD_PROPERTY, _password);
                mqQMgr = new MQQueueManager(_mqManager, props);
            }
            catch (MQException mqe)
            {
                string strError = mqrcText.getMQRCText(mqe.Reason);
                Message = "Error trying to create Queue Manager Object. Error: " + mqe.Message + ", Details: " + strError;
                context.Leave();
                return(Message);
            }

            //Step 2. Open Request Queue for reading/ getting the request
            try
            {
                requestQueue = mqQMgr.AccessQueue(strRequestQueueName,
                                                  MQC.MQOO_INPUT_AS_Q_DEF        // open queue for input
                                                  + MQC.MQOO_FAIL_IF_QUIESCING); // but not if MQM stopping
            }
            catch (MQException mqe)
            {
                string strError = mqrcText.getMQRCText(mqe.Reason);
                Message = "Error trying to open Request Queue for reading. Error: " + mqe.Message + ", Details: " + strError;
                if (mqQMgr.IsConnected)
                {
                    mqQMgr.Disconnect();
                }
                context.Leave();
                return(Message);
            }

            //Step 3. GET the request message. Note that you decide how long you wait for a message
            //to show up. As you are the server now, you do no matching - you must serve to all
            //clients. Guess why this method needed a separate thread? Because the GET() can hang the
            //thread if it is long enough. Note that request queue is NOT closed after GET is over.
            try
            {
                requestMessage = new MQMessage();
                MQGetMessageOptions gmo = new MQGetMessageOptions();
                gmo.Options      = MQC.MQGMO_WAIT;             // must be specified if you use wait interval
                gmo.WaitInterval = MQC.MQWI_UNLIMITED;

                gmo.WaitInterval = Convert.ToInt32(ConfigurationManager.AppSettings["WaitTime2"]);

                // Copy correlationID of the message you want to receive
                requestMessage.MessageId = CorId;

                requestQueue.Get(requestMessage, gmo);
                Message = requestMessage.ToString();
                Message = requestMessage.ReadString(requestMessage.MessageLength);
                return(Message);
            }
            catch (MQException mqe)
            {
                string strError = mqrcText.getMQRCText(mqe.Reason);
                Message = "Error trying to GET message from Request Queue. Error: " + mqe.Message + ", Details: " + strError;
                if (requestQueue.OpenStatus)
                {
                    requestQueue.Close();
                }
                if (mqQMgr.IsConnected)
                {
                    mqQMgr.Disconnect();
                }
                context.Leave();
                return(Message);
            }
        }
Example #11
0
 private void ExecuteScript(
     DialPlanExecutingScript executingScript,
     DialPlanContext dialPlanContext,
     DialPlanScriptFacade planFacade,
     string script)
 {
     try
     {
         Thread.CurrentThread.Name = "dialplanscript-" + executingScript.ScriptNumber;
         if (m_impersonationUsername != null && m_impersonationPassword != null)
         {
             WrapperImpersonationContext impersonationConext = new WrapperImpersonationContext(null, m_impersonationUsername, m_impersonationPassword);
             impersonationConext.Enter();
         }
         //logger.Debug(Thread.CurrentThread.Name + " identity=" + WindowsIdentity.GetCurrent().Name + ".");
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dial plan execution starting on thread " + Thread.CurrentThread.Name + " for " + dialPlanContext.Owner + ".", null));
         executingScript.DialPlanScriptEngine.Execute(script, executingScript.DialPlanScriptScope);
         //FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dial plan execution finished after full script run on thread " + Thread.CurrentThread.Name + " for " + dialPlanContext.Owner + ".", null));
     }
     catch (ApplicationException appExcp)
     {
         if (appExcp.Message != "Script was halted by external intervention.")
         {
             logger.Error("ApplicationException ExecuteScript. " + appExcp.Message);
             FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was an exception executing your dial plan script: " + appExcp.Message, executingScript.Owner));
             FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "ApplicationException on user " + executingScript.Owner + "'s dial plan script. " + appExcp.Message, null));
             executingScript.ExecutionError = appExcp.Message;
         }
         else
         {
             FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dial plan execution finished after being halted due to execution interrupt on thread " + Thread.CurrentThread.Name + " for " + dialPlanContext.Owner + ".", null));
         }
     }
     //catch (System.Scripting.SyntaxErrorException)
     catch (SyntaxErrorException syntaxExcp)
     {
         logger.Warn("SyntaxErrorException. Owner=" + dialPlanContext.Owner + ", DialPlanName=" + dialPlanContext.SIPDialPlan.DialPlanName + ", Line=" + syntaxExcp.Line + ".");
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was a syntax error in your dial plan on line " + syntaxExcp.Line + ", please check.", executingScript.Owner));
         executingScript.ExecutionError = "Dial plan syntax error";
     }
     catch (MissingMethodException missingExcp)
     {
         logger.Warn("MissingMethodException. " + missingExcp.Message);
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was a missing method exception in your dial plan: " + missingExcp.Message + ".", executingScript.Owner));
         executingScript.ExecutionError = "Dial plan missing method";
     }
     catch (ThreadAbortException) { }
     catch (Exception excp)
     {
         logger.Error("Exception ExecuteScript (" + excp.GetType() + "). " + excp.Message);
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "There was an exception executing your dial plan script: " + excp.Message, executingScript.Owner));
         FireProxyLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Exception on user " + executingScript.Owner + "'s dial plan script (" + excp.GetType() + "). " + excp.Message, null));
         executingScript.ExecutionError = "Dial plan exception";
     }
     finally
     {
         executingScript.StopExecution();
     }
 }
Example #12
0
        public ActionResult Dashboard(Models.ResourceModel resource)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("/client");
            }

            // extract img srcs from the thingy
            //string pattern = @"<img.*?src=""(?<url>.*?)"".*?>";
            string pattern = @"<img.+?src=[\""'](.+?)[\""'].*?>";
            Regex  r       = new Regex(pattern);

            string domain   = "GISPLANNING";
            string username = "******";
            string password = "******";
            WrapperImpersonationContext impContext = new WrapperImpersonationContext(domain, username, password);

            impContext.Enter();
            // extract image tags
            foreach (Match match in r.Matches(resource.ResourceHtml))
            {
                // get the src data
                string base64ImageString = match.Groups[1].Value;

                var    isJpeg        = false;
                var    isPng         = false;
                var    isTiff        = false;
                var    isGif         = false;
                string replaceString = string.Empty;

                // check to see which format it is...jpeg,png,tiff,gif
                if (base64ImageString.Contains("data:image/jpeg;base64,"))
                {
                    isJpeg        = true;
                    replaceString = "data:image/jpeg;base64,";
                }
                if (base64ImageString.Contains("data:image/png;base64,"))
                {
                    isPng         = true;
                    replaceString = "data:image/png;base64,";
                }
                if (base64ImageString.Contains("data:image/tiff;base64,"))
                {
                    isTiff        = true;
                    replaceString = "data:image/tiff;base64,";
                }
                if (base64ImageString.Contains("data:image/gif;base64,"))
                {
                    isGif         = true;
                    replaceString = "data:image/gif;base64,";
                }

                if (!string.IsNullOrEmpty(replaceString))
                {
                    // remove the data:image/png;base64, from it
                    base64ImageString = base64ImageString.Replace(replaceString, "");

                    // save the img to disk
                    Bitmap bmpFromString = null;
                    byte[] byteBuffer    = Convert.FromBase64String(base64ImageString);
                    //byte[] byteBuffer = Serializer.FromBase64(base64ImageString);
                    var    myUniqueFileName = string.Format(@"{0}.jpg", Guid.NewGuid());
                    string imageServerPath  = "http://images.lbi.sizeup.com";
                    string imageFilePath    = "\\\\images-lbi-www01.gisplanning.net\\d$\\images\\";
                    string path             = string.Empty;
                    using (MemoryStream memoryStream = new MemoryStream(byteBuffer))
                    {
                        memoryStream.Position = 0;

                        bmpFromString = (Bitmap)Bitmap.FromStream(memoryStream);

                        while (System.IO.File.Exists(myUniqueFileName))
                        {
                            myUniqueFileName = string.Format(@"{0}.jpg", Guid.NewGuid());
                        }


                        var context = System.Web.HttpContext.Current;

                        path = string.Format(@"{0}/{1}", imageServerPath, myUniqueFileName);

                        //System.IO.FileStream fs
                        //    = new System.IO.FileStream(path, System.IO.FileMode.Create
                        //    , System.IO.FileAccess.ReadWrite);

                        string filePath = string.Format(@"{0}{1}", imageFilePath, myUniqueFileName);
                        if (isJpeg == true)
                        {
                            bmpFromString.Save(filePath, ImageFormat.Jpeg);
                        }
                        if (isPng == true)
                        {
                            bmpFromString.Save(filePath, ImageFormat.Png);
                        }
                        if (isTiff == true)
                        {
                            bmpFromString.Save(filePath, ImageFormat.Tiff);
                        }
                        if (isGif == true)
                        {
                            bmpFromString.Save(filePath, ImageFormat.Gif);
                        }


                        //byte[] matriz = memoryStream.ToArray();
                        //fs.Write(matriz, 0, matriz.Length);

                        memoryStream.Close();
                        //fs.Close();
                    }
                    byteBuffer = null;


                    // replace base64 in html with new path
                    resource.ResourceHtml = resource.ResourceHtml.Replace(string.Format("{0}{1}", replaceString, base64ImageString), path);
                }
            }
            impContext.Leave();

            if (resource.SaveHtml == true)
            {
                Guid g_ClientID;
                Guid.TryParse(resource.ClientId, out g_ClientID);

                if (resource.ClientId != "")
                {
                    using (var context = ContextFactory.SizeUpContext)
                    {
                        var result = context.ClientResourceStrings.Where(x => x.ClientID == g_ClientID).FirstOrDefault();
                        if (result != null)
                        {
                            switch (resource.Section)
                            {
                            case "revenue":
                                result.DashboardRevenue = resource.ResourceHtml;
                                break;

                            case "salary":
                                result.DashboardSalary = resource.ResourceHtml;
                                break;

                            case "employees":
                                result.DashboardAverageEmployees = resource.ResourceHtml;
                                break;

                            case "costeffectiveness":
                                result.DashboardCostEffectiveness = resource.ResourceHtml;
                                break;

                            case "turnover":
                                result.DashboardTurnover = resource.ResourceHtml;
                                break;

                            case "healthcare":
                                result.DashboardHealthcare = resource.ResourceHtml;
                                break;

                            case "workerscomp":
                                result.DashboardWorkersComp = resource.ResourceHtml;
                                break;

                            default:
                                result.DashboardRevenue = resource.ResourceHtml;
                                break;
                            }

                            context.SaveChanges();
                        }
                    }
                }
            }

            // save all the resource to the database
            return(Content(resource.ResourceHtml));
            //return View();
        }