Archive for the ‘.Net’ Category

Download and delete files from FTP using Powershell

The following Powershell script connects to a FTP server, gets a list of files from a specific subfolder, downloads and deletes them.

It uses the System.URI,system.net.ftpwebrequesT, system.net.WebRequestMethods+, System.Net.NetworkCredential, System.IO.StreamReader and other .Net classes.

$user1='user'
$pass1='password'
$local_target1 = 'D:\997\'
$ftp_uri1='ftp://ftp.myserver.com'
$subfolder1='/outbound/997/'

function GetFilesListAsArray($user,$pass,$local_target,$ftp_uri,$subfolder)
{
 # ftp address from where to download the files
 $ftp_urix = $ftp_uri + $subfolder
 $uri=[system.URI] $ftp_urix

$ftp=[system.net.ftpwebrequest]::Create($uri)

if($user)
 {
 $ftp.Credentials=New-Object System.Net.NetworkCredential($user,$pass)
 }
 #Get a list of files in the current directory.
 #Use ListDirectoryDetails instead if you need date, size and other additional file information.
 $ftp.Method=[system.net.WebRequestMethods+ftp]::ListDirectory
 $ftp.UsePassive=$true

try
 {
 $response=$ftp.GetResponse()
 $strm=$response.GetResponseStream()
 $reader=New-Object System.IO.StreamReader($strm,'UTF-8')
 $list=$reader.ReadToEnd()
 $lines=$list.Split("`n")
 return $lines
 }
 catch{
 $_|fl * -Force
 }
}

function DownloadFile ($sourceuri,$targetpath,$username,$password){
 # Create a FTPWebRequest object to handle the connection to the ftp server
 $ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)

# set the request's network credentials for an authenticated connection
 $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
 $ftprequest.UseBinary = $true
 $ftprequest.KeepAlive = $false

# send the ftp request to the server
 $ftpresponse = $ftprequest.GetResponse()

# get a download stream from the server response
 $responsestream = $ftpresponse.GetResponseStream()

# create the target file on the local system and the download buffer
 try
 {
 $targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
 "File created: $targetpath"
 [byte[]]$readbuffer = New-Object byte[] 1024

# loop through the download stream and send the data to the target file
 do{
 $readlength = $responsestream.Read($readbuffer,0,1024)
 $targetfile.Write($readbuffer,0,$readlength)
 }
 while ($readlength -ne 0)

$targetfile.close()
 }
 catch
 {
 $_|fl * -Force
 }

}
function DeleteFile ($file,$username,$password){
 # Delete files from FTP server after download
 $uri2=[system.URI] $file
 $request = [system.Net.FtpWebRequest]::Create($uri2)
 $request.Credentials = New-Object System.Net.NetworkCredential($username,$password)
 $request.Method = [System.Net.WebRequestMethods+FTP]::DeleteFile
 $response = $request.GetResponse()
 "Deleted from FTP: $source" -f $response.StatusDescription
 $response.Close()
}

$lines = GetFilesListAsArray $user1 $pass1 $local_target1 $ftp_uri1 $subfolder1
'List of files OK'
$total_files = 0
foreach ($line in $lines){
 if ($line -ne '') {
 #TRIM the file_name because if it contains blank spaces you will get errors when creating the file
 $file_name = $line.ToString().Trim()
 $source = $ftp_uri1 + $subfolder1 + $file_name
 $target = $local_target1 + $file_name
 DownloadFile $source $target $user1 $pass1
 DeleteFile $source $user1 $pass1
 $total_files = $total_files + 1
 }
}
"Total files downloaded: $total_files"

If you get an error like the following when trying to execute the script:

File C:\scripts\test.ps1 cannot be loaded because the execution of scripts is disabled on this system.
Please see “get-help about_signing” for more details.

Make sure the execution of Powershell scripts is enabled:

Get-ExecutionPolicy

And set it to the appropriate level:

Set-ExecutionPolicy Unrestricted

References:

Running Windows PowerShell Scripts

Using the Set-ExecutionPolicy Cmdlet

(Powershell) Loop to delete files from an FTP Location

Anuncios

ASP.Net webforms role based access control

Answered at: http://stackoverflow.com/questions/11664078/permission-based-access-control/12181575#12181575

 

However, I’ve implemented Role Based Access Control on a a classic 3-tier ASP.Net 3.5 web forms application, using a MasterPage, a BasePage class and a RoleBasedAccessControl database model.

Example

User “jtirado” is assigned role “HR-Assistant”, can access route “mywebapp/employee.aspx?id=1452” to edit employee (id:1452) data.

Being “HR-Assistant”, this user can change employee telephone number and e-mail, can view employee salary but not edit the amount.

Telephone number, email, salary are dabatase fields and are represented/rendered by a “asp.net-control” on the ASPX page. So I want to restrict access to these controls based on user’s role.

MasterPage builds the options menu the user has access according to his assigned role. It’s used by all my internal pages.

    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CargaItemMenu(MnuPrincipal, Convert.ToInt32(Session["IdPais"]), Convert.ToInt32(Session["IdRol"]), Convert.ToInt32(Session["IdUsuario"]));
            Session.Add("MenuDinamico", MnuPrincipal);
            if (MnuPrincipal.Items.Count < 1)
            {
                MenuItem menuItems = new MenuItem();
                menuItems.Text = "Principal";
                menuItems.Value = "1";
                menuItems.NavigateUrl = "";
                menuItems.Selectable = true;
                MnuPrincipal.Items.Add(menuItems);
            }

        }
    }

    private void CargaItemMenu(Menu ctrlmenu, int v_IdPais, int v_IdRol, int v_IdUsuario)
    {
        oBEOpcionRol = new SEGU.Entities.ENOpcionRol();
        oBLOpcionRol = new SEGU.BusinessLogic.BLOpcionRol();
        List<ParametroGenerico> ArrayParam;
        ArrayParam = CargarParamentrosOpcionRol(v_IdPais, v_IdRol, v_IdUsuario);
        List<SEGU.Entities.ENOpcionRol> ListaMenuItems = oBLOpcionRol.ListaxIdPaisxIdRolxIdUsuario(ArrayParam);

        foreach (SEGU.Entities.ENOpcionRol objOpcionRol in ListaMenuItems)
        {
            if (objOpcionRol.IdOpcion.IdOpcion.Equals(objOpcionRol.IdOpcion.IdMenu))
            {
                MenuItem mnuMenuItem = new MenuItem();
                mnuMenuItem.Value = objOpcionRol.IdOpcion.IdOpcion.ToString();
                mnuMenuItem.Text = objOpcionRol.IdOpcion.Nombre.ToString();
                if (objOpcionRol.IdOpcion.RutaFormulario != "")
                {
                    mnuMenuItem.NavigateUrl = objOpcionRol.IdOpcion.RutaFormulario.ToString();// +"?IdOpcion=" + Convert.ToString(objOpcionRol.IdOpcion.IdOpcion);
                }

                if (objOpcionRol.IdOpcion.PageNew == "1")
                {
                    mnuMenuItem.Target = "_blank";
                }

                //mnuMenuItem.Target = "iframePrincipal"
                if (objOpcionRol.IdOpcion.Imagen.Trim() != "")
                {
                    mnuMenuItem.ImageUrl = "Seguridad/ImagenesMenus/" + objOpcionRol.IdOpcion.Imagen.Trim();
                }

                if ((mnuMenuItem.NavigateUrl.Trim().Length > 0))
                {
                    mnuMenuItem.Selectable = true;
                }
                else
                {
                    mnuMenuItem.Selectable = false;
                }
                ctrlmenu.Items.Add(mnuMenuItem);
                AddMenuItem(mnuMenuItem, ListaMenuItems);
            }
        }
    }
    private void AddMenuItem(MenuItem mnuMenuItem, List<SEGU.Entities.ENOpcionRol> listaOpcionRol)
    {
        foreach (SEGU.Entities.ENOpcionRol objOpcionRol in listaOpcionRol)
        {
            if (objOpcionRol.IdOpcion.IdMenu.ToString().Equals(mnuMenuItem.Value) && !objOpcionRol.IdOpcion.IdOpcion.Equals(objOpcionRol.IdOpcion.IdMenu))
            {
                MenuItem mnuNewMenuItem = new MenuItem();
                mnuNewMenuItem.Value = objOpcionRol.IdOpcion.IdOpcion.ToString();
                mnuNewMenuItem.Text = objOpcionRol.IdOpcion.Nombre.ToString();
                if (objOpcionRol.IdOpcion.RutaFormulario != "")
                {
                    mnuNewMenuItem.NavigateUrl = objOpcionRol.IdOpcion.RutaFormulario.ToString();// +"?IdOpcion=" + Convert.ToString(objOpcionRol.IdOpcion.IdOpcion);
                }

                if (objOpcionRol.IdOpcion.PageNew == "1")
                {
                    mnuNewMenuItem.Target = "_blank";
                }

                mnuMenuItem.ChildItems.Add(mnuNewMenuItem);
                //mnuNewMenuItem.Target = "iframePrincipal"
                if (objOpcionRol.IdOpcion.Imagen.Trim() != "")
                {
                    mnuNewMenuItem.ImageUrl = "Seguridad/ImagenesMenus/" + objOpcionRol.IdOpcion.Imagen.Trim();
                }

                if ((mnuNewMenuItem.NavigateUrl.Trim().Length > 0))
                {
                    mnuNewMenuItem.Selectable = true;
                }
                else
                {
                    mnuNewMenuItem.Selectable = false;
                }
                AddMenuItem(mnuNewMenuItem, listaOpcionRol);
            }
        }

    }

BasePage class checks if the user has access to the required page. All pages requiring authorization inherit from this BasePage class.

public class PaginaBase : System.Web.UI.Page
{
    SEGU.BusinessLogic.BLOpcionRol oBLOpcionRol;

    protected void Page_InitComplete(object sender, System.EventArgs e) {
    string Url = this.Page.AppRelativeVirtualPath;
    oBLOpcionRol = new SEGU.BusinessLogic.BLOpcionRol();
    int b = oBLOpcionRol.AutentificarUrl(Convert.ToInt32(System.Web.HttpContext.Current.Session["IdPais"]), Convert.ToInt32(System.Web.HttpContext.Current.Session["IdUsuario"]), Convert.ToInt32(System.Web.HttpContext.Current.Session["IdRol"]), Url);
    System.Web.HttpContext.Current.Session["IdOpcion"] = b;            
        if( b <= 0 ){
            System.Web.HttpContext.Current.Response.Redirect("~/Seguridad/Acceso.aspx");
        return;
        }
    }
.
.
}

Finally, on Customers.aspx **Page_Load** event I call a function (oBLPermisoOpcionRol.ValidarPermisos) which checks which receives the Page instance as parameters and iterate its controls (ex: DdlClientType, TxtLastName,ChkIsActive) to check which ones the user can edit, enabling, disabling or hiding them.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SetNodosMenu(TrvMenu, "");
            if (this.TrvMenu.Nodes.Count < 1)
            {
                PrimerNodos(this.TrvMenu);
            }
            ListarModuloxAnulado(GvModulo, Convert.ToString(RblAnuladoModuloBusqueda.SelectedValue), Convert.ToInt32(0), Convert.ToInt32(DdlNroPaginaModulo.SelectedValue));

            oBLPermisoOpcionRol = new SEGU.BusinessLogic.BLPermisoOpcionRol();
            oBLPermisoOpcionRol.ValidarPermisos(Page, Convert.ToInt32(Session["IdRol"]), Convert.ToInt32(Session["IdOpcion"]));
        }
    }

public void ValidarPermisos(System.Web.UI.Page v_Page, int v_IdRol, int v_IdOpcion)
{        
    BusinessLogic.BLPermisoOpcionRol oBLPermisoOpcionRol = new BusinessLogic.BLPermisoOpcionRol();
    List<ParametroGenerico> ArrayParam ;
    ArrayParam = CargarParametros(v_IdRol, v_IdOpcion);        
    List<SEGU.Entities.ENPermisoOpcionRol> Lista = oBLPermisoOpcionRol.ListaxIdRolxIdOpcion(ArrayParam);        
    for(int Fila= 0; Fila< Lista.Count; Fila++){
        bool v_Anulado= true;
        if (Lista[Fila].Anulado == "1") {
            v_Anulado = true;
        }else if (Lista[Fila].Anulado == "0") {
            v_Anulado = false;
        }
        bool v_ControlVisibleDisabled = true;
        if (Lista[Fila].VisbleDisabled == "1") // Control Disabled
        {
            v_ControlVisibleDisabled = true;
        }
        else if (Lista[Fila].VisbleDisabled == "0") // Control Visible
        {
            v_ControlVisibleDisabled = false;
        }
        SetControls(v_Page, Lista[Fila].IdPermiso.Control, v_Anulado, v_ControlVisibleDisabled);
    }
}
public void SetControls(System.Web.UI.Control parentControl, string v_Control, bool permitir, bool v_Permitir_ControlVisibleDisabled)
{
    foreach(System.Web.UI.Control c in parentControl.Controls){
        if( (c) is Button ){
            if( ((Button)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((Button)c).Enabled = false;
                    }else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((Button)c).Visible = false;
                    }                        
                }else{                        
                    ((Button)c).Visible = true;
                }
            }
        }else if( (c) is CheckBox ){
            if( ((CheckBox)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((CheckBox)c).Enabled = false;
                    }else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((CheckBox)c).Visible = false;
                    }
                }else{
                    ((CheckBox)c).Visible = true;
                }
            }
        }else if( (c) is Label ){
            if( ((Label)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((Label)c).Enabled = false;
                    }else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((Label)c).Visible = false;
                    }
                }else{
                    ((Label)c).Visible = true;
                }
            }
        }else if( (c) is TextBox ){
            if( ((TextBox)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((TextBox)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((TextBox)c).Visible = false;
                    }
                }else{
                    ((TextBox)c).Visible = true;
                }
            }
        }else if( (c) is GridView ){
            if( ((GridView)c).ID == v_Control ){
                if( permitir == true ){
                     if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((GridView)c).Enabled = false;
                    }else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                         ((GridView)c).Visible = false;
                     }
                }else{
                    ((GridView)c).Visible = true;
                }
            }
        }else if( (c) is ImageButton ){
            if( ((ImageButton)c).ID == v_Control ){
                if (permitir == true)
                {
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((ImageButton)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((ImageButton)c).Visible = false;
                    }
                }
                else
                {
                    ((ImageButton)c).Visible = true;
                }
            }
        }else if( (c) is HyperLink ){
            if( ((HyperLink)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((HyperLink)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((HyperLink)c).Visible = false;
                    }
                }else{                        
                    ((HyperLink)c).Visible = true;
                }
            }
        }else if( (c) is DropDownList ){
            if( ((DropDownList)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((DropDownList)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((DropDownList)c).Visible = false;
                    }
                }else{
                    ((DropDownList)c).Visible = true;
                }
            }
        }else if( (c) is ListBox ){
            if( ((ListBox)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((ListBox)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((ListBox)c).Visible = false;
                    }
                }else{
                    ((ListBox)c).Visible= true;
                }
            }
        }else if( (c) is DataList ){
            if( ((DataList)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((DataList)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((DataList)c).Visible = false;
                    }
                }else{
                    ((DataList)c).Visible = true;
                }
            }
        }else if( (c) is CheckBoxList ){
            if( ((CheckBoxList)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((CheckBoxList)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((CheckBoxList)c).Visible = false;
                    }
                }else{
                    ((CheckBoxList)c).Visible = true;
                }
            }
        }else if( (c) is RadioButton ){
            if( ((RadioButton)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((RadioButton)c).Enabled= false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((RadioButton)c).Visible = false;
                    }
                }else{                        
                    ((RadioButton)c).Visible = true;
                }
            }
        }else if( (c) is RadioButtonList ){
            if( ((RadioButtonList)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((RadioButtonList)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((RadioButtonList)c).Visible = false;
                    }
                }else{                        
                    ((RadioButtonList)c).Visible = true;
                }
            }
        }else if( (c) is Image ){
            if( ((Image)c).ID == v_Control ){
                if( permitir == true ){                        
                    ((Image)c).Visible = false;                        
                }else{                        
                    ((Image)c).Visible = true;
                }
            }
        }else if( (c) is Panel ){
            if( ((Panel)c).ID == v_Control ){
                if (permitir == true)
                {
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((Panel)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((Panel)c).Visible = false;
                    }
                }
                else
                {
                    ((Panel)c).Visible = true;
                }
            }
        }else if( (c) is Table ){
            if( ((Table)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((Table)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((Table)c).Visible = false;
                    }
                }else{
                    ((Table)c).Visible= true;
                }
            }
        }else if( (c) is LinkButton ){
            if( ((LinkButton)c).ID == v_Control ){
                if( permitir == true ){
                    if (v_Permitir_ControlVisibleDisabled == true)
                    {
                        ((LinkButton)c).Enabled = false;
                    }
                    else if (v_Permitir_ControlVisibleDisabled == false)
                    {
                        ((LinkButton)c).Visible = false;
                    }
                }else{                        
                    ((LinkButton)c).Visible = true;
                }
            }

        }else if( (c) is System.Web.UI.HtmlControls.HtmlInputButton ){
            if( ((System.Web.UI.HtmlControls.HtmlInputButton)c).ID == v_Control ){
                if( permitir == true ){
                    ((System.Web.UI.HtmlControls.HtmlInputButton)c).Visible = false;
                    ((System.Web.UI.HtmlControls.HtmlInputButton)c).Attributes.Add("disabled", "disabled");
                }else{
                    ((System.Web.UI.HtmlControls.HtmlInputButton)c).Visible = true;
                    ((System.Web.UI.HtmlControls.HtmlInputButton)c).Attributes.Remove("disabled");
                }
            }

        }else if( (c) is System.Web.UI.HtmlControls.HtmlAnchor ){
            if( ((System.Web.UI.HtmlControls.HtmlAnchor)c).ID == v_Control ){
                if( permitir == true ){
                    ((System.Web.UI.HtmlControls.HtmlAnchor)c).Visible = false;
                    // CType(c, System.Web.UI.HtmlControls.HtmlAnchor).Attributes.Add("disabled", "disabled")
                }else{
                    ((System.Web.UI.HtmlControls.HtmlAnchor)c).Visible = true;
                    //CType(c, System.Web.UI.HtmlControls.HtmlAnchor).Attributes.Remove("disabled") '' etiqueta <a runat="server" ID="id1">
                }
            }

        }else if( (c) is System.Web.UI.HtmlControls.HtmlGenericControl ){
            if( ((System.Web.UI.HtmlControls.HtmlGenericControl)c).TagName.ToUpper() == "DIV".ToUpper() ){
                if( ((System.Web.UI.HtmlControls.HtmlGenericControl)c).ID == v_Control ){
                    if( permitir == true ){
                        ((System.Web.UI.HtmlControls.HtmlGenericControl)c).Visible = false;
                        //CType(c, System.Web.UI.HtmlControls.HtmlGenericControl).Attributes.Add("disabled", "disabled")
                    }else{
                        ((System.Web.UI.HtmlControls.HtmlGenericControl)c).Visible = true;
                        //CType(c, System.Web.UI.HtmlControls.HtmlGenericControl).Attributes.Remove("disabled") '' etiqueta <div runat="server" ID="iddiv">
                    }
                }
            }

        }
        SetControls(c, v_Control, permitir, v_Permitir_ControlVisibleDisabled);
    }
}  

This way, I don’t have to use if-then sentences to check permissions and, I can create as many roles as I want, giving them any permissions, without having to change any C# code.

You can check these posts also:

Is ASP.NET role based security a true role based access control system?

Role-based access control – should I have the permission list in the db as well or just in the code (eg enum)?

How to control access to forms fields on a ASP.Net MVC 3 view?


			

VS 2010 Pattern Toolkit Manager fix

  1. Download the ‘Newtonsoft.Json.dll’ assembly (version 4.0.2 or higher) from http://json.codeplex.com.
  2. Copy the assembly to the directory: %localappdata%\Microsoft\VisualStudio\10.0\Extensions\Microsoft\Pattern Toolkit Manager\1.2.19.0\.
  3. Restart Visual Studio.
  4. VS should now start normally and you can create a new ‘Pattern Toolkit’ project.

Reference:

Q and A – Pattern Toolkit Builder extension

SELECT N +1 problem

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, “N” being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls –> more latency time –> decreased application/database performance.

However, ORM’s have options to avoid this problem, mainly using “joins”.

 

Topic on StackOverflow: http://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem

Publish ASP.Net web application using MSBuild and PowerShell

PowerShell script to build and publish ASP.Net web application, applying web.config tranformations, using MSBuild.

Considerations:

  • This works for a solution having  7 projects: 1 web application project and 6 related others (DataAccess, BussinessLogic,DomainEntities, Utils, etc).
  • All of these projects run under .Net Framework 3.5.
  • I’m using Visual Studio 2010.
  • Finally I got a MSBUILD error MSB1008 (Only one project can be specified.), but anyway, build and publish worked.

PowerShell script

$build = "$env:windir\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"
$SolutionPath = "D:\SOLUTION_PATH"
$SolutionFile = "SEGU.sln"
$WebProjectFile = "SEGU\SEGU.csproj"
$WebConfigTransform = "Build-Web.Config.xml"
$OutputPath = "D:\SOLUTION_PATH\PrecompiledWeb\SEGU"
& $build "$SolutionPath\$SolutionFile" /t:rebuild
& $build "$SolutionPath\$WebProjectFile" "/t:ResolveReferences;_CopyWebApplication;publish" /p:OutDir="$OutputPath\bin\" /p:WebProjectOutputDir="$OutputPath"
& $build "$SolutionPath\$WebConfigTransform"

Build-Web.config.xml

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="TransformXml" AssemblyFile="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.Dll"/>
<Target Name="GenerateConfigs">
<Message Text="Transfom Config." />
<TransformXml Source="SEGU/Web.config" Transform="Web.Release.Config" Destination="PrecompiledWeb/SEGU/Web.config" />
<Message Text="Done Transfom Config." />
</Target>
</Project>

Web.Release.config

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="UserName" value="myuser" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
<add key="Password" value="password" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
<add key="SERVERNAME" value="192.168.10.14" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
<add key="urlServerReporting" value="http://RELEASE_SERVER/ReportServer" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
<connectionStrings>
<add name="ConSEG" connectionString="Data Source=RELEASE_SERVER;Initial Catalog=Seguros;User ID=username;pwd=password" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
  <system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
  </system.web>
</configuration>

References:

Replicate VS2008 “Publish Web Site” from command line
How do I publish a Asp.net web application using MSBuild?
How to Publish Web with msbuild?
MSBuild Error MSB1008
MSBUILD : error MSB1008: Only one project can be specified. Switch: Education

Web config transformations

Web.config Transformation Syntax for Web Application Project Deployment
How to: Transform Web.config When Deploying a Web Application Project
Transform app.config and web.config
Web.config Transformation Tester
_CopyWebApplication with web.config transformations
Using MSBuild 4.0 web.config Transformation to Generate Any Config File
Config transformations outside of web app builds
Deploying an ASP.NET Web Application to a Hosting Provider using Visual Studio or Visual Web Developer: Web.Config File Transformations – 3 of 12

Continuous Integration: some posts

Martin Fowler: Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily – leading to multiple integrations per day. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible. Many teams find that this approach leads to significantly reduced integration problems and allows a team to develop cohesive software more rapidly.

Some posts about Continuous Integration for further reading:

Continuous Integration
How and why do I set up a C# build machine?
Best Continuous Integration Setup for a solo developer (.NET) [closed]
Continuous Integration for Everybody

System.Web.DataVisualization Missing

This was driving me crazy!!! But the solution was so easy!!!

Before, I had to ask my co-worker to compile the app and give it compiled to me so I can deploy it.

This post did the trick: System.Web.DataVisualization Missing

Had to install this from here :Microsoft Chart Controls for Microsoft .NET Framework 3.5