Category Archives: Code Snippets

Code Snippets IIS

IIS: Redirect to another domain

Redirect from any page of www.mysite1.com to a static root of another site www.mysite2.com

 

<rule name="site2.com" stopProcessing="true">
             <match url=".*" />
             <conditions>
                 <add input="{HTTP_HOST}" pattern="^(.*)?site1.com" />                 
             </conditions>
             <action type="Redirect" url="http://www.site2.com/{R:0}" />
</rule>
Code Snippets ASP.Net IIS

SSL Redirect URL, rewrite rule

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.webServer>
	<rewrite>
		<rules>
			<rule name="Redirect to http" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
				<match url="*" negate="false" />
				<conditions logicalGrouping="MatchAny">
					<add input="{HTTPS}" pattern="off" />
				</conditions>
				<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
			</rule>
		</rules>
	</rewrite>
  </system.webServer>
</configuration>

read more »

Code Snippets

Exporting AD user list

> dsquery user -name * -limit 0 >> c:\users.txt

Code Snippets .NET ASP.Net

UnobtrusiveValidationMode requires a ScriptResourceMapping for ‘jquery’ – Asp.NET

erro:

Erro de Servidor no Aplicativo '/'.

WebForms UnobtrusiveValidationMode requer um ScriptResourceMapping para 'jquery'. Adicione um jquery nomeado de ScriptResourceMapping (diferencia maiúsculas de minúsculas).

Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código. 



Adicionar no web.config

 <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
  </appSettings><span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>
Code Snippets Active Directory PowerShell

PowerShell: Get-ADUser to retrieve password last set and expiry information

Get-ADUser -identity username -properties *
 get-aduser -filter * -properties passwordlastset, passwordneverexpires |ft Name, passwordlastset, Passwordneverexpires
get-aduser -filter * -properties passwordlastset, passwordneverexpires | sort name | ft Name, passwordlastset, Passwordneverexpires

Export the list to CSV so we can work on it in Excel. In this example we substitute, format table (ft) for select-object.

Type:

Get-ADUser -filter * -properties passwordlastset, passwordneverexpires | sort-object name | select-object Name, passwordlastset, passwordneverexpires | Export-csv -path c:\temp\user-password-info-20131119.csv

PowerShell: Get-ADUser to retrieve password last set and expiry information


read more »

Code Snippets Exchange PowerShell

Turn Exchange Anonymous Relay On or Off or View Connector Status

This EMS script for Exchange 2007-2016 allows Exchange Administrators to toggle anonymous external relay permissions on front-end Receive Connectors. Connectors listed in Yellow allow anonymous SMTP emails to any internal or external recipients. Connectors listed in White only

Toggle-ExternalRelayReceiveConnectors


C:\_tmp>.\Toggle-ExternalRelayReceiveConnectors.ps1

Toggle External Relay

1 - SRV-EXCH2\Client Frontend EXSERVER1
2 - SRV-EXCH2\Default Frontend EXSERVER1
3 - SRV-EXCH2\Outbound Proxy Frontend EXSERVER1
X - Exit

Which Receive Connector to toggle:

This EMS script for Exchange 2007-2016 allows Exchange Administrators to toggle anonymous external relay permissions on front-end Receive Connectors. Connectors listed in Yellow allow anonymous SMTP emails to any internal or external recipients. Connectors listed in White only allow SMTP emails to internal recipients. Run this script from the Exchange Management Shell.

See my blog for more information: http://www.expta.com/2016/01/turn-exchange-anonymous-relay-on-or-off.html

read more »

Code Snippets Office365 PowerShell

Office 365 : Password Sync doesn’t synchronize with Azure AD Connect

Verified password sync is disabled via using PowerShell

Following cmdlets have been used to verify above and I noticed password sync was in fact disabled although I checked the option in Azure AD connect setup.

Import-Module ADSync
Get-ADSyncAADPasswordSyncConfiguration -SourceConnector <‘LOCAL DOMAIN NAME>

Enabled password sync via PowerShell

Set-ADSyncAADPasswordSyncConfiguration -SourceConnector <‘LOCAL DOMAIN NAME> -TargetConnector <‘xxxxxxx.onmicrosoft.com – AAD’> -Enable $true

 

thanks to: http://www.tekronin.net/2015/10/09/office-365-woes-password-sync-doesnt-synchronize-with-azure-ad-connect/

Office 365 woes | Password Sync doesn’t synchronize with Azure AD Connect

Code Snippets .NET VB

Dynamically Generate and Display Barcode Image in ASP.Net

n this article I will explain how to dynamically generate and display barcode image using ASP.Net in C# and VB.Net languages.
 
Barcode Font
First you will need to download the Free Barcode Font from the following URL
Once downloaded follow the following steps.
1. Extract the ZIP file.
2. Click and Execute INSTALL.exe file.
3. After installation is completed restart your machine.



 

<form id="form1" runat="server">
<asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
<asp:Button ID="btnGenerate" runat="server" Text="Generate" onclick="btnGenerate_Click" />

<hr />

<asp:PlaceHolder ID="plBarCode" runat="server" />
</form>




 


 
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO

 

 


Protected Sub btnGenerate_Click(sender As Object, e As EventArgs)
    Dim barCode As String = txtCode.Text
    Dim imgBarCode As New System.Web.UI.WebControls.Image()
    Using bitMap As New Bitmap(barCode.Length * 40, 80)
        Using graphics__1 As Graphics = Graphics.FromImage(bitMap)
            Dim oFont As New Font("IDAutomationHC39M", 16)
            Dim point As New PointF(2.0F, 2.0F)
            Dim blackBrush As New SolidBrush(Color.Black)
            Dim whiteBrush As New SolidBrush(Color.White)
            graphics__1.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height)
            graphics__1.DrawString("*" & barCode & "*", oFont, blackBrush, point)
        End Using
        Using ms As New MemoryStream()
            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
            Dim byteImage As Byte() = ms.ToArray()
 
            Convert.ToBase64String(byteImage)
            imgBarCode.ImageUrl = "data:image/png;base64," & Convert.ToBase64String(byteImage)
        End Using
        plBarCode.Controls.Add(imgBarCode)
    End Using
End Sub

 

 

 

 

https://www.aspsnippets.com/Articles/Dynamically-Generate-and-Display-Barcode-Image-in-ASPNet.aspx

Code Snippets

Tips for Coding Email Preheaders

Hidden preheader text

here are a lot of designs that just won’t accommodate visible preheader text, or it become undesirable for branding reasons. If you’d like to add hidden preheader text to your email, don’t worry, it’s not hard!
To begin with, you’ll want to pick a place where the preheader text won’t cause issues in your layout. Usually the text will take up, at most, one pixel of vertical space, but in some cases this can bump down content. If you’re putting the preheader text into an existing header, you may want to give it a row to itself, so that if any content below is moved, it will all be moved the same amount.
To hide the text, you’ll want to include the following inline styles:


<td style="display:none !important; visibility:hidden; mso-hide:all; font-size:1px; color:#ffffff; line-height:1px; max-height:0px; max-width:0px; opacity:0; overflow:hidden;">
  This is preheader text.            
</td>

As you can see, I have hidden the text in a multitude of ways. Many of these are fallbacks for clients that don’t recognize or play nicely with some of the other styles in the list.

One tip from my own personal experience: Don’t put placeholder text here! You may want to add placeholder text for testing, but make sure to remove it after. The last thing you want is for an email to go out with “This is preheader text” as the actual preheader text… unless you are intentionally making a “This is Spinal Tap” reference. It’s much better to have an email go out with no preheader text than with placeholder text.

Preheader character limits

Just how much preheader text should you include? We recommend 50-100 characters. Though some clients are capable of showing more than this, it’s usually only under special circumstances (like a very wide browser window). Check out this chart to see the limits of some popular email clients.

Preheader Character Limits

Email Client Limit
iPhone (5S) 64
Gmail (Web Client) 100
Gmail (iOS Client, 5S) 34
iPad 5, Mail App 64
Android 4.4 97
Apple Mail 8 50-100
Outlook 2013 60-100
Outlook.com 124-236
Yahoo! Mail 135-202

source:
https://www.emailonacid.com/blog/article/email-development/tips-for-coding-email-preheaders

Code Snippets SQL Server Transact-SQL

DBCC SHRINKFILE (Transact-SQL)

A. Shrinking a data file to a specified target size

The following example shrinks the size of a data file named DataFile1 in the UserDB user database to 7 MB.


USE UserDB;
GO
DBCC SHRINKFILE (DataFile1, 7);
GO

B. Shrinking a log file to a specified target size

The following example shrinks the log file in the AdventureWorks database to 1 MB. To allow the DBCC SHRINKFILE command to shrink the file, the file is first truncated by setting the database recovery model to SIMPLE.


USE AdventureWorks2012;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2012
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2012_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2012
SET RECOVERY FULL;
GO

C. Truncating a data file

The following example truncates the primary data file in the AdventureWorks database. The sys.database_files catalog view is queried to obtain the file_id of the data file.


&nbsp;

USE AdventureWorks2012;
GO
SELECT file_id, name
FROM sys.database_files;
GO
DBCC SHRINKFILE (1, TRUNCATEONLY);

D. Emptying a file

The following example demonstrates the procedure for emptying a file so that it can be removed from the database. For the purposes of this example, a data file is first created and it is assumed that the file contains data.


USE AdventureWorks2012;
GO
-- Create a data file and assume it contains data.
ALTER DATABASE AdventureWorks2012
ADD FILE (
NAME = Test1data,
FILENAME = 'C:\t1data.ndf',
SIZE = 5MB
);
GO
-- Empty the data file.
DBCC SHRINKFILE (Test1data, EMPTYFILE);
GO
-- Remove the data file from the database.
ALTER DATABASE AdventureWorks2012
REMOVE FILE Test1data;
GO

https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-shrinkfile-transact-sql