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
Related
For a while i've been trying to make a standalone program in c#, which uses the BrowseTags function from iHistorian_SDK. (iFix 5.8 and Historian 7.0)
First I made this function in VBA where it works great, but due to VBA being single threaded, I want to moive it out of VBA.
My VBA code that works today:
Public connectedServer As Object
Public myServerManager As Object
Private Sub TestBrowseFunction()
Call BrowseTagsFromHistorianCollector("SVNF-IFIX-HIS01", "SVNF-IFIX-SCA01_iFIX")
End Sub
Public Function BrowseTagsFromHistorianCollector(ByVal HistServer As String, ByVal HistCollector As String, Optional AdditionsOnly As Boolean = False, Optional SourceFilter As String = "*", Optional DescriptionFilter As String = "*")
On Error Resume Next
Dim MyTags As Variant
Dim Tag As Variant
Set connectedServer = Nothing
Set MyServerManager = CreateObject("iHistorian_SDK.ServerManager")
DoEvents
'Make sure Historian is installed correctly'
If MyServerManager Is Nothing Then
Err.Raise 0, , "Error Creating iHistorian Server Manager - please check to see if Historain Client is correctly installed on your system", vbOKOnly, "test"
Exit Function
End If
'Create iHistorian server object'
Set connectedServer = CreateObject("iHistorian_SDK.Server")
'Check to see if the connection is established, else connect.'
If CheckConnection = False Then connectedServer.Connect (HistServer)
If CheckConnection = True Then
'Browse the collector for tags.'
Set MyTags = connectedServer.collectors.Item(HistCollector).BrowseTags(AdditionsOnly, SourceFilter, DescriptionFilter)
'Loop all the tags from the collector'
For Each Tag In MyTags.Item
'INSERT CODE TO DO FOR EACH TAG HERE!'
Debug.Print Tag.tagName
Next
End If
End Function
' make sure that we are connected to a server'
Public Function CheckConnection() As Boolean
On Error GoTo errc
If connectedServer Is Nothing Then
CheckConnection = False
Exit Function
End If
If Not connectedServer.Connected Then
CheckConnection = False
Exit Function
End If
If connectedServer.ServerTime < CDate("1/1/1970") Then
CheckConnection = False
Exit Function
End If
CheckConnection = True
Exit Function
errc:
CheckConnection = False
End Function
This works great.
But in my attempt to convert the same function over to C# i keep getting errors.
First i connect to my historian server, which is pretty painless.
tsStatus.Text = "Connecting to " + HistServer;
try
{
connectedServer = new iHistorian_SDK.Server();
connectedServer.Connect(HistServer);
tsStatus.Text = "Connected to " + HistServer;
}
catch (Exception ex)
{
Debug.Print("Server connection threw exception: " + ex);
tsStatus.Text = "Failed connecting to " + HistServer;
}
My status label before i try to connect:
My status label after i try to connect:
After the connection is established, I would like to be able to do something like what i've done in VBA.
Set MyTags = connectedServer.collectors.Item(HistCollector).BrowseTags(AdditionsOnly, SourceFilter, DescriptionFilter)
My c# attempt goes as follows
iHistorian_SDK.TagRecordset MyTags;
MyTags = new iHistorian_SDK.TagRecordset();
MyTags = connectedServer.Collectors.Item("SVNF-IFIX-SCA01_iFIX").BrowseTags(false, "*", "*");
Does anyone know how I can come around this, or if it's even possible in C# to browse tags with the same methode of the collector object.
I've seen this video a few times so I would assume it's possible, they just skip the code where they actually browse tags.
Thanks in advance
/T
The parenthesis in VBA is an indexer. Try to replace .Collectors.Item.("...") with .Collectors.Item.["..."]
If you check the source code for the video link you provided (I.e. The client SDK sample), they aren't using the collectors to query the tags.
cmdBrowseTags_Click is using the ITags "Query" method to 'Browse Tags'.
Here is the GE provided help doco example included in "iHistClientAccessAPI.chm":
TagQueryParams query = new TagQueryParams();
List<Tag> list = new List<Tag>(), temp = null;
query.Criteria.TagnameMask = "*";
// simple query
connection.ITags.Query(ref query, out list);
// paged query
list.Clear();
query.PageSize = 100; // return at most 100 results per request
while (connection.ITags.Query(ref query, out temp))
list.AddRange(temp);
list.AddRange(temp);
I prefer something like this (includes the server connection for completeness):
ServerConnection serverConnection = new ServerConnection(
new ConnectionProperties
{
ServerHostName = "MyHistorianHostName",
Username = "MyUserName",
Password = "MyPassword",
ServerCertificateValidationMode = CertificateValidationMode.None
});
serverConnection.Connect();
if (serverConnection.IsConnected())
{
List<Tag> tagList = new List<Tag>();
TagQueryParams tagQueryParams = new TagQueryParams
{
Criteria = new TagCriteria { TagnameMask = "*" }, // Wilcard, get all tags.
Categories = Tag.Categories.All, // Change this to Basic fo mimimal info.
PageSize = 100 // The batch size of the while loop below..
};
bool isQuery = true;
while (isQuery)
{
isQuery = serverConnection.ITags.Query(ref tagQueryParams, out var tags);
tagList.AddRange(tags);
}
// At this point, tagList contains a list of all tags that matched your wildcard filter.
// To filter to a specific collector, you could then do something like:
var collectorTagList = tagList.Where(t => t.CollectorName == "MyCollector");
}
Goodluck :)
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();
}
}
}
I am using below code to read incoming mails from MS Outlook 2010 -
public static void outLookApp_NewMailEx(string EntryIDCollection)
{
NameSpace _nameSpace;
ApplicationClass _app;
_app = new ApplicationClass();
_nameSpace = _app.GetNamespace("MAPI");
object o = _nameSpace.GetItemFromID(EntryIDCollection);
MailItem Item = (MailItem)o;
string HTMLbpdyTest = Item.HTMLBody;
string CreationTime = Convert.ToString(Item.CreationTime);
string strEmailSenderEmailId = Convert.ToString(Item.SenderEmailAddress);
string strEmailSenderName = Item.SenderName;
string Subject = Item.Subject;
}
How can I get sender's mail id. I tried Item.SenderEmailAddress but its not giving me the sender's email id. It is giving me something like this -
/O=EXG5/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=TEST35345
The address returned now is an (X.400) Exchange address.
Please take a look at this MSDN article on how to retrieve the corresponding SMTP address.
I am using this VBA routine to retrieve the SMTP address of a mailItem object:
(should be easily portable to C#)
Private Function getSmtpMailAddress(sMail As Outlook.mailItem) As String
Dim strAddress As String
Dim strEntryId As String
Dim objRecipient As Outlook.Recipient
Dim objSession As Outlook.NameSpace
Dim objAddressentry As Outlook.AddressEntry
Dim objExchangeUser As Outlook.ExchangeUser
Dim objReply As Outlook.mailItem
On Error GoTo ErrHandler
If sMail.SenderEmailType = "SMTP" Then
strAddress = sMail.SenderEmailAddress
Else
Set objReply = sMail.reply()
Set objRecipient = objReply.recipients.item(1)
strEntryId = objRecipient.EntryID
objReply.Close OlInspectorClose.olDiscard
Set objSession = getMapiSession
strEntryId = objRecipient.EntryID
Set objAddressentry = objSession.GetAddressEntryFromID(strEntryId)
Set objExchangeUser = objAddressentry.GetExchangeUser()
strAddress = objExchangeUser.PrimarySmtpAddress()
End If
getSmtpMailAddress = strAddress
Exit Function
ErrHandler:
Err.Clear
On Error GoTo 0
getSmtpMailAddress = "???"
End Function
This works for Outlook 2007. The MSDN solution for Outlook 2010 as pointed out above, looks a bit nicer.
I'm using .net web browser control to open an url in new window through proxy with credentials. I use this code for that:
Public Function AppendHeader(ByRef OriginalHeader As String, ByVal Addition As String) As Boolean
If OriginalHeader <> "" Then
OriginalHeader = OriginalHeader + vbNewLine
End If
OriginalHeader = OriginalHeader + Addition
OriginalHeader.Trim(vbNewLine.ToCharArray)
End Function
Public Function Base64Enc(ByRef s As String) As String
Base64Enc = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(s))
End Function
Public Sub Navigate()
Dim webBrowser As WebBrowser = New WebBrowser()
Dim headers As String = ""
AppendHeader(headers, "Proxy-Authorization: Basic " & Base64Enc("user:pass"))
'AppendHeader(headers, "Authorization: Basic " & Base64Enc("user:pass"))
webBrowser.Navigate("http://stackoverflow.com", Guid.NewGuid().ToString(), Nothing, headers)
End Sub
This code helps to hide Windows Security window at the first time, but if loading web page sends requests to other urls this window shows again and again (you can see it on a screenshot below).
So what can I do to solve this problem?
(I'm using winforms and vb.net, but C# is suitable too)
Give this a try I am unable to test it :)
Private Sub webBrowser_Navigating(ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs)
Dim credentials As New System.Net.NetworkCredential("user", "pwd", "MyDomain")
Dim proxy As New System.Net.WebProxy("127.0.1.2", 80)
If proxy Is Nothing Then
e.Cancel = True
End If
End Sub
I'm doing a desktop academic project one of the requirment of this project is to allert the user on mobile by sms and this sms should be sent by a mobile that is connected with the pc. I don't know the way how can i do it. When i did google search here i got the gsm modems gateways one kind of solution to send sms through pc. But they are not free. Then Nokia Conectivity SDK is another way but it is not compatible with Visual Studio2010. I got this example on a website but the sender had said at the end there are errors in my code.
Option Explicit On
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.load
End Sub
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 9600
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Function SendSMS(ByVal CellNumber As String, ByVal SMSMessage As String) As Boolean
Dim MyMessage As String = Nothing
'Check if Message Length <= 160
If SMSMessage.Length <= 160 Then
MyMessage = SMSMessage
Else
MyMessage = Mid(SMSMessage, 1, 160)
End If
If IsOpen = True Then
SMSPort.WriteLine("AT+CMGS=" & CellNumber & vbCr)
_ContSMS = False
SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
_Continue = False
RaiseEvent Sending(False)
End If
End Function
Private Sub ReadPort()
Dim SerialIn As String = Nothing
Dim RXBuffer(SMSPort.ReadBufferSize) As Byte
Dim SMSMessage As String = Nothing
Dim Strpos As Integer = 0
Dim TmpStr As String = Nothing
While SMSPort.IsOpen = True
If (SMSPort.BytesToRead <> 0) And (SMSPort.IsOpen = True) Then
While SMSPort.BytesToRead <> 0
SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize)
SerialIn = SerialIn & System.Text.Encoding.ASCII.GetString(RXBuffer)
If SerialIn.Contains(">") = True Then
_ContSMS = True
End If
If SerialIn.Contains("+CMGS:") = True Then
_Continue = True
RaiseEvent Sending(True)
_Wait = False
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
RaiseEvent DataReceived(SerialIn)
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
End Sub
Public ReadOnly Property IsOpen() As Boolean
Get
If SMSPort.IsOpen = True Then
IsOpen = True
Else
IsOpen = False
End If
End Get
End Property
Public Sub Open()
If IsOpen = False Then
SMSPort.Open()
ReadThread.Start()
End If
End Sub
Public Sub Close()
If IsOpen = True Then
'SMSPort = New SMSCOMMS("COM1")
'SMSEngine.Open()
'SMSEngine.SendSMS("919888888888", "SMS Testing")
'SMSEngine.Close()
SMSPort.Close()
End If
End Sub
End Class
but it is in vb.net i have not command in it. is it work?
Kindly Give me some idea, example I'm doing it in winform using c sharp.
hey i used GSMCOMM library and that works for me to send and receive sms using Computer. download it from google and see its examples to check how it works.
here are some links that help
GSMCOMM Send and recieve SMS Using GSM Modem
from here you can download GSMCOMM library
I'm not sure if you want a way to connect to a phone or a way to send an sms from a pc so I'll give both.
To connect to a phone (if it has data and an android or IOS or something where you can directly modify code) you can create a socket connection from your pc to your phone. I have done this in android aps before and it works good.
If you simply need to send an sms from your computer and you know the carrier just send an email using this list http://www.mutube.com/projects/open-email-to-sms/gateway-list/