Get role list from Web.Config


var res = new List<string>();
var conf = WebConfigurationManager.GetSection("system.web/authorization");
if (conf != null)
{
    var sec = (AuthorizationSection)conf;
    foreach (AuthorizationRule r in sec.Rules)
    {
        if (r.Action == AuthorizationRuleAction.Allow)
        {
            var p = r.ElementInformation.Properties["roles"];
            if (p != null)
            {
                if (p.ValueOrigin != PropertyValueOrigin.Inherited)
                {
                    string val = p.Value.ToString();
                    if (!string.IsNullOrEmpty(val))
                    {
                        string[] roles = val.Split(',');
                        foreach (string roleStr in roles)
                        {
                            string roleVal = roleStr.Trim();
                            if (roleVal != string.Empty)
                            {
                                res.Add(roleVal);
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
}

Advertisements

SQL tip: sub-query in select column statement

Thats why SQL rocks 😀


select top 100
	b.Id,
	b.Title,
	cast(
	(
		select
			case
				when count(i.Id) = 0 then 0
				else 1
			end
		from AnnotationFiles i where i.BibliographicRecord_Id = b.Id
	) as bit)
	HasImage
from BibliographicRecords b

Posted in MS SQL. Tags: . Leave a Comment »

Change assembly version by team build

1. Create custom task by Visual Studio:


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyBuildExtensions
{
    public class AssemblyInfo : Task
    {
        private const string Company = "Company name";
        private const string Copyright = "© 19xx - {0} Company name";

        [Required]
        public string FileNames { get; set; }

        [Required]
        public int MajorVersion { get; set; }

        [Required]
        public int MinorVersion { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string Description { get; set; }

        public override bool Execute()
        {
            Log.LogMessage("FileName: {0}", FileNames);

            DateTime now = DateTime.Now;
            int year = now.Year;
            string copyright = string.Format(Copyright, year);

            Log.LogMessage("Copyright: {0}", copyright);

            string buildNumber = now.ToString("yyMM");
            string revision = now.ToString("dd");
            string version = string.Format("{0}.{1}.{2}.{3}", MajorVersion, MinorVersion, buildNumber, revision);

            Log.LogMessage("Version: {0}", version);

            List<string> fileList = new List<string>();
            if (FileNames.Contains(";"))
            {
                string[] files = FileNames.Split(';');
                fileList.AddRange(files);
            }
            else
            {
                fileList.Add(FileNames);
            }
            bool ok = false;
            foreach (string fileName in fileList)
            {
                ok = ReplaceProperties(fileName, version, copyright);
                if (!ok)
                {
                    break;
                }
            }
            return ok;
        }

        private bool ReplaceProperties(string fileName, string assemblyVersion, string assemblyCopyright)
        {
            bool ok = false;

            // remove readonly
            FileAttributes currentAttr = File.GetAttributes(fileName);
            File.SetAttributes(fileName, FileAttributes.Normal);

            // read file
            string content = File.ReadAllText(fileName, Encoding.UTF8);

            // replace properties
            ok = ReplaceProperty(ref content, Title, "AssemblyTitle", fileName);
            if (ok)
            {
                ok = ReplaceProperty(ref content, Title, "AssemblyProduct", fileName);
            }
            if (ok)
            {
                ok = ReplaceProperty(ref content, Description, "AssemblyDescription", fileName);
            }
            if (ok)
            {
                ok = ReplaceProperty(ref content, assemblyCopyright, "AssemblyCopyright", fileName);
            }
            if (ok)
            {
                ok = ReplaceProperty(ref content, assemblyVersion, "AssemblyVersion", fileName);
            }
            if (ok)
            {
                ok = ReplaceProperty(ref content, assemblyVersion, "AssemblyFileVersion", fileName);
            }

            // write back to file
            File.WriteAllText(fileName, content, Encoding.UTF8);

            // set readonly back
            File.SetAttributes(fileName, currentAttr);

            return ok;
        }

        private bool ReplaceProperty(ref string content, string newValue, string propertyName, string fileName)
        {
            string pattern = string.Format("{0}\\(\".*\"\\)", propertyName);
            string replacement = string.Format("{0}(\"{1}\")", propertyName, newValue);
            var re = new Regex(pattern, RegexOptions.Multiline);
            if (re.IsMatch(content))
            {
                content = re.Replace(content, replacement);
            }
            else
            {
                Log.LogError("The content of file {0} does not contain {1} attribute!", fileName, propertyName);
                return false;
            }
            return true;
        }
    }
}

You must add those references first:

  • Microsoft.Build.Framework.dll
  • Microsoft.Build.Utilities.v3.5.dll

2. Copy DLL that contains created task to Team Build server.
For example: C:\Program Files\MSBuild\ExtensionPack\MyBuildExtensions.dll

3. Modify project Team Build Type file (TFSBuild.proj):


<UsingTask AssemblyFile="$(MSBuildExtensionsPath)\\ExtensionPack\\MyBuildExtensions.dll" TaskName="MyBuildExtensions.AssemblyInfo"/>
<Target Name="BeforeCompile">
		
        <!-- specify assembly files to include for AssemblyInfo Task -->
        <CreateItem Include="$(SourcesRoot)\**\AssemblyInfo.*">
            <Output ItemName="AssemblyInfoFiles" TaskParameter="Include"/>
        </CreateItem>

	<MyBuildExtensions.AssemblyInfo
			FileNames="@(AssemblyInfoFiles)"
			MajorVersion="1"
			MinorVersion="2"
			Title="Product title"
			Description="Product description">			
	</MyBuildExtensions.AssemblyInfo>

</Target>

Where $(SourcesRoot) is custom defined property that points to the sources folder.

My versioning is in the format: Minor.Major.YYMM.DD

Get assembly version & other attributes

To get assembly version:

var systemVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

To get assembly file attribute:

string company = "Default";
var ass = Assembly.GetExecutingAssembly();
var att = ass.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (att.Length > 0)
{
var companyAtt = att[0] as AssemblyCompanyAttribute;
company = companyAtt.Company;
}

Posted in C#. Tags: . Leave a Comment »

MS SQL bulk export / import

To export in native format execute from the command-line:

bcp MyDatabase..MyTable format nul -n -x -f C:\MyFolder\MyTableFormat.xml -T
bcp MyDatabase..MyTable out C:\MyFolder\MyTableData.dat -n -T

To deal with tables containing XML datatype the format file (MyTableFormat.xml) must be modified: add MAX_LENGTH=”8001″ to the FIELD element that represents column containing XML!

To import data in existing table that already contains data execute SQL:

print 'Inserting MyTable with KEEPIDENTITY ...'
INSERT INTO [dbo].[MyTable]
WITH (KEEPDEFAULTS, KEEPIDENTITY)
([Id],[Col1],[Col2],[ColXml])
SELECT [Id],[Col1],[Col2],CONVERT(xml, [ColXml])
FROM
OPENROWSET
(
BULK 'C:\MyFolder\MyTableData.dat',
FORMATFILE='C:\MyFolder\MyTableFormat.xml''
)
as t1
WHERE t1.Id NOT IN (SELECT Id FROM [dbo].[MyTable])

If you don’t want to preserve Id values from imported table then instead of previous example execute following:

print 'Inserting MyTable with autoincrement ...'
INSERT INTO [dbo].[MyTable]
WITH (KEEPDEFAULTS)
[Col1],[Col2],[ColXml])
SELECT [Col1],[Col2],CONVERT(xml, [ColXml])
FROM
OPENROWSET
(
BULK 'C:\MyFolder\MyTableData.dat',
FORMATFILE='C:\MyFolder\MyTableFormat.xml''
)

Enable WCF message logging/tracing

Place following in the config file:

<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage=”true”
logMalformedMessages=”false”
logMessagesAtServiceLevel=”false”
logMessagesAtTransportLevel=”true”
maxMessagesToLog=”3000″
maxSizeOfMessageToLog=”2000″/>
</diagnostics>

. . .

<system.diagnostics>
<sources>
<source name=”System.ServiceModel.MessageLogging” switchValue=”Information, ActivityTracing”>
<listeners>
<add name=”log”
initializeData=”c:\temp\Traces.svclog”
type=”System.Diagnostics.XmlWriterTraceListener” />
</listeners>
</source>
</sources>
<trace autoflush=”true”/>
</system.diagnostics>

  • Use SvcTraceViewer.exe to view svclog file (visual studio command prompt).
  • Change parameter swithcValue to “Warning, ActivityTracing” when in production!
  • Message will not be placed into the log, if size will be larger than maxSizeOfMessagesToLog (in bytes)!
Posted in WCF. Tags: . Leave a Comment »

How to navigate to the current path of the BAT file

@ECHO OFF
REM Go to the current directory
REM.
CD %~dp0
REM Show files
DIR