Trikks

Real Kung Fu

Cannot change Language when UseCurrentUICulture is on

Posted by trikks on January 17, 2012

This error occurs since you forgot to set the UseCurrentUICulture to false when instantiating the MetaDataContext object

The error message looks something like this
MetaDataPlusException was unhandled
Cannot change Language when UseCurrentUICulture is on

To solve this you simple need to set the UseCurrentUICulture to false when instantiating your MetaDataContext object, in example

MetaDataContext metaDataContext = new MetaDataContext(connectionString)
{
    UseCurrentUICulture = false,
    Language = Capo.EPiServer.Constants.ProductCatalogConstants.DefaultLanguage
};

Cheers!

Posted in EpiServer Commerce | Leave a Comment »

EPiServer Commerce (Mediachase) Unable to cast object of type ‘System.DBNull’ to type ‘System.String’. after creating a new catalog

Posted by trikks on December 22, 2011

This means you (or someone) where sloppy when creating a new catalog. the error may vary but check the InvalidCastException in the stacktrace for hints.

In this scenario the catalog didn’t have a default language set, so removing it and adding that property when creating it solved the issue.

Method to create new EPiServer Commerce Catalog

Here is my method to create working catalog

public static bool Create(string catalogName)
{
    try
    {
        CatalogDto catalogDto1 = CatalogContext.Current.GetCatalogDto(-1, new CatalogResponseGroup(CatalogResponseGroup.ResponseGroup.CatalogInfo));
        CatalogDto.CatalogRow newCatalogRow = catalogDto1.Catalog.NewCatalogRow();
        newCatalogRow.Name = catalogName;
        newCatalogRow.StartDate = DateTime.Now;
        newCatalogRow.EndDate = DateTime.Now.AddYears(20);
        newCatalogRow.IsActive = true;
        newCatalogRow.SortOrder = 0;
        newCatalogRow.ApplicationId = AppContext.Current.ApplicationId;
        newCatalogRow.Created = DateTime.Now;
        newCatalogRow.Modified = DateTime.Now;
        newCatalogRow.IsPrimary = false;
        newCatalogRow.DefaultLanguage = "sv-SE";

        // save
        catalogDto1.Catalog.AddCatalogRow(newCatalogRow);
        CatalogContext.Current.SaveCatalog(catalogDto1);
        return true;
    }
    catch
    {
        return false;
    }
}

Method to delete an EPiServer Commerce Catalog

public static void Delete(string catalogName)
{
    CatalogDto catalogs = CatalogContext.Current.GetCatalogDto();
    CatalogDto.CatalogRow catalog = catalogs.Catalog.FirstOrDefault(x => x.Name.ToLower().Equals(catalogName.ToLower()));
    CatalogContext.Current.DeleteCatalog(catalog.CatalogId);
}

The full error

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type ‘System.DBNull’ to type ‘System.String’.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

 

Stack Trace:

[InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.]
   Mediachase.Commerce.Catalog.Dto.CatalogRow.get_DefaultLanguage() +80

[StrongTypingException: The value for column 'DefaultLanguage' in table 'Catalog' is DBNull.]
   Mediachase.Commerce.Catalog.Dto.CatalogRow.get_DefaultLanguage() +193
   EPiServer.Business.Commerce.HttpModules.<>c__DisplayClass1b.<GetAllCommerceLanguages>b__18(CatalogRow catalogRow) +29
   System.Collections.Generic.List`1.ForEach(Action`1 action) +76
   EPiServer.Business.Commerce.HttpModules.ProductUrlRewriteModule.GetAllCommerceLanguages() +337
   EPiServer.Business.Commerce.HttpModules.ProductUrlRewriteModule.GetProductByLink(UrlBuilder url) +729
   EPiServer.Business.Commerce.HttpModules.ProductUrlRewriteModule.UrlRewriteProvider_ConvertingToInternal(Object sender, UrlRewriteEventArgs e) +147
   EPiServer.Web.UrlRewriteProvider.OnConvertingToInternal(UrlRewriteEventArgs e) +26
   EPiServer.Web.FriendlyUrlRewriteProvider.TryConvertToInternal(UrlBuilder url, LanguageApiMode apiMode, CultureInfo& preferredCulture, Object& internalObject) +173
   EPiServer.Web.FriendlyUrlRewriteProvider.TryConvertToInternal(UrlBuilder url, CultureInfo& preferredCulture, Object& internalObject) +23
   EPiServer.Web.UrlRewriteModule.HttpUrlRewriteToInternal(UrlBuilder url) +483
   EPiServer.Web.UrlRewriteModuleBase.BeginRequestEventHandler(Object sender, EventArgs e) +205
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171

 


Version Information: Microsoft .NET Framework Version:2.0.50727.5448; ASP.NET Version:2.0.50727.5420

 

Posted in EpiServer Commerce, Mediachase | Leave a Comment »

Getting the previous and next record from list using linq

Posted by trikks on December 1, 2011

Generic lists, you just gotta love them, especially if using linq!

Well to the point. Lets say you got a list with Guid’s of which you know one and based on that knowledge want to get either the one before or after.

Guid a = new Guid("709DBFA9-88B3-4518-A32F-C21B6AAE2917");
Guid b = new Guid("B9956FC6-FD9B-4F52-B96E-C1D0C29E1E55");
Guid c = new Guid("BFB9054A-AB18-4349-BCB4-19979D3486BB"); // <-- you know this one, the c guid
Guid d = new Guid("1A8D6CAB-FD42-4517-A0EA-08D3F64DCD69");
Guid e = new Guid("02A8CA8A-5BC8-41BE-8AB8-332EF0B5407B");
List<Guid> guidList = new List<Guid> {a, b, c, d, e};

Solution

Oh wow, now I need to start building indexes pushing and popping yada yada. Well no, a better way to solve this is by using linq.
Getting the record after the one you search for

private static Guid GetNext(IEnumerable<Guid> guidList, Guid current)
{
    return guidList.SkipWhile(i => !x.Equals(current)).Skip(1).First();
}
And to get the record before...
private static Guid GetPrevious(IEnumerable<Guid> guidList, Guid current)
{
    return guidList.TakeWhile(i => !x.Equals(current)).Last();
}

Using Generics (you should)

Whilst separated methods can be neat sometimes a lot of time and engineering can be saved using some generics instead, this means you can dynamically change the type of list you want to search for a certain record.

In example

private static T GetNext<T>(IEnumerable<T> list, T current)
{
    try
    {
        return list.SkipWhile(x => !x.Equals(current)).Skip(1).First();
    }
    catch
    {
        return default(T);
    }
}

private static T GetPrevious<T>(IEnumerable<T> list, T current)
{
    try
    {
        return list.TakeWhile(x => !x.Equals(current)).Last();
    }
    catch
    {
        return default(T);
    }
}

Some usage

String example

string f = "first";
string g = "second";
string h = "third";
string i = "fourth";
string j = "fifth";
List<string> stringList = new List<string>{f,g,h,i,j};

var prev = GetPrevious<string>(stringList, j);
var next = GetNext<string>(stringList, j);

Guid example

Guid a = new Guid("709DBFA9-88B3-4518-A32F-C21B6AAE2917");
Guid b = new Guid("B9956FC6-FD9B-4F52-B96E-C1D0C29E1E55");
Guid c = new Guid("BFB9054A-AB18-4349-BCB4-19979D3486BB");
Guid d = new Guid("1A8D6CAB-FD42-4517-A0EA-08D3F64DCD69");
Guid e = new Guid("02A8CA8A-5BC8-41BE-8AB8-332EF0B5407B");
List<Guid> guidList = new List<Guid> {a, b, c, d, e};

var prev = GetPrevious<Guid>(guidList, c);
var next = GetNext<Guid>(guidList, c);

-

Cheers!

Posted in C# | Leave a Comment »

Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Posted by trikks on November 19, 2011

So you got the “Failure adding assembly to the cache: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.” when running Gacutil

Well good news is that this is easy to fix, you are simply running an old version of gacutil

open a terminal en enter gacutil, maybe something like
PS C:\Windows\Microsoft.NET\Framework\v1.1.4322> .\gacutil.exe
Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.30729.1
Copyright (c) Microsoft Corporation. All rights reserved.
Check the version

Now this option may vary a bit, but in my case the gacutil I should use was in this folder

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64

PS C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64> gacutil
Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.

So, by simply switching to this version my problems are solved!

Posted in .net | Leave a Comment »

Compress a file using GZip and convert it to Base64 – and back – using C#

Posted by trikks on November 3, 2011

Sometimes you want to store a file in a database or even transfer stuff over the Internet through different protocols, maybe even to other platforms. In many of these cases the traditional methods simply wont do.

Storing files in databases is usually made by sending the file as a blob to the database and it usually works out pretty good to, but in some cases you simply want a different structure. I often tend to end up in projects with several platforms and languages, this means XML or similar languages like JSON. Anyway binary data is out, you need a different way to transfer or store files.

When it comes to files I recommend using GZip compression which is shipped as a standard with .NET. If you want more simple compression you should be looking at gzdeflate and gzinflate.

If you only want the source project download it here  http://www.trikks.com/download.php?id=CompressConsole.zip

Compressing a file

string fileName = @"c:\test.pdf";
byte[] file = File.ReadAllBytes(fileName);

// Compress
byte[] compress = Compress(file);
public static byte[] Compress(byte[] data)
{
    using (var compressedStream = new MemoryStream())
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
    {
        zipStream.Write(data, 0, data.Length);
        zipStream.Close();
        return compressedStream.ToArray();
    }
}

Encode the byte array

string encoded = base64_encode(compress);
public string base64_encode(byte[] data)
{
	if (data == null)
		throw new ArgumentNullException("data");
	return Convert.ToBase64String(data);
}

The contents of “encoded” is your file but compressed and base64 encoded. You can take this string and send it through any protocol allowing strings.

If we print the encoded string it looks something like this

Decode and Decompress

// Decode and decompress
byte[] decoded = base64_decode(encoded);
byte[] decompressed = Decompress(decoded);
File.WriteAllBytes(@"c:\out.pdf", decompressed);
public static byte[] base64_decode(string encodedData)
{
    byte[] encodedDataAsBytes = Convert.FromBase64String(encodedData);
    return encodedDataAsBytes;
}
public static byte[] Decompress(byte[] data)
{
    using (var compressedStream = new MemoryStream(data))
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
    using (var resultStream = new MemoryStream())
    {
        var buffer = new byte[4096];
        int read;

        while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            resultStream.Write(buffer, 0, read);
        }

        return resultStream.ToArray();
    }
}

Now that wasn’t hard was it :)

You can download a visual studio project here http://www.trikks.com/download.php?id=CompressConsole.zip

Posted in C# | Leave a Comment »

Joomla! 1.7 Hello World Module Evolved

Posted by trikks on October 6, 2011

So you want to write some modules for Joomla! 1.7 I suppose. Well the good news is that this is a part of Joomla that still simple to work with.

I’ve made this mod_helloworld a bit more complex than the example presented on other sites since I introduce one of the most useful elements in Joomla, the parameters as well as view selection.

If you are tired of reading already download the file here

http://www.trikks.com/download.php?id=mod_helloworld_1_7.zip

Whats in it?

Some files…

You can set this up in the admin interface

And this will be displayed

Code

helper.php

<?php
/**
 * Helper class for Hello World 1.7 skeleton module
 * @author Trikks, http://trikks.wordpress.com
 */
class modHelloWorldHelper {

    /**
 * Retrieves the hello message *
 * @param array $params An object containing the module parameters
 * @access public
 */
    function getHello($params) {
        return 'Hello World!';
    }

}
?>

mod_helloworld.php

<?php
/** 
* Entry Point for Hello World 1.7 skeleton module
* @author Trikks, http://trikks.wordpress.com
*/
defined( '_JEXEC' ) or die( 'Restricted access' ); // no direct access allowed

// Include the syndicate functions only once
require_once dirname(__FILE__).DS.'helper.php'; // get helper files

$hello = modHelloWorldHelper::getHello($params);
require JModuleHelper::getLayoutPath('mod_helloworld', $params->get('layout', 'default'));
?>

mod_helloworld.xml

The settings file, note the parameters in the config section. These parameters are the ones showing in the backend. You fetch them in the views by typing

$params->get('param_name')
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="1.7" client="site" method="upgrade">
    <name>mod_helloworld</name>
    <author>Joomla! Project</author>
    <creationDate>October 2011</creationDate>
    <copyright>Copyleft</copyright>
    <license>GNU General Public License version 2 or later; see LICENSE.txt</license>
    <authorUrl>http://trikks.wordpress.com</authorUrl>
    <version>1.7.0</version>
    <description>Trikks simple hello world module.</description>
    <files>
        <filename module="mod_helloworld">mod_helloworld.php</filename>
        <filename>mod_helloworld.xml</filename>
        <filename>index.html</filename>
        <filename>helper.php</filename>
        <filename>tmpl/default.php</filename>
        <filename>tmpl/index.html</filename>
    </files>
    <config>
        <fields name="params">
            <fieldset name="basic">
                <field name="mod_helloworld_text" type="text" label="A textfield" description="Enter any text"/>
                <field name="mod_helloworld_list" type="list" label="A dropdown" description="Use for custom dropdowns" default="1">
                    <option value="1">JYes</option>
                    <option value="0">JNo</option>
                </field>
                <field name="mod_helloworld_radio" type="radio" label="Radiobuttons" description="Use radiobuttons for explicit selections" default="1">
                    <option value="0">JNo</option>
                    <option value="1">JYes</option>
                </field>
                <field name="layout" type="modulelayout" label="JFIELD_ALT_LAYOUT_LABEL" description="JFIELD_ALT_MODULE_LAYOUT_DESC"/>
                <field name="mod_helloworld_image" type="media" label="Mediaselector" description="Select media"/>
            </fieldset>
        </fields>
    </config>
</extension>

tmpl/default.php

The default view of this module

<?php
// This is the default output file
defined('_JEXEC') or die;

// Echo from getHello method
echo "<p style='font-weight: bold;'>$hello</p>";

// Echo params
echo "<p>";
echo $params->get('mod_helloworld_text') . " | ";
echo $params->get('mod_helloworld_list') . " | ";
echo $params->get('mod_helloworld_radio') . " | ";
echo $params->get('mod_helloworld_image');
echo "</p>";
?>

tmpl/notdefault.php

Simply an additional view which will render a different result in the frontend

<?php
// This is an optional output file
defined('_JEXEC') or die;

// Echo from getHello method
echo "<p style='font-weight: bold;'>$hello</p>";
echo "<p style='font-style: italic;'>- O Hai!</p>";

// Echo params
echo "<p>";
echo $params->get('mod_helloworld_text') . " | ";
echo $params->get('mod_helloworld_list') . " | ";
echo $params->get('mod_helloworld_radio') . " | ";
echo $params->get('mod_helloworld_image');
echo "</p>";
?>

Ending

Not that hard ey :)

http://www.trikks.com/download.php?id=mod_helloworld_1_7.zip

Have fun

 

 

 

Posted in Joomla | 5 Comments »

Launching the new Lion Launchpad with a mouse key

Posted by trikks on September 6, 2011

So you’ve updated to Lion. Good! It’s lovely.

Now, we all love the brand new application desk known as Launchpad but is there a smooth way to open it if you’re on a regular 2-xx button mouse? Of course!

Opening the Launchpad with a mousekey

Launchpad is an application available in the applications folder. To be able to open it with a mouse key like the scroll wheel button you need a plugin like USB Overdrive (http://www.usboverdrive.com/USBOverdrive/News.html).

This way you will be able to open virtually any application with a mouse key.

 

Have fun

Posted in Mac OS X | Leave a Comment »

The type ” is ambiguous: it could come from assembly ” or from assembly ”. Please specify the assembly explicitly in the type name.

Posted by trikks on August 26, 2011

Ah the good old error

You most likely seen it looking something like this

The type ‘Prometer.Objects.AnalysisEngineData’ is ambiguous: it could come from assembly ‘C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\aa63ddac\c47315b5\App_Code.8t9ff09n.DLL’ or from assembly ‘C:\Projects\Webbprojects\Prometer\bin\Prometer.DLL’. Please specify the assembly explicitly in the type name.

In short

Now there are quite a few tricks out there that suggest how to solve this. None of them shows to be correct unless you are really lucky. In general this error depend on a structural error in your Visual Studio project. That means this can be solved by either moving the file or by changing the “Build Action” from Compile to Content.

In reasonable depth

This occur when an aspx page tries to reach a class (like an objectdatasource) and tries to (or actually do) compile the class. But since it’s already compiled everything will fail.

Now in the case shown above I had put my class libraries in the App_Code directory and set the “Build Action” to “Compile” on each library. This solution works but will fail if an aspx-page tries to reach a library since it will build it’s own version of the library (stupid). Now I can solve this by leaving my files in the App_Code folder just setting the ”Build Action” to “Content” instead. But other things might fail doing that.

The best option is to move the class libraries to a separate directory, in example “/Classes”. If so done remember to set the ”Build Action” to “Compile”.

If in App_Code

If in /Classes

So that should be it, please not that there are no work around for this. The structure has to be correct otherwise it simply wont work.
Good luck!

Posted in IIS | 3 Comments »

Programmatically check if an assembly is loaded in GAC with C#

Posted by trikks on July 13, 2011

Maybe you are writing an installer of some kind or are depending on some external assemblies to have your .net program or website to work, I often do. So with no further ado. Here is a small program which will lead you to success in these matters *fanfare*.

Example, running in console

 

Download VS project

Here

Source Code

using System;
using System.Runtime.InteropServices;

namespace ConsoleTestAssembly
{
    class Program
    {
        static void Main()
        {
            string response;

            var exist = AssemblyExist("Camelot.SharePointConnector", out response);
            Console.WriteLine(string.Concat(exist, Environment.NewLine, response, Environment.NewLine));

            exist = AssemblyExist("Camelot.SharePointIntegration", out response);
            Console.WriteLine(string.Concat(exist, Environment.NewLine, response, Environment.NewLine));

            exist = AssemblyExist("Camelot.NoExisting", out response);
            Console.WriteLine(string.Concat(exist, Environment.NewLine, response, Environment.NewLine));

            Console.ReadKey();
        }

        public static bool AssemblyExist(string assemblyname, out string response)
        {
            try
            {
                response = QueryAssemblyInfo(assemblyname);
                return true;
            }
            catch (System.IO.FileNotFoundException e)
            {
                response = e.Message;
                return false;
            }
        }

        // If assemblyName is not fully qualified, a random matching may be 
        public static String QueryAssemblyInfo(string assemblyName)
        {
            var assembyInfo = new AssemblyInfo {cchBuf = 512};
            assembyInfo.currentAssemblyPath = new String('', assembyInfo.cchBuf);

            IAssemblyCache assemblyCache;

            // Get IAssemblyCache pointer
            var hr = GacApi.CreateAssemblyCache(out assemblyCache, 0);
            if (hr == IntPtr.Zero)
            {
                hr = assemblyCache.QueryAssemblyInfo(1, assemblyName, ref assembyInfo);
                if (hr != IntPtr.Zero)
                {
                    Marshal.ThrowExceptionForHR(hr.ToInt32());
                }
            }
            else
            {
                Marshal.ThrowExceptionForHR(hr.ToInt32());
            }
            return assembyInfo.currentAssemblyPath;
        }
    }

    internal class GacApi
    {
        [DllImport("fusion.dll")]
        internal static extern IntPtr CreateAssemblyCache(
            out IAssemblyCache ppAsmCache, int reserved);
    }

    // GAC Interfaces - IAssemblyCache. As a sample, non used vtable entries 
    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
    internal interface IAssemblyCache
    {
        int Dummy1();
        [PreserveSig()]
        IntPtr QueryAssemblyInfo(
            int flags,
            [MarshalAs(UnmanagedType.LPWStr)]
            String assemblyName,
            ref AssemblyInfo assemblyInfo);

        int Dummy2();
        int Dummy3();
        int Dummy4();
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct AssemblyInfo
    {
        public int cbAssemblyInfo;
        public int assemblyFlags;
        public long assemblySizeInKB;

        [MarshalAs(UnmanagedType.LPWStr)]
        public String currentAssemblyPath;

        public int cchBuf;
    }

}

Thats it.

Posted in .net, C# | Tagged: | Leave a Comment »

Howto programmatically add, update and remove ConnectionStrings in Umbraco

Posted by trikks on July 13, 2011

I found that amazing no-one ever posted snippets to howto actually manipulate the web.config file when using Umbraco.

Anyway, lets keep it short.

Dont forget to import the businesslogic.dll into your project and reference it

using System;
using System.Configuration;
using umbraco; // from businesslogic.dll

 

Adding a connectionString in web.config

Note, you should either replace the Camelot.SharePointProvider with your preferred provider or add a parameter to the method to be able to modify this dynamically.

/// <summary>
/// Adds a new connectionString in web.config.
/// </summary>
/// <param name="name">Name the connection</param>
/// <param name="connString">The actual connectionstring. Read more at http://docs.bendsoft.com/camelot-net-connector/</param>
public static void AddConnection(string name, string connString)
{
    var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
    var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
    config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(name, connString, "Camelot.SharePointProvider"));
    config.Save();

    ConfigurationManager.RefreshSection("connectionStrings");
}

Updating a connectionString in web.config

Note, if the connectionString doesn’t exist this method will create it for you

/// <summary>
/// Update an existing connectionString, if it dosn't exist it will be created
/// </summary>
/// <param name="name">Name the connection</param>
/// <param name="connString">The actual connectionstring. Read more at http://docs.bendsoft.com/camelot-net-connector/</param>
public static void UpdateConnection(string name, string connString)
{
    var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
    var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
    var section = (ConnectionStringsSection)config.GetSection("connectionStrings");

    if (section.ConnectionStrings[name] != null)
    {
        // Update the connectionstring if it exist
        section.ConnectionStrings[name].ConnectionString = connString;
        config.Save();

        ConfigurationManager.RefreshSection("connectionStrings");
    }
    else
    {
        // ...otherwise we add a new
        AddConnection(name, connString);
    }
}

Delete a connectionString in web.config

/// <summary>
/// Remove a connectionString
/// </summary>
/// <param name="name">The name of the connectionString to remove</param>
public static void RemoveConnection(string name)
{
    var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
    var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
    var section = (ConnectionStringsSection)config.GetSection("connectionStrings");

    // Die if the connectionstring dosn't exist
    if (section.ConnectionStrings[name] == null) return;

    var keys = section.ConnectionStrings;
    keys.Remove(name);
    config.Save();
    ConfigurationManager.RefreshSection("connectionStrings");
}

Check if connectionstring exist

/// <summary>
/// Check if a connectionString with the same name already exist
/// </summary>
/// <param name="name">Name of the connection</param>
/// <returns>True on existence, otherwise false</returns>
private static bool ConnectionExist(string name)
{
    var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
    var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
    var section = (ConnectionStringsSection)config.GetSection("connectionStrings");

    // Return false if it doesn't exist, true if it does
    return section.ConnectionStrings[name] != null;
}

Thats it!

Posted in Umbraco | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.