El TecnoBaúl de Kiquenet

Kiquenet boring stories

Archive for 27 agosto 2014

Using different credentials to connect to Team Foundation Server

Posted by kiquenet en 27 agosto 2014

TFS Cache
<system drive>\Users\<your profile>\AppData\Microsoft\Team Foundation

You can try clearing the cache manually here: C:\Users[USERNAME]\AppData\Local\Microsoft\Team Foundation\5.0\Cache

Control Panel->User Accounts –> Manage your credentials (CredentialManager)

You can also use the command line to open the credential manager.

control /name Microsoft.CredentialManager

This will open the credential manager.

Recently, I had to authenticate to Team Foundation Server using an account with greater permissions to perform some administrative tasks.  As you may know, this requires entering alternate credentials when you add the server to the list of TFS servers, or when you need to connect to the server.  Once you’ve connected once, you aren’t prompted again as the credentials are cached locally.

In the past, to remedy this, you could simply delete the local TFS cache, which is located in the following directory (Windows Vista and onwards):

<system drive>\Users\<your profile>\AppData\Microsoft\Team Foundation

image

However, in more recent versions this has changed somewhat, and the user’s credentials are no longer linked to the local TFS cache or configuration.

Where are the Credentials?

Good question.  After some digging about, it seems that the credentials are now stored in the user’s Credential Manager store within Windows.  If you aren’t familiar with this, it was introduced on the more recent versions of Windows, and it lives via the Control Panel, under the following path: Control Panel->User Accounts

image

Inside this location, you can view all the locally cached credentials, including Windows Credentials:

image

Note: that it appears that for TFS credentials used by Team Explorer and other applications, the credentials are the ones under “Generic Credentials” not under “Windows Credentials” (in case you have TFS entries in both).

Making Changes

To modify or remove the credentials you use to connect to TFS, simply expand the appropriate entry and click on “Edit”, or to delete the local credentials, click on “Remove”.  If you opt to remove the credentials, you’ll be prompted to enter new credentials next time you connect to the specified TFS server.

image

So that was a little out of the way. When I tested this, I made sure that I’d disconnected from TFS before changing/removing the credential configuration.

It would be nice if Team Explorer linked to the Credentials Manager so we didn’t have to go digging to work this out, wouldn’t it?

TFS credentials

When you connect TFS from Visual Studio you will be asked to give user credential to connect. If you checked the option Remember my credentials while connecting TFS, you won’t be asked credentials again to connect TFS. In that case, if you wanted to change different credentials to connect TFS. you need to follow below solution to force Visual Studio to ask new credentials to connect TFS.

Revert TFS credentials in Visual Studio

Force to change TFS credentials in Visual Studio

      You need to remove TFS credentials from Windows Vault to clear and force to ask new TFS credentials in Visual Studio
      1. Go to Control Panel (Start -> Control Panel).
      2. Click User Accounts ( or User Accounts and Family Safety->User Accounts in Windows 7 Machine)
      3. Click Credential Manager (or Manage your credentials)

Remove TFS user credentials in Visual Studio

     4. In Credential Manager page, you can see the two type of credentials
           i. Windows Credentials
           ii. Generic Credentials

     5. Click on two credential’s modify link,  click the link Remove from vault to remove stored TFS credentials.

Now, When you login into Visual Studio you will be asked to give credentials to connect TFS.

Note:
Don’t forgot to uncheck the option Remember my credentials to force to ask credentials for every TFS connections.

References:
http://sanderstechnology.com/2013/using-different-credentials-to-connect-to-team-foundation-server/11865/#.U-iskPl_vij
http://www.morgantechspace.com/2013/09/how-to-change-user-credentials-for-tfs.html

Anuncios

Posted in Seguridad, TFS | Etiquetado: , , | Leave a Comment »

Introducing SQLite

Posted by kiquenet en 22 agosto 2014

http://damienbod.wordpress.com/2013/11/14/using-sqlite-with-net/

Helper class:

https://github.com/iancooper/Paramore/blob/master/Renegade/UserGroupManagement.Configuration/DomainDatabaseBootStrapper.cs
csharp-sqlite SQLiteClientTestDriver.cs

Getting started with SQLite and .NET
http://blog.kurtschindler.net/getting-started-with-sqlite-and-net/

You can install and use the core SQLite library on the official download page, but as a .NET developer your best bet is go with System.Data.SQLite – an ADO.NET provider for the SQLite engine. It also includes design-time support in Visual Studio 2005/2008!

See using-SQlite with Entity Framework 6 and the Repository Pattern

http://damienbod.wordpress.com/2013/11/18/using-sqlite-with-entity-framework-6-and-the-repository-pattern/

Code: https://github.com/damienbod/SQLiteExamples

What is it? (Taken from http://schimpf.es/sqlite-vs-mysql )
SQLite is a single-file based database which is useful for testing and for embedding in applications. This means that all the information is stored in a single file on a file system and you use a SQLite library to open this file to read and write your data.

Here’s 3 links to the SQLite website which are worth reading:

Hello World Project (Taken from http://blog.tigrangasparian.com/2012/02/09/getting-started-with-sqlite-in-c-part-one/)

Using Entity Framework 6 with SQLite (taken from brice-lambson.blogspot.ch )

This an example doesn’t work quiet as easy as described. To use Entity Framework 6 with SQLite, the source code of the SQLite package needs to be changed, or you must get the pre-release package fromhttps://www.myget.org/F/bricelam/

SQLite Administration
Use the Firefox addon: https://addons.mozilla.org/de/firefox/addon/sqlite-manager/

Here you can browser select, insert as you wish. It is easy to use and uncomplicated.

SQLite Manager is a Firefox addon (or see project hosted on google code:http://code.google.com/p/sqlite-manager/)

SQLite Manager GUI

sqliteDb1

 

SQlite Administrator

SQLite Administrator is a great little freeware tool supporting multiple languages and many features.

SQLite Administrator GUI

Link for SQL as understood by SQLite: http://www.sqlite.org/lang.html

sqlite-net available from this link https://github.com/praeclarum/sqlite-net.

Unfortunately, the getting started documentation are not enough. It doesnt even mention how to create a database. I tried looking at the examples, unfortunately, the examples are broken(unable to compile, run time error etc).

The most practical tutorial i can find on the net is http://blog.tigrangasparian.com/2012/02/09/getting-started-with-sqlite-in-c-part-one/

Unfortunately, sqlite-net doesnt fully support sqlite.org sqlite implementation, thus making the tutorial useless for praeclarum sqlite-net.

Error :- Mixed mode assembly is built against version ‘v2.0.50727’ of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information
http://geeksprogrammings.blogspot.com.es/2014/08/sqlite-error-mixed-mode-assembly-.html

Discusión en ALT.NET Hispano
https://groups.google.com/forum/#!msg/altnet-hispano/A8-mXfuifnk/TfcT1VLuYj8J

References:
http://stackoverflow.com/questions/19851213/how-to-usecreate-db-create-table-query-etc-praeclarum-sqlite-net


http://system.data.sqlite.org

https://addons.mozilla.org/de/firefox/addon/sqlite-manager/

http://sqliteadmin.orbmu2k.de/

http://blog.tigrangasparian.com/2012/02/09/getting-started-with-sqlite-in-c-part-one/

http://brice-lambson.blogspot.ch/2012/10/entity-framework-on-sqlite.html

http://brice-lambson.blogspot.ch/2013/06/systemdatasqlite-on-entity-framework-6.html

http://www.connectionstrings.com/sqlite/

http://www.codeproject.com/Articles/236918/Using-SQLite-embedded-database-with-entity-framewo

http://stackoverflow.com/questions/2514785/how-to-create-an-entity-framework-model-from-an-existing-sqlite-database-in-visu

http://www.thomasbelser.net/2009/01/25/c-sharp-und-sqlite-eine-kleine-einfuhrung/

http://cplus.about.com/od/howtodothingsinc/ss/How-To-Use-Sqlite-From-Csharp.htm

http://stackoverflow.com/questions/11591002/how-can-i-use-sqlite-in-a-c-sharp-project

http://schimpf.es/sqlite-vs-mysql/

http://chinookdatabase.codeplex.com/

http://stackoverflow.com/questions/14510096/entity-framework-6-sqlite

http://blogs.msdn.com/b/mim/archive/2013/06/18/sync-framework-with-sqlite-for-windows-store-apps-winrt-and-windows-phone-8.aspx

http://code.msdn.microsoft.com/windowsapps/Sqlite-For-Windows-8-Metro-2ec7a882

http://blogs.msdn.com/b/andy_wigley/archive/2013/06/06/sqlite-winrt-database-programming-on-windows-phone-and-windows-8.aspx

Posted in .NET, DataAccess | Etiquetado: | Leave a Comment »

UAC, Run As Administrator, Elevated Process

Posted by kiquenet en 22 agosto 2014

cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.UseShellExecute = false; // true ???
cmd.Verb = “runas”

The Verb only works with UseShellExecute set to true

You must use ShellExecute. ShellExecute is the only API that knows how to launch Consent.exe in order to elevate.
In C#, the way you call ShellExecute is to use Process.Start along with UseShellExecute = true:






const int ERROR_CANCELLED = 1223; //The operation was canceled by the user. ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe"); info.UseShellExecute = true; info.Verb = "runas"; try { Process.Start(info); } catch (Win32Exception ex) { if (ex.NativeErrorCode == ERROR_CANCELLED) MessageBox.Show("Why you no select Yes?"); else throw; }

You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to ‘runas’, as follows:

startInfo.Verb = "runas";

This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.

This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you’ll need to run your entire host process with elevated permissions by embedding the appropriate manifest in your application to require the ‘highestAvailable’ execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

Edit: I see just just edited your question to state that "runas" didn’t work for you. That’s really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.

Manifest for Application: http://msdn.microsoft.com/en-us/library/bb756929.aspx

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Executable: IsUserAdmin.exe 
Manifest:IsUserAdmin.exe.manifest
Sample application manifest file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> 
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="IsUserAdmin"
     type="win32"/> 
  <description>Description of your application</description> 
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="requireAdministrator"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>

Update: The app manifest way is preferred:

Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.

(Properties Project –> Application –> Resources –> Icon and manifest (embed, first add it and then select)

How to set UAC settings in manifest (VS 2008)

http://justinyue.wordpress.com/2008/12/19/how-to-set-uac-settings-in-manifest-for-vs-2008/

if (IsAdministrator() == false)
{
    // Restart program and run as admin
    var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
    startInfo.Verb = "runas";
    System.Diagnostics.Process.Start(startInfo);
    Application.Current.Shutdown();
    return;
}

private static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)


this error

The Process object must have the UseShellExecute property set to false in order to redirect IO streams.

The Process object must have the UseShellExecute property set to false in order to start a process as a user

you cannot have it both ways. UAC prevents an unelevated process from hi-jacking the capabilities of an elevated one. The only way you can redirect is to elevate yourself first.

You need to set UseShellExecute to true for the Verb to be respected and it must be set to ‘false’ to redirect standard output. You can’t do both.

I’m pretty sure Windows also won’t allow you to redirect standard input/output/error across the admin/non-admin security boundary. You’ll have to find a different way to get output from the program running as admin.

According to this article, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don’

http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx

  • UAC – What. How. Why.. The architecture of UAC, explaining that CreateProcess cannot do elevation, only create a process. ShellExecute is the one who knows how to launch Consent.exe, and Consent.exe is the one who checks group policy options.


Check out this code (I was inspired by the code here, but I’ve improved it – in my version there is no directory created and removed to check for admin privileges):

:::::::::::::::::::::::::::::::::::::::::

:: Automatically check & get admin rights

:::::::::::::::::::::::::::::::::::::::::

@echo off

CLS

ECHO.

ECHO =============================

ECHO Running Admin shell

ECHO =============================

:checkPrivileges

NET FILE 1>NUL 2>NUL

if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges

if '%1'=='ELEV' (shift & goto gotPrivileges) 
ECHO.

ECHO **************************************

ECHO Invoking UAC for Privilege Escalation

ECHO **************************************

setlocal DisableDelayedExpansion

set "batchPath=%~0"

setlocal EnableDelayedExpansion

ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"

ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"

"%temp%\OEgetPrivileges.vbs"

exit /B

:gotPrivileges

::::::::::::::::::::::::::::

:START

::::::::::::::::::::::::::::

setlocal & pushd .

REM Run shell as admin (example) - put here code as you like

cmd /k

The script takes advantage of the fact that NET FILE requires admin privilege and returns errorlevel 1 if you don’t have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the admin account and password.

I have tested it with Windows 7 and with Windows XP – works fine for both. Advantage is, after the start point you can place anything that requires admin privileges, e.g. if you intend to re-install and re-run a Windows service for debugging purpose (assumed that mypackage.msi is a service installer package):

msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice

Without this privilege elevating script UAC would ask you three times for your admin user and password – now you’re asked only once at the beginning, and only if required.


Update: If your script just needs to show an error message and exit if there are no admin privilegesinstead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:

@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
  ECHO "RUN AS ADMINISTRATOR"  to run this batch. Exiting... & ECHO. & 
  PAUSE & EXIT /D)
REM ... proceed here with admin rights ...

This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects admin rights, otherwise exit with an error. If you don’t require the PAUSE, just remove it. Important: NET FILE [...] EXIT /D) must be in the same line, it is displayed here in multiple lines for better readability!


Update: On some machines, I’ve encountered issues, which are solved in the new version above already. One was due to different double quote handling, the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.

I have fixed this now by stripping the quotes in the path and re-adding them later and I’ve added an extra parameter which is added when the script re-launches with elevated rights.

The double quotes are removed by the following (details are here):

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion

You can then access the path by using !batchPath!, it contains no double quotes so it is safe to say "!batchPath!" later in the script.

The line

if '%1'=='ELEV' (shift & goto gotPrivileges)  

checks if the script has already been called by the VBS to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.


Mt.exe Tool

Common Errors:

Exited with code 9009 (Post Build Event)

Values of attribute "name" not equal in different manifest snippets. mt.exe


http://stackoverflow.com/questions/4677055/visual-studio-post-build-event-mt-exe-command-fails-with-code-9009?rq=1#4865696

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\mt.exe"
"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\mt.exe" -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"

References:

http://stackoverflow.com/questions/8690552/run-elevated-process

http://stackoverflow.com/questions/16926232/run-process-as-administrator-from-a-non-admin-application/20872219#20872219

http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically

http://msdn.microsoft.com/en-us/magazine/cc163486.aspx

http://stackoverflow.com/questions/7044985/how-can-i-auto-elevate-my-batch-file-so-that-it-requests-from-uac-admin-rights?answertab=votes#tab-top

http://justinyue.wordpress.com/2008/12/19/how-to-set-uac-settings-in-manifest-for-vs-2008/

Posted in .NET, Scripts, Security | Etiquetado: , , , , | Leave a Comment »

Troubleshooting: Sharepoint Deployments and Powershell

Posted by kiquenet en 13 agosto 2014

 

Account for Installations

http://sharepointlearningcurve.blogspot.com.es/2010/04/sharepoint-2010-installation-account.html

http://serverfault.com/questions/349300/permissions-error-setting-up-powershell-account-privileges-for-sharepoint-2010

http://sharepoint.stackexchange.com/questions/26831/permissions-error-setting-up-sharepoint-2010-powershell-account-privileges

Error This operation uses the SharePoint Administration service (spadminV4), which could not be contacted.  If the service is stopped or disabled, start it and try the operation again.

http://support.microsoft.com/kb/925727

http://sharepoint.stackexchange.com/questions/72106/remove-spwebapplication-not-working-if-spadminv4-service-is-run-by-local-system

http://sharepoint.stackexchange.com/questions/110928/spadminv4-which-could-not-be-contacted-in-deployment

Term Store in sharepoint 2013 using powershell

Error Current user has insufficient permissions to perform this operation

To resolve the issue:

•Go the Central Administration

•Go to : “Manage service applications” ( _admin/serviceapplications.aspx).

•Select “Managed Metadata Service” to get the Terms Store admin interface.

•In the section : “Term Store Administrators”. Add the user that you use to run sharepoint management shell

•Save the changes.

In SharePoint 2013 Enterprise, I followed the steps above, but it still didn’t work.

Following on from there, I went to the ‘Term Store Management Tool’ in Central Admin (/_layouts/15/termstoremanager.aspx) and added the user there too. This resolved the permissions issue for me.

Cmdlets Sharepoint and Powershell

http://blog.falchionconsulting.com/index.php/tag/cmdlets/page/2/

Read Logging Files Sharepoint

Reading the log file.

The simplest way is opening the log files from the 14$\logs in Notepad. This might be quickest way but not the most efficient in a live multiuser environment. I usually use this in a development environment in combination with a text editor that automatically reloads the file when it’s updated (Notepad++).

Using powershell with a correlation id

You can use powershell to quickly track down a correlation ID and dump the related log files into a file

1

get-splogevent -starttime (get-date).addminutes(-20) | where-object { $_.correlation -eq “b66db71a-3257-4470-adf9-5c01dc59ecb3″ } | fl message > c:\errors.txt

More info can be found here :
http://www.mysharepointadventures.com/2011/08/175/

Uls viewer

A Windows application for viewing the ULS logs more easily. Very handy when you are (trying to) reproduce a specific error and during debugging
I use it when I’m trying to track down a specific error and during debugging.

http://ulsviewer.codeplex.com/

image.png

Farm solution

Codeplex also has a nice solution which you can query the SharePoint logs with from within Central Administration.
The solution installs in your Central Administration. Very handy if you want a quick look in your logs files without having to connect over remote desktop to the actual server.
For detailed log digging this tool might not be sufficient.

http://sp2010getcorrelation.codeplex.com/

Visual Studio Integrated ULS Viewer
https://integrateduls.codeplex.com/Wikipage?ProjectName=integrateduls

tool.png

 

References:
http://sharepoint.stackexchange.com/questions/73022/cannot-create-a-group-in-term-store-using-powershell-current-user-has-insuffic
http://sharepoint.stackexchange.com/questions/7868/best-way-to-get-reference-to-local-sitecollection-term-store-group
http://blog.amtopm.be/2010/12/27/error-occurred-in-deployment-step-activate-features-the-current-user-has-insufficient-permissions-to-perform-this-operation/

http://blog.amtopm.be/2012/02/21/read-logging-files-in-sharepoint/

http://blog.falchionconsulting.com/index.php/tag/cmdlets/page/2/

http://sharepointlearningcurve.blogspot.com.es/2010/04/sharepoint-2010-installation-account.html

Posted in .NET, PowerShell, Scripts, Sharepoint | Etiquetado: , , , , | Leave a Comment »

Troubleshooting VSIX

Posted by kiquenet en 11 agosto 2014

VSIX Best Practices

This post is about a new way to install extensions to Visual Studio, introduced in VS 2010, called the VSIX file. The information it contains will be of most interest to readers who develop Visual Studio extensions, but I encourage users who download and install those extensions to read it as well.

A VSIX file conforms to the ECMA Open Packaging Conventions (OPC) standard. It’s created as part of a VSIX project build in Visual Studio, and you can view its contents with any zip file utility. If you upload your VSIX to the Visual Studio Gallery, your customer can install it right in Visual Studio, in the new Extension Manager:

image

It can also be installed by downloading and double clicking on the file, and uninstalled either in the Extension Manager, or by simply deleting the associated files. You can find introductory information about VSIX here and here.

The VSIX feature comes with a lot of options. In most cases you don’t have to understand them all. This post is a list of tips that will give you some guidance about how to use the new VSIX capabilities in the best way. Here’s what I’m going to talk about:

  • How to package your extension into a VSIX in the simplest way
  • How to install via MSI if you need to
  • How to use VSIX versioning
  • What to avoid

Packaging your extensions using VSIX

  • Use strong names for all your assemblies. You don’t want your “util.dll” to collide with somebody else’s; if you don’t use strong names the system won’t distinguish between them, and somebody will get a run time error.
  • Distribute your whole product in one independent VSIX if you can. The feature does allow one VSIX to depend on another. But, save that for situations where each one is developed and shipped separately, because shipping a single VSIX will reduce the amount of information you have to understand.
  • If you ship more than one VSIX, and they share common assemblies, copy the common assemblies into each separate VSIX. This has the effect of shipping your whole product in one VSIX described above. There’s no runtime harm in shipping copies of common assemblies – in memory the CLR will only load one:
    image
    But be aware that it will load only one, and the first one loaded wins. So you should ship updates to all your VSIXs that contain common assemblies together.
  • If your product is extending another extension, then your VSIX needs to take a dependency on the target VSIX using either the Select Installed Extension or Manual Reference choice in the dialog below (which you raise by clicking the Add Reference button in the VSIX Manifest Editor).
    image
    image
    In this case
    • Read the Versioning section below to understand the best way to specify the version of your target VSIX in this dialog.
    • Stay aware of your target extension’s updates, and test to make sure your extension is still compatible with each update.
  • If your VSIX publishes an API that another VSIX will use
    • Read the versioning section below to understand how your users will expect your versioning to behave.
    • Maintain binary compatibility between versions if you can; this just makes life simpler for your extenders.
    • Keep your extenders aware of approaching updates so they can test against them. Make sure they know in advance if you plan to release a version that breaks compatibility.

Installing via MSI

Some extensions still need to be installed by MSI: for example some of your files might have to be in a specific, well-known location, you might have a component like an MSBuild task that VSIX install doesn’t support, you might need to use binding redirection – see more information here. There’s no problem with doing that. In fact, we provide a way for an MSI installed extension to make itself visible in the new Extension Manager, so that the customer can see all his extensions in one place.

To make your extension visible in the Extension Manager, your MSI install should create a subdirectory in the Extensions directory for the hosting product:

For a non-administrative, per-user install (recommended) in Visual Studio, the path will look like this:
        Users\user id\AppData\Local\Microsoft\VisualStudio\10.0\Extensions\your company\extension name\version\
and for a per-machine install:
        Program Files\VS 10.0 install directory\Common7\Ide\Extensions\your company\your extension name\version\
An Isolated Shell application will define its own Extension directory.

In that folder, put the extension.vsixmanifest file built by your VSIX project, with an added element that marks it as installed by MSI:

 <Identifier Id="VSIXProject2.Microsoft IT.8532242f-afdc-44fa-82b2-0b6b5afc1c38">
    <Name>VSIXProject2</Name>
<InstalledByMsi>true</InstalledByMsi>


</Identifier>

Note that although the user will then see the extension in the Extension Manager, since it’s installed by MSI, he still needs to manage it through Windows Add/Remove Programs.

Versioning

If your extension is self-contained (i.e. you distribute it in a single VSIX that doesn’t have any dependencies on other ones), and no other VSIXs will depend on yours (i.e. your VSIX doesn’t expose any APIs), you don’t need to read this section. If your VSIX does offer or consume APIs, or you distribute multiple VSIXs with common shared assemblies, read on for more information.

First, let’s do a quick review of how versioning works in the CLR. For an assembly with a strong name, its CLR identity comes from a combination of the file name on disk, Assembly Version string, an optional cultural attribute, and a digital signature. When one assembly references (i.e. consumes APIs from) another one, the consumer is targeted to a particular version of the referenced assembly at build time. (Binding redirection can change this at run time, but the VSIX installer doesn’t support that yet.) The version string contains four segments: <major version>.<minor version>.<build number>.<revision> (for example “1.2.123.0”). The recommended convention for using the version string is that when an assembly’s API breaksbinary compatibility, the major version is incremented. (Note that I’m talking about Assembly Version, which is part of the strong name, not Assembly File Version, which is purely informational – you can use Assembly File Version any way you like. See more information here.)

That’s all background information. Now let’s talk about using versioning with VSIX files. The first thing I’m going to recommend, although it probably sounds a little unexpected, is that you not change the Assembly Version strings when you ship an update of your VSIX. This is because, as I mentioned above, the VSIX installer doesn’t support binding redirection yet, so if you do change any segment of an assembly version number, you may break downstream VSIXs that depend on the old version number of your assembly. The VSIX file has its own mechanism for version management, and I recommend that you use that one instead, because its added flexibility gets you around the binding redirection issue.

For a VSIX that uses an API from another VSIX:

The syntax of a VSIX version string is the same as the assembly one, and we will use the recommended convention to indicate that a new release breaks binary compatibility with the old one: incrementing the major version number. The big advantage of the VSIX versioning mechanism is that if you’re consuming an API from another VSIX, you can specify a range of version numbers of the target VSIX that you’re compatible with. Let’s see how this works. When you raise the Add VSIX Reference dialog in the VSIX Manifest Editor:

image

image

in the Version fields just above, you can specify a range between minimum and maximum version numbers that you’re compatible with. If the developer of the VSIX whose API you consume obeys the versioning conventions, you can specify a range like from Min 1.0 to Max 1.9999 to indicate that you will use any version of your dependency between those two. When the VSIX you depend on installs, for example, version 1.2, you will be compatible with it. When the user attempts to install 2.0, the installer will recognize the incompatibility:

image

and display a warning dialog:

image

If the user updates the extension you depend on anyway, your extension will be disabled because of the incompatibility, and he should look for an update from you that’s compatible with the new version of the API.

If for any reason you believe you are dependent on a specific version of the target extension, you can code that number as the Min and Max values to target only that version:

image

If you only code the Min value, you will bind to anything equal or higher. I don’t recommend that, because binary compatibility breakage (in the example below, from 1.x to 3.0) can lead to run time errors.

image

For a VSIX that offers an API to other VSIXs:

If you release an extension that offers an API, you should handle the versioning at the VSIX level. This means leaving the Assembly Version string unchanged across releases, and incrementing your VSIX version number (shown in the VSIX manifest editor below).

image

It’s great for your consumers if your API can maintain binary compatibility across releases. If you need to break compatibility, increment the major version number. But at that point, when the VSIX installer upgrades your extension, all the consumers of your API will have to ship releases that are compatible with the new API.

Things to avoid:

    • Embedding one VSIX inside another (using the Add payload selection in the Add VSIX Reference dialog). 
      image

      In the current version of Visual Studio, certain combinations of embedded VSIXs and version updates don’t install properly. This feature should be avoided for now; the safest practice is to install VSIXs that have a dependency relationship separately.

Summary

In this article we looked at a set of recommendations for using the new VSIX feature. What I want to leave you with is: minimize complexity. Take advantage of the new VSIX features as you need them, but keep your life as simple as possible by using only the features you need. That way the VSIX install experience will be simple for your customers, which is the  reason VSIX was invented.

How VSIX extensions are discovered and loaded in VS 2010

is the new technology used for deploying extensions in Visual Studio 2010. The primary goal of this new technology is to encourage extension creation and consumption by easing the management (“management” meaning Browsing/Installing/Uninstalling/Enabling/Disabling) of Visual Studio extensions. To take full advantage of the VSIX installer for deploying your extensions, it helps to know a little bit more about how Visual Studio decides which extensions to load.

Dmitry Goncharenko provided a good high-level overview of how these VSIX extensions are discovered and loaded in his post Bootstrapping of VS packages and VSIX extensions in VS2010. Let’s now take a more in-depth look at how this process works.

An extension consists of:

  1. an extension.vsixmanifest file, which contains metadata about the extension
  2. any additional files that represent the extension content. This could include MEF assemblies, VS Package assemblies, VS Template ZIP files, PkgDef files, etc..

The simplest vsix extension would contain only the extension.vsixmanifest file, though that would admittedly be a very uninteresting extension.

Extension Discovery

In accordance with the goal of simplicity, a VSIX extension install consists of only copying the extension files into one of a few well-known locations. These locations are defined in the “Master PkgDef” file, located at <VsInstallRootFolder>\Common7\IDE\devenv.pkgdef and pictured below.

MasterPkgDef

The relevant values are described below.

Variable

Description

ApplicationExtensionsFolder

The root folder under which machine wide VSIXs are deployed.

(This is set as <VsInstallRootFolder>\Common7\IDE\Extensions)

UserExtensionsRootFolder

The root folder under which user specific VSIXs are deployed.

(This is set as %LocalAppData%\Microsoft\VisualStudio\10.0\Extensions)

PkgDefSearchPath

A list of additional folders where extensions will be searched for. The name for this property was originally defined by the PkgDef subsystem. This list is shared with vsix extensions so that any extensions that contain .pkgdef files will be properly loaded. Note that this includes ApplicationExtensionsFolder.

Upon initialization, the Extension Manager service, SVsExtensionManager, will search the above locations for extension.vsixmanifest files. The PkgDefSearchPath folders are searched first, followed by the UserExtensionsRootFolder.

Extension Loading Rules

At this point, each extension must pass a few trials before being considered installed by the Extension Manager. Before diving into the details, here’s a quick summary of these:

  • The extension.vsixmanifest XML conforms to the XSD.
  • The extension has not been marked for deletion.
  • The extension’s identifier cannot conflict with any other previously discovered extensions.

First, if the extension.vsixmanifest XML does not conform to the VSIX manifest XSD schema, it is ignored. If the manifest XML passes schema validation, then it will be deserialized into an object model in memory. Second, the Extension Manager needs to verify that the extension is not marked for deletion. Before going any further, it would be helpful to discuss what exactly this means.

If you’ve uninstalled an extension through the Extension Manager dialog in Visual Studio, you may have noticed that the uninstall occurs extremely fast. This is because the extension is only marked for deletion at that time. On a subsequent initialization of the Extension Manager (the next time Visual Studio or the VSIX Installer are launched), all of the pending deletions are cleaned up on a background thread *after* all installed extensions have been discovered. Therefore, any extension that is marked for deletion should be discarded and no longer considered installed.

Third, if the extension contains the same ID as another extension that has already been discovered, it will be discarded. This is where the search order becomes important. The UserExtensionsRootFolder is searched last in order to give precedence to machine wide extensions when an ID conflict is encountered.

Once an extension has passed these checks, it is considered “installed” by the Extension Manager service. Figuring out whether an extension is not installed because of one of the above reasons is easy since the Extension Manager logs this information to the Visual Studio activity log. The activity log can be enabled by running the Visual Studio process (<VsInstallRootFolder>\Common7\IDE\devenv.exe) with the ‘/log’ switch, as follows:

devenv.exe /log <path_to_log_file>

The Mechanics of Enabled/Disabled Extensions

So your extension is successfully “installed”, but how does the Extension Manager determine whether it’s “Enabled”? The answer depends upon where your extension is installed. Extensions installed to any directory in the PkgDefSearchPath list of folders are always enabled. Extensions installed to the UserExtensionsRootFolder path must be individually enabled through a list maintained in the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\ExtensionManager\EnabledExtensions registry key. TheExtension Manager Install API, used by the extension install dialog as well as the VSIX installer, will write the entry in the EnabledExtensions key for any newly installed extension so that extensions installed in this manner are automatically enabled. You’ll notice that if you manually install an extension by copying the extension files to a subfolder in the UserExtensionsRootFolder path, it will be disabled at first because the corresponding entry in EnabledExtensions has not been added. Enabling the extension can also be accomplished through the Extension Manager dialog.

Enable

Lastly, extensions in the UserExtensionsRootFolder path will all be disabled when running Visual Studio as an administrator, if the following option is not checked under Tools->Options->Environment->Extension Manager

Options

This option was likely the most common culprit for why users (particularly administrators running WindowsXP) found that their extensions were not enabled in Beta2 and prior builds of Visual Studio, since the default value for the option was ‘False’. Due to the frequency with which customers ran into this problem, we’ve changed the default value for this option to ‘True’. Note that the Extension Manager dialog provides a warning if you’re running Visual Studio elevated, but do not have this option checked.

AdminMessage

When in doubt about why an extension does not seem to be loaded or enabled, you should consult the Visual Studio activity log, which will output various diagnostics during the loading process. You may also want to check out the following posts related to extension loading:


References:

http://blogs.msdn.com/b/visualstudio/archive/2010/06/09/vsix-best-practices.aspx?Redirected=true

http://blogs.msdn.com/b/visualstudio/archive/2010/02/19/how-vsix-extensions-are-discovered-and-loaded-in-vs-2010.aspx

Posted in VisualStudio | Etiquetado: , | Leave a Comment »

Environment Variables

Posted by kiquenet en 11 agosto 2014

  • Variable– a term primarily known from programming. A variable is a memory space (storage) for a predefined type of data. A variable always has a name and represents some data or objects. In programming and in the Windows environment, there exist predefined variables that have been set by the creators to be used by the system or the user For example, using a string to the variable %SYSTEMROOT% you will get the path to Windows directory. Besides predefined variables, you can create your own, or they can be created and modified according to the requirements of a program or user. In case of a virus or incorrect variable values the system or program may not work correctly.
  • Environment Variables – predefined variables that are intended for saving system settings or string. Most variables are saved in Windows registry and most of them are set during the installation of the system or upon a user’s or program’s request. In the Windows system, you can either see user variables representing particular settings of each user or system variables intended for the system and all users. You can recognize the variable environment very easily – there is the "percentage" (%) character in front and behind the variable (%Variable%).

Variable management

  • Right click the icon Computer – Properties – Advanced – Environment Variables

Environment Variables

By marking a variable or using buttons you can add, modify or remove some variables

edit environment variables

Example of editing the "windir" variable after clicking the Edit button.

  • TIP: If we want to add a new variable MW in user variables with the value c:\MUJWEB, you can go to Start – Run and type %MW% to open a window with the content of the c:\MUJWEB directory.
  • Displaying and editing in the command line using the "set" command

C:\set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\adminxp\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
COMPUTERNAME=ADMINXP-PC
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\adminxp
LOCALAPPDATA=C:\Users\adminxp\AppData\Local
LOGONSERVER=\\ADMINXP-PC
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 15 Model 79 Stepping 2, AuthenticAMD
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=4f02
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PROMPT=$P$G
PUBLIC=C:\Users\Public
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\adminxp\AppData\Local\Temp
TMP=C:\Users\adminxp\AppData\Local\Temp
USERDOMAIN=adminxp-PC
USERNAME=adminxp
USERPROFILE=C:\Users\adminxp
windir=C:\Windows

Example of displaying the settings of some system variables in the command line using the "set" command. For help, use the command "set /?".

To display particular variables, even those that are not visible after using the "set" command, you can use the "echo" command. E.g. echo %ALLUSERSPROFILE%

To modify, use the syntax SET [variable=[string]] – e.g. SET MW=C:\MUJWEB

  • Some values can be changed directly in the registry or through graphical environment and system tools or using other applications.
  • Changes can be made through login scripts or other scripts and batch commands (autoexec.bat in older systems).

List of primary variables of Windows Vista and Windows XP

%ALLUSERSPROFILE%
Path to the All User profile
Vista – C:\ProgramData
WindowsXP – C:\Documents and Settings\All Users

%APPDATA%
Path to the Application Data folder
Vista – C:\Users\%USERNAME%\AppData\Roaming
WindowsXP – C:\Documents and Settings\%USERNAME%\Application Data

%CD%
Path to the current directory.

%CMDCMDLINE%
Path to the launched operation in the Command Line / Cmd.exe program (C:\WINDOWS\system32\cmd.exe)

%CMDEXTVERSION%
Version number of the current Command Processor Extensions

%commonprogramfiles%
Path to the Common Files folder (Ex. C:\Program Files\Common Files)

%COMPUTERNAME%
Computer name

%COMSPEC%
Path to the command interpreter

%DATE%
Current date

%ERRORLEVEL%
Error code for the last used command (0 means OK)

%HOMEDRIVE%
Current home drive letter (according to the home directory)

%HOMEPATH%
Full path to the user’s home folder.

%HOMESHARE%
Full network path to the user’s home folder.

%LOCALAPPDATA%
(ex. C:\Users\%USERNAME%\AppData\Local)

%LOGONSERVER%
Name of the domain controller that validated the domain logon. If the domain is not available, name of the computer is displayed.

%NUMBER_OF_PROCESSORS%
Number of processors in the computer

%OS%
Name of the OS family (ex. Windows_NT – the same for XP and Vista)

%PATH%
Path to executable files. (if you define an executable program, it is launched without the need of specifying the full path).

%PATHEXT%
File types that are set as executable in the operating system.

%PROCESSOR_ARCHITECTURE%
Processor’s architecture. (x86, IA64)

%PROCESSOR_IDENTFIER%
Processor’s description.

%PROCESSOR_LEVEL%
Processor’s model number

%PROCESSOR_REVISION%
Version number of the processor’s hardware

%ProgramData%
New in Vista (ex. C:\ProgramData). The same as %ALLUSERSPROFILE%.

%PROGRAMFILES%
Path to the Program Files directory. (ex. C:\Program Files)

%PROMPT%
Setup of the current command intepreter (e.g. $P$G, more with "prompt /?")

%PUBLIC%
Represents the public folder for shared data (data which must be visible for all users within a computer or network). Newly in Vista (C:\Users\Public).

%RANDOM%
Generates a random decimal number within the range from 0 to 32767.

%SYSTEMDRIVE%
Denotes the drive that contains the root directory of the Windows system (ex. c:)

%SYSTEMROOT%
Location of the root directory of the operating system.

%TEMP% a %TMP%
Folder for temporary data. Some applications invoke the folder with the variable %TMP%, others use %TEMP%. (ex. C:\Users\%USERNAME%\AppData\Local\Temp)

%TIME%
Current time

%USERDOMAIN%
Name of the domain that contains the account of the currently logged in user. If the user is not a member of the domain, name of the computer will be displayed.

%USERNAME%
Name of the currently logged in user

%USERPROFILE%
Location of the current user’s profile

%WINDIR%
Location of the operating system directory. %SYSTEMROOT% is a newer variable. %WINDIR% is used by older systems and applications.

Saving data and variables for all users – registry for Windows XP

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

Common AppData
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Application Data

Common Desktop
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Desktop

Common Documents
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Documents

Common Favorites
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Favorites

Common Programs
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Start Menu\Programs

Common Start Menu
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Start menu

Common Startup
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Start Menu\Programs\Startup

Common templates
REG_EXPAND_SZ
%ALLUSERSPROFILE%\Templates

Saving data and variables for all users – registry for Windows Vista

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\User Shell Folders

Common AppData
REG_EXPAND_SZ
%ProgramData%

Common Desktop
REG_EXPAND_SZ
%PUBLIC%\Desktop

Common Documents
REG_EXPAND_SZ
%PUBLIC%\Documents

CommonMusic
REG_EXPAND_SZ
%PUBLIC%\Music

CommonPictures
REG_EXPAND_SZ
%PUBLIC%\Pictures

Common Programs
REG_EXPAND_SZ
%ProgramData%\Microsoft\Windows\Start Menu\Programs

Common Start Menu
REG_EXPAND_SZ
%ProgramData%\Microsoft\Windows\Start Menu

Common Startup
REG_EXPAND_SZ
%ProgramData%\Microsoft\Windows\Start Menu\Programs\Startup

Common templates
REG_EXPAND_SZ
%ProgramData%\Microsoft\Windows\Templates

CommonVideo
REG_EXPAND_SZ
%PUBLIC%\Videos

{3D644C9B-1FB8-4f30-9B45-F670235F79C0}
REG_EXPAND_SZ
%PUBLIC%\Downloads

Saving data and variables for all users – registry for Windows XP

Key: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurentVersion\Explorer\User Shell Folders

AppData
REG_EXPAND_SZ
%USERPROFILE%\Application Data

Cache
REG_EXPAND_SZ
%USERPROFILE%\Local Settings\Temporary Internet Files

Cookies
REG_EXPAND_SZ
%USERPROFILE%\Cookies

Desktop
REG_EXPAND_SZ
%USERPROFILE%\Desktop

Favorites
REG_EXPAND_SZ
%USERPROFILE%\Favorites

History
REG_EXPAND_SZ
%USERPROFILE%\Local Settings\History

LocalAppData
REG_EXPAND_SZ
%USERPROFILE%\Local Settings\Application Data

Local Settings
REG_EXPAND_SZ
%USERPROFILE%\Local Settings

My Pictures
REG_EXPAND_SZ
%USERPROFILE%\My Documents\My Pictures

NetHood
REG_EXPAND_SZ
%USERPROFILE%\NetHood

Personal
REG_EXPAND_SZ
%USERPROFILE%\My Documents

PrintHood
REG_EXPAND_SZ
%USERPROFILE%\PrintHood

Programs
REG_EXPAND_SZ
%USERPROFILE%\Start Menu\Programs

Recent
REG_EXPAND_SZ
%USERPROFILE%\Recent

SendTo
REG_EXPAND_SZ
%USERPROFILE%\SendTo

Start Menu
REG_EXPAND_SZ
%USERPROFILE%\Start Menu

Startup
REG_EXPAND_SZ
%USERPROFILE%\Start Menu\Programs\Startup

Templates
REG_EXPAND_SZ
%USERPROFILE%\Templates

Saving data and variables for all users – registry Windows Vista

Key: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

AppData
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming

Cache
REG_EXPAND_SZ
%USERPROFILE%\AppData\Local\Microsoft\Windows\Temporary Internet Files

Cookies
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Cookies

Desktop
REG_EXPAND_SZ
%USERPROFILE%\Desktop

Favorites
REG_EXPAND_SZ
%USERPROFILE%\Favorites

History
REG_EXPAND_SZ
%USERPROFILE%\AppData\Local\Microsoft\Windows\History

LocalAppData
REG_EXPAND_SZ
%USERPROFILE%\AppData\Local

My Music
REG_EXPAND_SZ
%USERPROFILE%\Music

My Pictures
REG_EXPAND_SZ
%USERPROFILE%\Pictures

My Video
REG_EXPAND_SZ
%USERPROFILE%\Videos

NetHood
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Network

Personal
REG_EXPAND_SZ
%USERPROFILE%\Documents

PrintHood
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Printer

Programs
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start

Recent
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Recent

SendTo
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\SendTo

Startup
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start

Start Menu
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start

Templates
REG_EXPAND_SZ
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Templates

{374DE290-123F-4565-9164-39C4925E467B}
REG_EXPAND_SZ
%USERPROFILE%\Downloads

References:
http://www.adminxp.com/windowsvista/index.php?aid=235

Posted in Sistemas | Etiquetado: | Leave a Comment »

Servicios de dominio de Active Directory Windows Server 2012 controlador dominio

Posted by kiquenet en 11 agosto 2014

Referencia muy buena en Ajpdsoft respecto Active Directory y Windows Server 2012

Artículo realizado íntegramente por Alonsojpd miembro fundador del Proyecto AjpdSoft.

Tutorial donde explicamos cómo instalar el rol Servicios de dominio de Active Directory en un servidor con Microsoft Windows Server 2012. Mostramos los requisitos necesarios para promocionar un equipo a controlador de dominio con Active Directory, entre ellos cómo instalar el rol de Servidor DNS.

Videotutorial Cómo instalar rol Dominio Active Directory Windows Server 2012 R2 controlador de dominio

A continuación mostramos un videotutorial donde explicamos cómo instalar el rol de Servicios de Dominio de Active Directory en un equipo con Microsoft Windows Server 2012 R2. Promocionaremos el servidor con Active Directory a Controlador de Dominio. Este rol también instalará el rol de servidor de DNS:

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

En este tutorial explicaremos cómo instalar el rol Servicios de dominio de Active Directory en un servidor con el sistema operativo Microsoft Windows Server 2012. Puesto que será el primer servidor del dominio, se creará como controlador principal de dominio con el catálogo global. Esta acción creará un nuevo dominio.

Para promocionar un servidor a controlador de dominio e instalar el rol Servicios de dominio de Active Directory necesitaremos un equipo con el sistema operativo W2012, en el siguiente tutorial explicamos cómo instalar este sistema operativo:

Para instalar el rol de Servicios de dominio de Active Directory el equipo con W2012 debe cumplir, al menos, los siguientes requisitos.

Establecer dirección IP estática en servidor Windows Server 2012

1. El servidor W2012 debe disponer de una dirección IP fija (estática) y no establecida por DHCP. Para asegurarnos de ello, pulsaremos la tecla "Windows" del teclado o la combinación de teclas Control + Escape para mostrar el nuevo menú de inicio metro de W2012, pulsaremos en "Panel de control":

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

Pulsaremos en "Centro de redes y recursos compartidos:

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

Pulsaremos en "Ethernet" en "Conexiones":

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

Pulsaremos en "Propiedades" en la ventana de "Estado de Ehernet":

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

Seleccionaremos "Protocolo de Internet versión 4 (TCP/IPv4)" y pulsaremos en "Propiedades":

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

Comprobaremos que tenemos asignada una dirección IP estática (no debe estar marcada la opción "Obtener una dirección IP automáticamente):

Requisitos iniciales para instalar Servicios de dominio de Active Directory y promoción a controlador de dominio W2012

Instalar rol de Sevidor de DNS en Windows Server 2012

Para instalar el rol o característica de Servicios de dominio de Active Directory el servidor W2012 requerirá del rol "Servidor DNS" instalado. Para instalarlo (si aún no lo hemos hecho) pulsaremos la tecla "Windows" del teclado o la combinación de teclas Control + Escape, en el menú de Inicio metro pulsaremos en "Administrador del servidor":

Instalar rol de Sevidor de DNS en Windows Server 2012

Pulsaremos en el menú "Administrar" y seleccionaremos "Agregar roles y características":

Instalar rol de Sevidor de DNS en Windows Server 2012

Marcaremos el rol "Servidor DNS":

Instalar rol de Sevidor de DNS en Windows Server 2012

El rol "Serviodor DNS" requerirá de la característica "Herramientas de administración remota del servidor" – "Herramientas de administración de roles" – "Herramientas del servidor DNS". Nos lo indicará en la ventana de agregar características requeridas, marcaremos "Incluir herramientas de administración (si es aplicable)":

Instalar rol de Sevidor de DNS en Windows Server 2012

Con "Servidor DNS" marcado pulsaremos "Siguiente":

Instalar rol de Sevidor de DNS en Windows Server 2012

El asistente para agregar roles y características nos indicará las características que se instalarán, pulsaremos "Siguiente":

Instalar rol de Sevidor de DNS en Windows Server 2012

El asistente para instalar el rol de Servidor DNS nos indicará algunas cuestiones a tener en cuenta, pulsaremos "Siguiente":

Instalar rol de Sevidor de DNS en Windows Server 2012

Con el texto: El Sistema de nombres de dominio (DNS) proporciona un método estándar para asociar nombres a direcciones de Internet numéricas. De esta forma, los usuarios pueden hacer referencia a los equipos de la red usando nombres fáciles de recordar en lugar de largas series de números. Además, DNS proporciona un espacio de nombres jerárquico, lo que garantiza que cada nombre de host será único en una red de área local o extensa. Los servicios DNS de Windows pueden integrarse con los servicios de Protocolo de configuración dinámica de host (DHCP) en Windows, de forma que ya no es necesario agregar registros DNS cuando se agregan equipos a la red. Cosas para tener en cuenta:

  • La integración del servidor DNS con los Servicios de dominio de Active Directory replica automáticamente los datos DNS y otros datos del servicio de directorio. Esto facilita la administración de DNS.
  • Los Servicios de dominio de Active Directory requieren la instalación de un servidor DNS en la red. Si está instalando un controlador de dominio, también puede instalar el rol de servidor DNS seleccionando el rol Servicios de dominio de Active Directory con el Asistente para la instalación de Servicios de dominio de Active Directory.

El asistente para agregar roles y características nos indicará las características y roles elegidos para la instalación, pulsaremos "Instalar":

Instalar rol de Sevidor de DNS en Windows Server 2012

Se iniciará la instalación del rol de Servidor DNS, el asistente nos indicará el progreso del proceso:

Instalar rol de Sevidor de DNS en Windows Server 2012

El asistente para agregar roles y características nos indicará que el proceso ha finalizado con el texto "Instalación correcta en XXX". Pulsaremos "Cerrar":

Instalar rol de Sevidor de DNS en Windows Server 2012

Pulsando en el botón "Inicio" podremos comprobar que se ha añadido un nuevo acceso directo llamado "DNS", pulsaremos sobre él:

Instalar rol de Sevidor de DNS en Windows Server 2012

Desde "Administrador de DNS" podremos consultar y administrar el servicio de DNS del servidor W2012:

Instalar rol de Sevidor de DNS en Windows Server 2012

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Para instalar el rol de Servicios de dominio de Active Directory en un servidor con Windows Server 2012 el equipo deberá cumplir los requisitos que indicamos aquí. En nuestro caso este servidor será el primero del dominio, por lo que al agregar el rol de Servicios de dominio de Active Directory se creará el dominio indicado y este servidor será controlador principal de dominio con el catálogo global.

Para instalar el rol de Servicios de dominio de Active Directory en W2012 pulsaremos el botón "Inicio" (o la combinación de teclas Control + Escape), en el menú Inicio pulsaremos en "Administrardor del servidor":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

En el Administrador del servidor pulsaremos en "Agregar roles y características":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Con el texto: Este asistente le ayuda a instalar roles, servicios de rol o características. Podrá elegir qué roles, servicios de rol o características desea instalar según las necesidades de los equipos de la organización, como compartir documentos u hospedar un sitio web. Para quitar roles, servicios de rol o características inicie el Asistente para quitar roles y características. Antes de continuar, compruebe que se han completado las siguientes tareas:

  • La cuenta de administrador tiene una contraseña segura.
  • Las opciones de red, como las direcciones IP estáticas, están configuradas.
  • Las actualizaciones de seguridad más recientes de Windows Update están instaladas.

Si debe comprobar que se ha completado cualquiera de los requisitos previos anteriores, cierre el asistente, complete los pasos y, después, ejecute de nuevo el asistente.

Marcaremos la opción "Instalación basada en características o roles" y pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Con el texto: Seleccione el tipo de instalación. Puede instalar roles y características en un equipo físico, en una máquina virtual o en un disco duro virtual (VHD) sin conexión.

  • Instalación basada en características o en roles: para configurar un solo servidor, agregue roles, servicios de rol y características.
  • Instalación de Servicios de Escritorio remoto: instale los servicios de rol necesarios para que la infraestructura de escritorio virtual (VDI) cree una implementación de escritorio basada en máquinas o en sesiones.

Marcaremos "Seleccionar un servidor del grupo de servidores", seleccionaremos el servidor SRVAJPDSOFT (el servidor que corresponda) , pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Marcaremos "Servicios de dominio de Active Directory":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

El rol de "Servicios de dominio de Active Directory" requiere de otras características, por lo que si no están instaladas nos lo indicará en la ventana de agregar características requeridas para Servicios de dominio de Active Directory, estas características son "Herramientas de AD DS y AD LDS", "Módulo de Active Directory para Windows PowerShell". Marcaremos "Incluir herramientas de administración (si es aplicable)" y pulsaremos "Agregar características":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Tras marcar "Servicios de dominio de Active Directory" y sus características requeridas pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

El asistente para agregar roles y características de W2012 nos mostrará las características que se instalarán, requeridas para el rol Servicios de dominio de Active Directory, pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

El Asistente para agregar roles y características nos mostrará algunas advertencias, las leeremos y comprobaremos que nuestro servidor cumple los requisitos y pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Con el texto: Servicios de dominio de Active Directory (AD DS) almacena información acerca de los usuarios, los equipos y otros dispositivos de la red. AD DS ayuda a los administradores a administrar esta información de forma segura y facilita el uso compartido de recursos y la colaboración entre usuarios. AD DS también se requiere en aplicaciones habilitadas para el uso de directorios como Microsoft Exchange Server y otras tecnologíasde Windows Server como la directiva de grupo. Observaciones:

  • Para ayudar a garantizar que los usuarios puedan iniciar sesión en la red en caso de una interrupción en el servidor, instale un mínimo de dos controladores de dominio para un dominio.
  • AD DS requiere la instalación de un servidor DNS en la red. Si no hay un servidor DNS instalado, se le pedirá que instale el rol de servidor DNS en este servidor.
  • Al instalar AD DS, también se instalarán los servicios de espacio de nombres DFS, replicación DFS y replicación de archivos requeridos por el servicio de directorio.

El Asistente para agregar roles y características nos mostrará todos los roles y características elegidas para la instalación, pulsaremos "Instalar":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Se iniciará la instalación, el asistente nos mostrará el progreso del proceso:

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Tras la instalación de Servicios de dominio de Active Directory el asistente nos indicará que ha concluido, pulsaremos "Cerrar":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

En la ventana de Administrador del servidor nos aparecerá una advertencia, pulsaremos en el triángulo amarillo de advertencia y pulsaremos en "Promocionar este servidor a controlador de dominio":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Se iniciará el asistente para configuración de Servicios de dominio de Active Directory. Puesto que sólo tenemos un servidor y es el primero marcaremos "Agregar un nuevo bosque", introduciremos el nombre del dominio, por ejemplo "ajpdsoft.local.com":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

El asistente nos mostrará el nivel funcional del bosque y dominio raíz, con las posibilidades: Windows Server 2012, Windows Server 2003, Windows Server 2008, Windows Server 2008 R2, las capacidades del controlador de dominio y la contraseña para restauración de servicios de directorio (DSRM). Especificaremos el nivel funcional para indicar si queremos compatibilidad con sistemas anteriores, en nuestro caso dejaremos "Windows Server 2012" pues todos los servidores serán W2012. Marcaremos "Servidor de Sistema de nombres de dominio (DNS)", "Catálogo global (GC)". Introduciremos una contraseña para modo de restauración y pulsaremos "Siguiente":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Es posible que nos muestre una advertencia indicando que "No se puede crear una delegación para este servidor DNS porque la zona principal autoritativa no e encuentra". Marcaremos "Crear delegación DNS", si no tenemosinstalado el rol de Sevidor de DNS tal vez aparezca deshabilitada dicha opción:

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Y nos mostrará el siguiente mensaje, pulsaremos "Aceptar":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Con el texto: No se puede crear una delegación para este dominio DNS porque la zona principal autoritativa no se encuentra o no ejecuta el servidor DNS de Windows. Si está realizando una integración en una infraestructura DNS existente, debe crear manualmente una delegación a este servidor DNS en la zona principal para garantizar una resolución de nombres confiable desde fuera del dominio "ajpdsoft.local.com". De lo contrario no es preciso realizar ninguna acción.

Estableceremos el nombre NetBIOS para el dominio que se creará, por defecto el asistente usará la primera parte del nombre del dominio especificado anteriormente, en nuestrocaso "ajpdsoft":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

A continuación podremos elegir la ubicación (unidad y carpeta) donde se guardará la base de datos, los archivos de registro y la carpeta SYSVOL, por defecto:

  • La carpeta de la base de datos: C:/Windows/NTDS
  • La carpeta de archivos de registro: C:/Windows/NTDS
  • La carpeta SYSVOL: C:/Windows/SYSVOL

El asistente para configuración de Servicios de dominio de Active Directory nos mostrará todas las opciones elegidas. Desde aquí podremos ver el script que generará dicha configuración pulsando en "Ver script":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

El script de Windows PowerShell para implementación de AD DS será:

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

#
# Script de Windows PowerShell para implementación de AD DS
#

Import-Module ADDSDeployment
Install-ADDSForest `
-CreateDnsDelegation:$false `
-DatabasePath "C:/Windows/NTDS" `
-DomainMode "Win2012" `
-DomainName "ajpdsoft.local.com" `
-DomainNetbiosName "AJPDSOFT" `
-ForestMode "Win2012" `
-InstallDns:$true `
-LogPath "C:/Windows/NTDS" `
-NoRebootOnCompletion:$false `
-SysvolPath "C:/Windows/SYSVOL" `
-Force:$true

El asistente para configuración de Servicios de dominio de Active Directory nos indicará todas las advertencias relacionadas con requisitos previos que debe cumplir el servidor, si no son grabes podremos continuar con el proceso. Por supuesto deberemos leer y resolver las advertencias de requisitos previos que sean necesarias. Pulsaremos "Instalar":

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Algunas advertencias típicas:

  • Los controladores de dominio de Windows Server 2012 tienen un valor predeterminado para la configuración de seguridad llamada "Permitir algoritmos de criptografía compatibles con Windows NT 4.0" que impiede los algoritmos de criptografía más vulnerables al establecer las sesiones del canal de seguridad. Para obtener más información acerca de esta configuración consulte el artículo 942564.
  • Este equipo tiene al menos un adaptador de red físico que no tiene asignadas direcciones IP estáticas en sus propiedades IP. Si se habilitan IPv4 e IPv6 en un adaptador de red, se deben asignar direcciones IP estáticas IPv4 e IPv6 a las propiedades IPv4 e IPv6 del adaptador de red físico. Estas direcciones IP se deben asignar a todos los adaptadores de red físicos para lograr un funcionamiento confiable del Sistema de nombres de dominio (DNS).
  • No se puede crear una delegación para este servidor DNS porque la zona principal autoritativa no se encuentra o no ejecuta el servidor DNS de Windows. Si está realizando una integración en una infraestructura DNS existente, debe crear manualmente una delegación a este servidor DNS en la zona principal para garantizar una resolución de nombres confiable desde fuera del dominio "ajpdsoft.local.com". De lo contrario, no es preciso realizar ninguna acción.

Tras la instalación del rol Servicios de dominio de Active Directory y tras configurar Servicios de dominio de Active Directory en el Administrador del servidor podremos ver el estado del rol AD DS:

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Pulsando la combinación de teclas Control + Escape o la tecla "Windows" del teclado, en el menú de Inicio metro, tendremos los accesos directos para administrar Active Directory:

  • Administración de directivas de grupo.
  • Módulo de Active Directory para Windows PowerShell.
  • Editor ADSI.
  • Dominios y confianzas de de Active Directory.
  • Usuarios y equipos de Active Directory.
  • Centro de administración de Active Directory.
  • Sitios y servicios de Active Directory.

Instalar rol de Servicios de dominio de Active Directory en Windows Server 2012

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

Tras instalar el rol de Servicios de dominio de Active Directory podremos crear todos los objetos necesarios para nuestro dominio (impresoras, carpetas compartidas, usuarios, unidades organizativas, alias, grupos, contatos, equipos). Para crear una unidad organizativa pulsaremos la tecla "Windows" del teclado (o las teclas Control + Escape), en el menú de Inicio pulsarmos en "Usuarios y equipos de Active Directory":

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

En el árbol de la izquierda pulsaremos con el botón derecho del ratón sobre el servidor "ajpdsoft.local.com", en el menú desplegable pulsaremos en "Nuevo" – "Unidad organizativa":

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

Introduciremos un nombre para la unidad organizativa, por ejemplo "uoDesarrollo" y pulsaremos "Aceptar":

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

Las unidades organizativas servirán como contenedor para otros objetos de Active Directory como usuarios, equipos, impresoras, … También servirán para establer directivas diferentes por unidad organizativa.

Para agregar un nuevo usuario al dominio Active Directory pulsaremos con el botón derecho del ratón sobre la unidad organizativa en la que queramos crearlo, seleccionaremos "Nuevo" – "Usuario":

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

Introduciremos los datos para el usuario (nombre, iniciales, apellidos, nombre completo, nick o nombre de inicio de sesión):

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

Introduciremos la contraseña para el nuevo usuario, estableceremos las opciones para la contraseña y pulsaremos "Siguiente":

Añadir unidad organizativa y usuario en Active Directory en servidor con Windows Server 2012

Pulsaremos "Finalizar" y el usuario quedará creado para iniciar sesión en el servidor W2012 o bien para iniciar sesión en cualquier equipo agregado al dominio, incluso para cualquier aplicacion que admita validación en LDAPy Active Directory. En el siguiente tutorial explicamos cómo agregar un equipo tanto Windows XP como Microsoft Windows 7 a un dominio para que valide el inicio de sesión en él:

Consultar qué servidor es el controlador principal de dominio en Windows Server 2012

Para consultar qué servidor de todos los miembros del dominio es el controlador principal (el que tiene todos los roles), en Windows Server 2012 pulsaremos la tecla "Windows" del teclado (o Control + Escape), pulsaremos en "Usuarios y equipos de Active Directory":

Consultar qué servidor es el controlador principal de dominio en Windows Server 2012

Pulsaremos con el botón derecho del ratón sobre el servidor, en nuestro caso "ajpdsoft.local.com", en el menú emergente seleccionaremos "Maestro de operaciones":

Consultar qué servidor es el controlador principal de dominio en Windows Server 2012

En esta ventana podremos consultar qué servidor del dominio es el Maestro de Operaciones:

  • RID: el Maestro de operaciones administra la asignación de grupos RID a otros controladores de dominio, sólo un servidor en el dominio puede realizar este rol.
  • Controlador principal de dominio: el maestro de operaciones emula las funciones de un controlador de dominio principal (PDC) para clientes con versiones anteriores a Windows 2000.
  • Infraestructura: el Maestro de Infraestructura asegura la consistencia de objetos para operaciones entre dominios.

Consultar qué servidor es el controlador principal de dominio en Windows Server 2012

Consultar qué servidor es el controlador principal de dominio en Windows Server 2012

Consultar qué servidor es el controlador principal de dominio en Windows Server 2012

Referencias:
http://www.ajpdsoft.com/modules.php?name=News&file=article&sid=626

Posted in Sistemas | Etiquetado: , | Leave a Comment »

CCO– Copia de Carbón Oculta–BCC–Blind Carbon Copy

Posted by kiquenet en 11 agosto 2014

Ver más en http://concopiaoculta.osi.es/

Destacado Con Copia Oculta

Quien te ha recomendado esta página quiere que, cuando envíes un correo a múltiples destinatarios protejas su privacidad y evites divulgar sus direcciones de correo innecesariamente. Para ello, con el apoyo de la Oficina de Seguridad del Internauta (OSI), te mostraremos cómo utilizar la opción «Con Copia Oculta (CCO)» del correo electrónico.

Ordenador virus


Copia de carbón oculta
o con copia oculta1 2 3 (CCO) es un campo del encabezado de un mensaje de correo electrónico. A diferencia del campo Para (o A) y la casilla CC, las direcciones de correo electrónico añadidas a CCOpermanecen invisibles a los destinatarios del mensaje. En algunos proveedores de correo es necesario hacer clic en un enlace del encabezado para que aparezca este campo ("Añadir CCO", "Mostrar CCO" o "Mostrar CC: y CCO:"). Si no se tradujo del inglés lo encontraremos por BCC (Blind Carbon Copy, "Copia de Carbón Ciega", si se traduce literalmente). Desde las opciones de estos proveedores suele ser posible hacer que esta casilla aparezca automáticamente. Esta casilla se usa con diferentes objetivos:

  • Para enviar una copia del mensaje a una tercera persona sin que el destinatario principal lo sepa (o cuando no se quiere que el destinatario principal conozca la dirección electrónica de dicha tercera persona).
  • Para enviar o reenviar un mensaje a varios destinatarios sin que cada uno de ellos reciba las direcciones electrónicas de los demás. Esto es una precaución anti correo masivo, virus (y otro tipo de malware), bulos ysuplantación de identidad porque evita que los destinatarios propaguen gran cantidad de direcciones de correo electrónico (que es lo que ocurre si se ponen las direcciones en los campos Para o CC), con el riesgo de que caigan en manos de remitentes de correo masivo y /o de virus (u otro tipo de badware), hoax y mensajes con suplantación de identidad. Por esta razón, a menudo tiene sentido usar CCO en las listas de correo.

CCO también se usa a veces para que cierto tipo de correo masivo parezca más auténtico. Al esconder la dirección del destinatario el expendedor del mensaje espera engañarlo y hacerle creer que ha recibido accidentalmente un mensaje de correo electrónico (sobre una oferta que supuestamente lo hará millonario, por ejemplo) que no iba dirigido a él.

En principio (salvo en algunos proveedores de correo web) es posible enviar un mensaje a todas las direcciones como CCO, sin que necesariamente deba ponerse algo en el campo Para, algunos rellenan el campo con "Destinatarios ocultos" (‘Undisclosed recipients en inglés)’. Sin embargo, en caso de que el cliente de correo exija escribir un destinatario en este campo, la recomendación más habitual es utilizar la dirección del propio remitente del correo, o una dirección falsa, de esta manera se preserva la privacidad de todos los destinatarios.

¿Qué significan los campos CC y CCO en un mensaje de correo de Outlook?

CC

CC es la abreviatura de Con copia. Si agrega el nombre de un destinatario en este cuadro de un mensaje de correo de Microsoft Outlook®, se enviará una copia del mensaje a ese destinatario y los demás destinatarios del mensaje podrán ver su nombre.

CCO

CCO es la abreviatura de Con copia oculta. Si agrega el nombre de un destinatario en este cuadro de un mensaje de correo, se enviará una copia del mensaje a ese destinatario y los demás destinatarios del mensaje no podrán ver su nombre. Si el cuadro CCO no está visible al crear un nuevo mensaje, se puede agregar. En el menú Ver del mensaje, haga clic en Campo CCO.

Referencias:

http://es.wikipedia.org/wiki/Copia_de_carb%C3%B3n_oculta
http://concopiaoculta.osi.es/

https://support.google.com/mail/answer/57143?hl=es
http://office.microsoft.com/es-es/outlook-help/que-significan-los-campos-cc-y-cco-en-un-mensaje-de-correo-de-outlook-HA001056513.aspx

Posted in Curiosidades | Etiquetado: , , | Leave a Comment »

Introducing MSMQ–MS Queues

Posted by kiquenet en 6 agosto 2014

MSMQ uses flat files located in %windir%\system32\msmq.

If you want to implement your own queueing, I suggest you take a look at Ayende’s blog post on queueing

 

Surviving poison messages in MSMQ

http://www.cogin.com/articles/SurvivingPoisonMessages.php

Purgue:

Invoke-Command -ComputerName "mycomputer" -ScriptBlock {

        ## if public then $queuename = ".\YOUR_Q_NAME" 
        $queuename = ".\private$\YOUR_Q_NAME"  

        [Reflection.Assembly]::LoadWithPartialName("System.Messaging") | Out-Null
        $queue = New-Object -TypeName "System.Messaging.MessageQueue"
        $queue.Path = $queuename 
        $messagecount = $queue.GetAllMessages().Length
        $queue.Purge()
        Write-Host "$queuename has been purged of $messagecount messages."
    }
 
Write-Host ""
Write-Host "Examples using the .NET System.Messaging assembly to access MSMQ"
Write-Host ""

Write-Host "... load the .NET Messaging assembly"
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")

Write-Host ""

if ([System.Messaging.MessageQueue]::Exists(".\private$\MyQueue"))
  {
  [System.Messaging.MessageQueue]::Delete(".\private$\MyQueue")
  Write-Host "... delete old myqueue"
  }
if ([System.Messaging.MessageQueue]::Exists(".\private$\BtsQueue"))
  {
  [System.Messaging.MessageQueue]::Delete(".\private$\BtsQueue")
  Write-Host "... delete old btsqueue"
  }

Write-Host "... create a new queue"
$q1 = [System.Messaging.MessageQueue]::Create(".\private$\MyQueue")

Write-Host "... create new queue, set FullControl permissions for RBC\BIZTALK"
$qb = [System.Messaging.MessageQueue]::Create(".\private$\BtsQueue")

$qb.SetPermissions("RBC\BIZTALK", 
      [System.Messaging.MessageQueueAccessRights]::FullControl,            
      [System.Messaging.AccessControlEntryType]::Set)

Write-Host "... list existing queues" 
$pqs = [System.Messaging.MessageQueue]::GetPrivateQueuesByMachine(".")
Write-Host "    Count: "$pqs.length  -ForegroundColor gray
foreach($q in $pqs)
  {
    Write-Host "       "$q.QueueName  -ForegroundColor gray
  }

Write-Host "... access existing queue"
$q2 = New-Object System.Messaging.MessageQueue ".\private$\MyQueue"

Write-Host "... adding string Formatter and additional properties "
$q2.Formatter.TargetTypeNames = ,"System.String"
$q2.MessageReadPropertyFilter.ArrivedTime = $true 
$q2.MessageReadPropertyFilter.SentTime = $true 

Write-Host "... create a new High priorty message "
$msg = New-Object System.Messaging.Message "TestMessage"
$msg.label = "Test Msg Label"
$msg.body = "Add some body to test message"
$msg.priority = [System.Messaging.MessagePriority]::High

Write-Host "... send the High message"
$q2.send($msg)

$msg.body = "Some more text for the test message"
$msg.priority = [System.Messaging.MessagePriority]::Low

Write-Host "... send the Low message"
$q2.send($msg)

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length  -ForegroundColor gray

Write-Host "... peek at queue"
$ts = New-Object TimeSpan 10000000 # 1 sec. timeout just in case MSMQ is empty
$pk = $q2.Peek($ts)
Write-Host "    ArrivedTime: "$pk.ArrivedTime.DateTime -ForegroundColor gray
Write-Host "    SentTime   : "$pk.SentTime.DateTime -ForegroundColor gray

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length -ForegroundColor gray

Write-Host "... receive from queue"
$rmsg = $q2.receive($ts)
Write-Host "    Body : "$rmsg.body  -ForegroundColor gray
Write-Host "    Label: "$rmsg.label -ForegroundColor gray

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length  -ForegroundColor gray

Write-Host "... purge the queue "
$q2.Purge()

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length  -ForegroundColor gray

Write-Host ""
Write-Host "All done, but remember to delete the test queues !!"

Queue Journal



var systemJournalQueue = new MessageQueue("FormatName:Direct=os:.\\System$;JOURNAL"); var systemDeadLetterQueue = new MessageQueue("FormatName:Direct=os:.\\System$;DEADLETTER"); var systemDeadXLetterQueue =new MessageQueue("FormatName:Direct=os:.\\System$;DEADXACT")); systemJournalQueue.Purge();
private static void PurgeQueues(int archiveAfterHowManyDays, MessageQueue queue)
{
    queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });
    queue.MessageReadPropertyFilter.ArrivedTime = true;

    using (MessageEnumerator messageReader = queue.GetMessageEnumerator2())
    {
        int counter = 0;
        while (messageReader.MoveNext())
        {
            Message m = messageReader.Current;
            if (m.ArrivedTime.AddDays(archiveAfterHowManyDays) < DateTime.Now)
            {
                queue.ReceiveById(m.Id);
                counter++;
            }
        }
    }
}

http://www.meadow.se/wordpress/retrieving-the-message-count-is-msmq-queues/comment-page-1/#comment-473136
http://jopinblog.wordpress.com/2008/03/12/counting-messages-in-an-msmq-messagequeue-from-c/

$queues = Get-WmiObject Win32_PerfFormattedData_msmq_MSMQQueue
$queues | ft -property Name,MessagesInQueue

$host = ...
$cred = get-credential
$queues = Get-WmiObject Win32_PerfFormattedData_msmq_MSMQQueue -computer $host -credential $cred
$queues | ft -property Name,MessagesInQueue
private static int GetMsmqMessageCount(string queuePath, string machine,
  string username, string password)
{
  var options = new ConnectionOptions
    {Username = username, Password = password};
  var path = string.Format(@"\\{0}\root\CIMv2", machine);
  var scope = new ManagementScope(path, options);
  scope.Connect();

  string queryString = 
    String.Format("SELECT * FROM Win32_PerfFormattedData_msmq_MSMQQueue WHERE Name = '{0}'",
	  queuePath);
  var query = new ObjectQuery(queryString);

  var searcher = new ManagementObjectSearcher(scope, query);

  IEnumerable<int> messageCountEnumerable = 
    from ManagementObject queue in searcher.Get()
    select (int) (UInt64) queue.GetPropertyValue("MessagesInQueue");

  return messageCountEnumerable.First();
}
 

References:
http://stackoverflow.com/questions/802661/how-does-msmq-manage-messages?rq=1

http://stackoverflow.com/questions/25011855/how-purge-messages-from-ms-queue-in-remote-server-using-script
http://stackoverflow.com/questions/765954/setting-permissions-on-a-msmq-queue-in-script/915127#915127
http://stackoverflow.com/questions/11533690/how-message-get-purged-from-poison-queue-in-msmq
http://stackoverflow.com/questions/1063378/msmq-how-to-purge-system-queue-journal-programaticaly
http://stackoverflow.com/questions/11793441/purge-msmq-queue-and-reset-iis-from-a-bat-file

http://stackoverflow.com/questions/20344562/create-private-message-queue-on-remote-machine
http://blogs.msdn.com/b/johnbreakwell/

xcopy, zero administration, queuing service
http://ayende.com/blog/3480/rhino-queues

Posted in .NET, Comandos | Etiquetado: , | Leave a Comment »

PSExec Troubleshooting

Posted by kiquenet en 6 agosto 2014


Version PsExec v2.11


PsExec \\SERVER -u myDomain\UserDeployTFS -p xxx cmd.exe /v /c
time /t

PsExec \\SERVER -u myDomain\UserDeployTFS -p xxx cmd.exe /v /c echo ^%computername^%

Useful commands:

Checked the ports used by PSExec, 445 and 135, and both are open on the SERVER machine (nc is a unix commad)

nc –z SERVER 445
nc –z SERVER 135

Telnet SERVER 445

net user administrator /enable:yes

runas /user:myDomain\UserDeployTFS cmd

cmdkey.exe /add: SERVER /user:myDomain\UserDeployTFS /pass:XXXX

cmdkey.exe /delete: SERVER

all network based authentication/credentials between the two computers with differing clocks will fail. Local accounts will still be able to login. If you use something like psexec and instead of using your domain credentials, you specify valid administrative credentials on the local machine, it should connect just fine and allow you to fix the clock.

schtasks.exe /create /F /S $RemoteHost /ru domain\User /rp password /tn Sync-Time /sc Once /st $NowPlusOneMinute /tr "w32tm /resync"

PsExec needs the local administrator account on windows to be enabled. Recent Windows(following linux) has made this account default set to disabled(the logic is the same as for ‘sudo’ in linux: security). Enable this account by the following command(run command prompt as administrator)…

net user administrator /enable:yes

set the network credentials:
cmdkey /list:%DOMAIN% | find "%DOMAIN_USER%" >NUL || cmdkey /add:%DOMAIN% /user:%DOMAIN%\%DOMAIN_USER% /pass:%DOMAIN_USER_PWD% >>%LOGFILE% 2>>&1

Runas was not possible with local shares and other permissions.

Errors:

Couldn’t access SERVER:

Access is denied.

http://stackoverflow.com/questions/25035759/access-denied-using-psexec-when-connect-to-remote-server

http://serverfault.com/questions/616583/access-denied-using-psexec-when-connect-to-remote-server

References:

http://serverfault.com/questions/489822/psexec-is-not-connecting-to-machine-using-supplied-username-and-password/489845

http://serverfault.com/questions/216466/cannot-access-client-pc-remotely-due-to-time-date-issue-xp-win2k3-environment

http://stackoverflow.com/questions/20373885/psexec-and-windows-2008-server-access-denied

http://stackoverflow.com/questions/18791468/psexec-win7-to-win7-access-denied-psexesvc-remains

Posted in Comandos, Errores, Scripts | Etiquetado: , | Leave a Comment »