How can I check if my .net application is running on Windows 2003 Server?
Because Buildnumber 5.2 is Windows XP and also windows Server 2003.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx
So I need a different check.
Can someone help me?
Environment.OSVersion only gives you the version of the kernel which is the same in XP and Server 2003, so you can't really tell them apart.
However, as far as I'm concerned, they are almost identical in what features they support. If you tell us why you need to know the difference, what feature you'd like to test, we might be able to help more.
Okay guys,
I coded something that should detect if the OS is a windows server.
If so, it should return true:
Private ReadOnly Property IsWindowsServer() As Boolean
Get
Const VER_NT_WORKSTATION As Byte = &H1
Const VER_PRODUCT_TYPE As UInteger = &H80
Const VER_EQUAL As Byte = 1
Dim osvi As New OSVERSIONINFOEX()
osvi.dwOSVersionInfoSize = CUInt(Marshal.SizeOf(osvi))
osvi.wProductType = VER_NT_WORKSTATION
Dim dwlConditionMask As ULong = VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL)
Return Not VerifyVersionInfo(osvi, VER_PRODUCT_TYPE, dwlConditionMask)
End Get
End Property
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Structure OSVERSIONINFOEX
Public dwOSVersionInfoSize As Integer
Public dwMajorVersion As Integer
Public dwMinorVersion As Integer
Public dwBuildNumber As Integer
Public dwPlatformId As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128)> _
Public szCSDVersion As String
Public wServicePackMajor As UInt16
Public wServicePackMinor As UInt16
Public wSuiteMask As UInt16
Public wProductType As Byte
Public wReserved As Byte
End Structure
<DllImport("kernel32.dll")> _
Private Function VerSetConditionMask(dwlConditionMask As ULong, dwTypeBitMask As UInteger, dwConditionMask As Byte) As ULong
End Function
<DllImport("kernel32.dll")> _
Private Function VerifyVersionInfo(<[In]> ByRef lpVersionInfo As OSVERSIONINFOEX, dwTypeMask As UInteger, dwlConditionMask As ULong) As Boolean
End Function
I need someone who can check this on different Windows Servers and check if it returns true or not.
I f you test, please write the OS-Server Build Number or Name here, so I know if it works for different versions ^^
U can check like this:
MsgBox(IsWindowsServer())
The best way to do this IMO is to use WMI. The Win32_OperatingSystem class contains a property ProductType which is 1 for workstation OS and 2 or 3 for server OS.
I'm no good at VB.NET, maybe someone else can convert this C# for you:
public static bool IsServerOS()
{
return IsServerOS(Environment.MachineName);
}
public static bool IsServerOS(string computerName)
{
ConnectionOptions options = new ConnectionOptions() { EnablePrivileges = true, Impersonation = ImpersonationLevel.Impersonate };
ManagementScope scope = new ManagementScope(string.Format(#"\\{0}\root\CIMV2", computerName), options);
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
using (ManagementObjectCollection results = searcher.Get())
{
if (results.Count != 1) throw new ManagementException();
uint productType = (uint)results.OfType<ManagementObject>().First().Properties["ProductType"].Value;
switch (productType)
{
case 1:
return false;
case 2:
return true;
case 3:
return true;
default:
throw new ManagementException();
}
}
}
Related
First let me tell you I'm new to the .NET world, but have been Software Emgineer for 16 years, so I'm not new to coding. I ran across something that has me baffled, and maybe a more seasoned .NET developer might know what is causing a perfomance issue of my COM object. I have spent days browsing through forums with no luck, I decide to seek help by putting this post together. I have developed my .NET code in VS 2010 using C#. I know, the IDE is little aged. The code is pretty simple. The main method takes the Certificates encoded string, converts it to a byte format, and passes that to the X509Certificate object. I then use the objects method to get the expiration date. I also added a memory clean-up class hoping it would solve my problem. It did not.
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Runtime.InteropServices; //Need for API
namespace CertificationInfo
{
//Certification Class
public class CertificateInformation
{
//[DllImport("kernel32.dll")]
//public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
//Class Attributes
//private X509Certificate CertificateObject;
public string CertificateData;
public string ExpirationDate;
private MemoryManagement MemMngr;
//Constructor
public CertificateInformation()
{
//Reset Expiration Date
this.ExpirationDate = "";
MemMngr = new MemoryManagement();
}
//Method
public string GetCertExpirationDate(string rawdata)
{
try
{
//Clean Up Memory
this.MemMngr.ReleaseMemory();
//Reset Expiration Date Property
this.ExpirationDate = "";
//Check for data
if (rawdata == "" && this.CertificateData == "")
{
//Nothing is passed & property is blank
this.ExpirationDate = "";
}
else
{
//Check for Raw Data value
if (rawdata != "")
{
this.CertificateData = rawdata;
}
//Convert Property Array
//Might be best to use unicode Under Encoding namespace
//System.Text.UnicodeEncoding Encoding0=new System.Text.UnicodeEncoding();
//Byte[] bytedata0=Encoding0.GetBytes(rawdata);
//Convert Property to byte array
System.Text.ASCIIEncoding Encoding = new System.Text.ASCIIEncoding();
Byte[] bytedata = Encoding.GetBytes(this.CertificateData);
//Create Encoding Object
X509Certificate CertificateObject = new X509Certificate(bytedata);
//this.CertificateObject = new X509Certificate(bytedata);
//Might have to check to see iff cert object is null though catch should pick it up
//Get Expiration date
this.ExpirationDate = CertificateObject.GetExpirationDateString();
//Reset Object & Certificate Data Property
CertificateObject = null;
Encoding = null;
this.CertificateData = "";
//Clean Up Memory
this.MemMngr.ReleaseMemory();
}
}
//Error Trapping in case of error still returns something
catch
{
this.ExpirationDate = "";
}
return this.ExpirationDate;
}
}
//API Class to Clean up Memory threads
public class MemoryManagement
{
//Memory Management API
[DllImport("kernel32.dll")]
public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
//Method
public void ReleaseMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
}
}
I moved it into the GAC, and registered it as a DLL on my local machine. I then created a Lotus Script agent, that loops through all my documents(records). In the iteration it pulls a field into a string, passes it to method, and returns the expiration date as a string
%REM
Agent TestDLL
Created Jan 13, 2014 by Keith Wiwel/TPS/PGH/PNC
Description: Comments for Agent
%END REM
Option Public
Option Declare
Sub Initialize
Dim Session As New NotesSession
Dim db As NotesDatabase
Dim view As NotesView
Dim document As NotesDocument
Dim COMObj As Variant
'Counts
Dim TotalCount As Long
Dim MissingDataCount As Long
Dim COMErrorCount As Long
Dim COMSuccessCount As Long
Print "ETH - GetExpirationDLL: Initializing Notes Objects"
Set db=Session.Currentdatabase
Set view=db.Getview("Active Certificates - By Web Site")
Print "ETH - GetExpirationDLL: Initializing COM Object"
Set COMObj=CreateObject("CertificationInfo.CertificateInformation")
TotalCount=0
MissingDataCount=0
COMErrorCount=0
COMSuccessCount=0
Print "ETH - GetExpirationDLL: Start Processing"
Set document=view.Getfirstdocument()
Do Until document Is Nothing
TotalCount=TotalCount+1
Print "Processing..."+CStr(TotalCount)
'Expiration Variables
Dim expirationdate As String
Dim rawdata As String
Dim legacyexpirationdate As String
'Get data & Legacy Values
'rawdata
rawdata=CStr(Trim(document.Getitemvalue("CRT_File")(0)))
legacyexpirationdate=CStr(document.expirationdate(0))
If rawdata="" Then
'Capture Certificates with No CSR Data
document.ExpirationDate=""
If LegacyExpirationDate="" Then
document.LegacyExpirationDate=legacyexpirationdate
End If
document.COMError="Missing CSR"
Call document.Save(True,False)
MissingDataCount=MissingDataCount+1
Else
'Capture Legacy & Certificate Expiration Date
If legacyexpirationdate="" Then
document.LegacyExpirationDate=legacyexpirationdate
End If
Dim Certificatedat As String
CertificateDat=ComObj.CertificateData
'expirationdate=ComObj.ExpirationDate
expirationdate=COMObj.GetCertExpirationDate(rawdata)
Dim CertDate As String
CertDate=ComObj.ExpirationDate
Dim Debug As String
Debug=ComObj.xx
Print "Com expiration:" +CStr(ComObj.ExpirationDate)
If CStr(expirationdate)<>"" Then
'Success - Processing Expiration date
document.ExpirationDate=CStr(expirationdate)
COMSuccessCount=COMSuccessCount+1
Else
'Failed - Processing Expiration date
document.ExpirationDate=CStr(expirationdate)
document.COMError="COM Expiration Failed"
COMErrorCount=COMErrorCount+1
End If
Call document.Save(True,False)
End If
Set document=view.getnextdocument(document)
Loop
'Log Report
Print "ETH - GetExpirationDLL: Processed "+CStr(TotalCount)+" certificates."
Print "ETH - GetExpirationDLL: "+CStr(MissingDataCount)+" certificates had missing CSR data."
Print "ETH - GetExpirationDLL: "+CStr(COMErrorCount)+" certificates failed in the COM Object."
Print "ETH - GetExpirationDLL: "+CStr(COMSuccessCount)+" certificates were succesfully processed."
Print "ETH - GetExpirationDLL: End Processing"
'Delete COMObj
End Sub
The two main lines of code above are:
Set COMObj=CreateObject("CertificationInfo.CertificateInformation")
which creates the COM object. The other is:
expirationdate=expirationdate=COMObj.GetCertExpirationDate(rawdata)
which uses the method to pull the expiration date. As you might have expected, it works fine, however this is where my problem occurs. When I first ran the code it flew, it took roughly 10 minutes to go through 4,000+ records. I had a few anomalies that I wanted to check, so I ran it a couple more times. Each time it degraded, and enventually started crawling. My first thought was it was a memory leak. Since I was running it locally, I decided to turn off the power to the pc see if it cleared. It did not. I also installed it on my laptop to prove to myself it ran smotthly on it's first run. Ran fine on the first one, then perfomance started degrading on consecutive runs. Last day it was running so slow it was over 8+ hours. This is local machine testing so there are is no servers to contend with network traffic. I am at a complete loss, can anyone tell me what is going on? CPU is at 20% when running, and Mem usage for notes2.exe growsa little each time. It slows down when it enters:
expirationdate=expirationdate=COMObj.GetCertExpirationDate(rawdata)
That's the bottleneck. I am completely stuck, does anyone know what is going on?
This is my first attempt in using a card reader in C#, or basically anywhere.
I use ACS ACR122U PICC Interface 0 reader in Windows 7 64bit.
My first problem occurs when I tried to connect to the reader using
ModWinsCard.SCardConnect(hContext, cbReader.SelectedItem.ToString(), ModWinsCard.SCARD_SHARE_DIRECT, 0, ref hCard, ref Protocol);
It returns error code 6, but I googled and solved it by changing project's platform from Any CPU to X86.
Right after that I bumped to another issue, this time in controlling the reader.
I tried with :
_sentBuffer = new byte[]
{
0xFF,
0x00,
0x48,
0x00,
0x00
};
_receivedBuffer = new byte[10];
_receivedBuffer[0] = 0;
_returnCode = ModWinsCard.SCardControl(_hCard, _dwControlCode, ref _sentBuffer[0], _sentBuffer.Length, ref _receivedBuffer[0], _receivedBuffer.Length, ref bytesReturned);
The returned code is 1, which is weird because I can't found it in the documentation.
Really need a hand in this.
Thanks !
Doing some research myself about working with SCardControl and found I was getting the same return value of 1.
I found a list of Error Codes here which then states the below.
"Note Some return values may have the same value as existing Windows return values that signify a similar condition. For information about error codes not listed here, see System Error Codes."
And that documentation states that the error code value 1 is ERROR_INVALID_FUNCTION
I know this question is old but hopefully it will help someone in the future.
I somehow have it solved by downloading the latest driver from the provider's website, with uninstalling the driver that is included in the driver CD.
Still wonder what does return 1 means though..
I know this is an old topic, but I have the same problem on Windows 10 (x64), except I'm using VB6.
I have a lot working through using SCardTransmit etc, I can controle/read/write if there's a card on it. But I want to control the reader (ACR112U) without a card (turn off autodetection/beep) and that's only possible using SCardControl (as far as I know), cause when I connect with Directmode and then call our SetBuzzerCardDetection to turn it off, I get a ERROR_BAD_COMMAND, but when shared and a card it works.
Even the example from ACS themselves with IOCTL_GET_VERSIONS gives me return value ERROR_INVALID_FUNCTION
Dim vcVersion As VERSION_CONTROL
Dim lReturnedLength As Long
m_lResult = SCardControl(m_hCard, _
IOCTL_GET_VERSIONS, _
0, 0, _
vcVersion, 20, _
lReturnedLength)
If m_lResult <> SCARD_S_SUCCESS Then
I'm using the following
Declare Function SCardControl Lib "WinScard.dll" ( ByVal hCard As Long, ByVal dwControlCode As Long, ByRef lpInBuffer As Any, ByVal lSizeofBuffer As Long, ByRef lpReceiveBuffer As Any, ByVal lpReceiveBufferSize As Long, ByRef lpBytesReturned As Long) As Long
Const IOCTL_CCID_ESCAPE As Long = (&H42000000 + 3500)
'hCard is a valid handle returned by SCardConnect
'lReturn = SCardConnect(hContext, sReader, eShareMode, ePreferredProtocol, hCard, eActiveProtocol)
'With card on reader: eShareMode = SCARD_SHARE_SHARED, ePrefferedProtocol = SCARD_PROTOCOL_Tx
'Without card on reader: eShareMode = SCARD_SHARE_DIRECT, ePrefferedProtocol = SCARD_PROTOCOL_UNDEFINED
Dim abIn() As Byte
Dim abOut() As Byte
Dim lInLength As Long
Dim lOutLength As Long
Dim lReturn As Long
Dim lReturnedLength As Long
'Command for turning off Buzzer output during card detection
lInLength = 5
ReDim abIn(lInLength - 1)
abIn(0) = &HFF
abIn(1) = &H0
abIn(2) = &H52
abIn(3) = &H0
abIn(4) = &H0
lOutLength = 256
ReDim abOut(lOutLength - 1)
lReturn = SCardControlAny(hCard, _
IOCTL_CCID_ESCAPE, _
abIn(0), lInLength, _
abOut(0), lOutLength, _
lReturnedLength)
'with card on reader: lReturn = ERROR_BAD_COMMAND
'without card on reader: lReturn = ERROR_INVALID_FUNCTION
Mind you for using Escape I also added the ControlEscapeEnable to the registry (just for the sake of it I added it in several places)
First I did everything without loading a special driver (other than what Windows 10 itself already got), but due to Samuel Adam's remark I loaded the latest from ACS website but it didn't make a difference.
It's really driving me crazy, just like it's also driving me crazy that WebUSB doesn't allow it anymore so I would have been able to use a webbased version.
I'm sure there must be some documentation on MSDN somewhere, but I couldn't find it. It looks like some subset/variation of JSON. Really, this question grew out of something that has always bugged me: what do all the 8:s and 3:s mean? Is this some a version number of some kind? Maybe a typing scheme? Every VDPROJ excerpt I've ever seen is filled with these "eight-colon" and "three-colon" prefixes, but this is not the sort of question search engines are really good for.
"DeployProject"
{
"VSVersion" = "3:800"
"ProjectType" = "8:{978C614F-708E-4E1A-B201-565925725DBA}"
"IsWebType" = "8:FALSE"
"ProjectName" = "8:ProjectNameRedacted"
"LanguageId" = "3:1033"
"CodePage" = "3:1252"
"UILanguageId" = "3:1033"
"SccProjectName" = "8:"
"SccLocalPath" = "8:"
"SccAuxPath" = "8:"
"SccProvider" = "8:"
"Hierarchy"
{
"Entry"
{
"MsmKey" = "8:_02F97BB7BD104F1AAA1C97C854D5DC99"
"OwnerKey" = "8:_UNDEFINED"
"MsmSig" = "8:_UNDEFINED"
}
...
If anyone just wants to berate my pitiful Google-fu, that's fine too.
As #R. Matveev pointed out, the prefix numbers likely indicate the type of data stored in the property. This would be useful when deserializing the file into an object structure.
I doubt the source code which Visual Studio used to read/write the files was ever made open source, so it's no wonder that web searches returned nothing.
The best I could find was this page on OLE Automation data types, which may not have been the actual constants, but the data types seem to match the values in the *.vdproj file.
2.2.7 VARIANT Type Constants
typedef enum tagVARENUM
{
VT_EMPTY = 0x0000,
VT_NULL = 0x0001,
VT_I2 = 0x0002,
VT_I4 = 0x0003, // 4-byte signed integer
VT_R4 = 0x0004,
VT_R8 = 0x0005,
VT_CY = 0x0006,
VT_DATE = 0x0007,
VT_BSTR = 0x0008, // BSTR (string data)
VT_DISPATCH = 0x0009,
VT_ERROR = 0x000A,
VT_BOOL = 0x000B, // Boolean value
VT_VARIANT = 0x000C,
VT_UNKNOWN = 0x000D
...
} VARENUM;
I need to identify if a request comes from Internet or Intranet using either client-side or server-side.
The problem I'm trying to solve is: our web site can be accessed from internet and intranet. The intranet user (user inside company), does not have access to internet. We are using Google Anylitics, when intranet user access the page, the page take so long to upload because it tries to download (ga) JavaScript file generated from Google.
Any solution?
You can check the ip address of a user. Private ip4 address always start with either 10., or 172., or 192.* ... more info on private networks here.
You can also make Google Analytics load Asynchronous.
***************** UPDATE - PLEASE READ *************************************
As #igor-turman has correctly pointed out, that only a portion of the "172" and the "192" address ranges are designated for private use.
The remaining ip addresses starting with 172 and 192 ARE PUBLIC.
Here is the regex expression to check for private IP addresses:
(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)
You can test this regex on regexpal.com here.
This is how I would do the ip check:
string ipString = System.Web.HttpContext.Current.Request.UserHostAddress;
byte[] ipBytes = System.Net.IPAddress.Parse(ipString).GetAddressBytes();
int ip = System.BitConverter.ToInt32(ipBytes, 0);
// your network ip range
string ipStringFrom = "192.168.1.0";
byte[] ipBytesFrom = System.Net.IPAddress.Parse(ipStringFrom).GetAddressBytes();
int ipFrom = System.BitConverter.ToInt32(ipBytesFrom, 0);
string ipStringTo = "192.168.1.255";
byte[] ipBytesTo= System.Net.IPAddress.Parse(ipStringTo).GetAddressBytes();
int ipTo = System.BitConverter.ToInt32(ipBytesFrom, 0);
bool clientIsOnLAN = ipFrom >= ip && ip <= ipTo;
If you have multiple subnets, just do the same for them (from, to), then add to the bool condition above. I just realized that, in your case, the above may be an overkill.
Alternatively, for you, it might be as simple as:
bool isOnLAN = System.Web.HttpContext.Current.Request.UserHostAddress.StartsWith("192.168.1.")
Necromancing:
None of the answers are good or correct.
You can convert the IP (IPv4 only - IPv6 is UInt128) into a UInt32 value, and then you can check if the requesting IP is somewhere in the private IP ranges:
e.g. you can use that to set the cookies to "Secure", if it's not intranet.
For Each thisCookie As System.Web.HttpCookie In response.Cookies
thisCookie.HttpOnly = True
Dim ipString As String = System.Web.HttpContext.Current.Request.UserHostAddress
If Not IPv4Info.IsPrivateIp(ipString) Then
thisCookie.Secure = True
End If
Next thisCookie
VB.NET Class, which you can convert into C# yourselfs (http://converter.telerik.com)
Public Class IPv4Info
Private Class IPv4Range
Public RangeStart As UInt32
Public RangeEnd As UInt32
End Class
' https://en.wikipedia.org/wiki/Private_network
' https://tools.ietf.org/html/rfc1918
' 192.168.0.0 - 192.168.255.255 (65,536 IP addresses)
' 172.16.0.0 - 172.31.255.255 (1,048,576 IP addresses)
' 10.0.0.0 - 10.255.255.255 (16,777,216 IP addresses)
Private Shared Rng127 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("127.0.0.0"), .RangeEnd = GetIpNum("127.255.255.255")}
Private Shared Rng192 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("192.168.0.0"), .RangeEnd = GetIpNum("192.168.255.255")} ' CIDR: 192.168.0.0/16 (255.255.0.0)
Private Shared Rng172 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("172.16.0.0"), .RangeEnd = GetIpNum("172.31.255.255")} ' CIDR: 172.16.0.0/12 (255.240.0.0)
Private Shared Rng10 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("10.0.0.0"), .RangeEnd = GetIpNum("10.255.255.255")} ' CIDR: 10.0.0.0/8 (255.0.0.0)
' http://stackoverflow.com/questions/36831/how-do-you-parse-an-ip-address-string-to-a-uint-value-in-c
Public Shared Function GetIpNum(ipString As String) As UInt32
Dim ipAddress__1 As System.Net.IPAddress = System.Net.IPAddress.Parse("some.ip.address")
Dim ipBytes As Byte() = ipAddress__1.GetAddressBytes()
Dim ip As UInt32 = CUInt(ipBytes(0)) << 24
ip += CUInt(ipBytes(1)) << 16
ip += CUInt(ipBytes(2)) << 8
ip += CUInt(ipBytes(3))
Return ip
End Function
Public Shared Function isIn127(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn127(ip)
End Function
Public Shared Function isIn127(x As UInt32) As Boolean
If x >= Rng127.RangeStart AndAlso x <= Rng127.RangeEnd Then
Return True
End If
Return False
End Function
Public Shared Function isIn192(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn192(ip)
End Function
Public Shared Function isIn192(x As UInt32) As Boolean
If x >= Rng192.RangeStart AndAlso x <= Rng192.RangeEnd Then
Return True
End If
Return False
End Function
Public Shared Function isIn172(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn172(ip)
End Function
Public Shared Function isIn172(x As UInt32) As Boolean
If x >= Rng172.RangeStart AndAlso x <= Rng172.RangeEnd Then
Return True
End If
Return False
End Function
Public Shared Function isIn10(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn10(ip)
End Function
Public Shared Function isIn10(x As UInt32) As Boolean
If x >= Rng10.RangeStart AndAlso x <= Rng10.RangeEnd Then
Return True
End If
Return False
End Function
' string ipString = System.Web.HttpContext.Current.Request.UserHostAddress;
Public Shared Function IsPrivateIp(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return IsPrivateIp(ip)
End Function
Public Shared Function IsPrivateIp(ip As UInt32) As Boolean
If isIn127(ip) OrElse isIn192(ip) OrElse isIn172(ip) OrElse isIn10(ip) Then
Return True
End If
Return False
End Function
End Class
Note: For doing this with UInt128, there's a good implementation of UInt128 in NaCl.NET.
Use the Request.UserHostAddress property to determine whether the request came from a public or private network
I have list of over 20 queues that needs to be added as private queue in MSMQ.
Is there a way to do it using
Command Line
C# programming
If there is a way to do using some sort of script or .net programming then I could add it with out manually inputting it and causing typos.
Please let me know.
thanks
using System.Messaging;
//...
void CreateQueue(string qname) {
if (!MessageQueue.Exists(qname)) MessageQueue.Create(qname);
}
You can only create private queues on your local computer. For more information see: Creating Queues
For command line, you can create a .vbs file with following content:
Option Explicit
Dim objInfo
Dim objQue
Dim objMsg
Dim strFormatName ' Destination
strFormatName = "direct=os:.\private$\test"
Set objInfo = CreateObject("MSMQ.MSMQQueueInfo")
Set objMsg = CreateObject("MSMQ.MSMQMessage")
objMsg.Label = "my message"
objMsg.Body = "This is a sample message."
objInfo.FormatName = strFormatName
set objQue = objInfo.Open( 2, 0 )
' Send Message
objMsg.Send objQue
' Close Destination
objQue.Close
Set objMsg = Nothing
Set objInfo = Nothing
msgbox "Done..."
A bit late on this, however I only started working on them now.
To add to Richard's answer, you can create public queues.
you need the hostname though and admin access to that machine.
public static MessageQueue CreatePrivate(string name) {
string path = string.Format(#".\private$\{0}", name);
if (!MessageQueue.Exists(path)) {
MessageQueue.Create(path);
return new MessageQueue(path);
}
return new MessageQueue(path);
}
public static MessageQueue CreatePublic(string hostname,string queuename) {
string path = string.Format(#"{0}\{1}", hostname,queuename);
if (!MessageQueue.Exists(path)) {
MessageQueue.Create(path);
return new MessageQueue(path);
}
return new MessageQueue(path);
}
}