Right settings for firewall rule C# - c#

I got a new question, what firewall settings is needed for blocking an IP address ? I found the property "RemoteAddress", like firewallRule.RemoteAddress, but I dont know how to use it. This is what I found on stackoverflow ( following code blocks all access to internet ), Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NETCONLib;
using NATUPNPLib;
using NetFwTypeLib;
namespace WindowsFormsApplication1
{
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
}
}
}

You can use list of ip addresses (subnets, aliases) splitted by commas
$Rule.RemoteAddresses = RemoteAddresses = 'LocalSubnet,10.1.1.1/255.255.255.255,12.5.0.0/255.255.0.0'

As far as I can tell, you have to retrieve the RemoteAddresses list first before adding to it. Otherwise, it just overwrites each IP with the next one. The format needs to be as Jan described in his/her answer. However, the subnet "/255.255.255.255" is not needed when adding a single IP address. My app only blocks a single ip at a time, but you can put ranges in there as Jan describes. Most the credit goes to others on SO with exception of the RemoteAddresses part. If there's a better/cleaner way, I would love to hear it. Here's how I ended up doing it:
private void BlockIp(string ip, string ruleName)
{
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == ruleName).FirstOrDefault();
if (firewallRule == null)
{
firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Name = ruleName;
firewallPolicy.Rules.Add(firewallRule);
firewallRule.Description = "Block inbound traffic";
firewallRule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
//firewallRule.LocalPorts = "8080";
//firewallRule.Grouping = "#firewallapi.dll,-23255";
firewallRule.Enabled = true;
firewallRule.RemoteAddresses = ip;
//firewallPolicy.Rules.Add(firewallRule); //throws error, not needed
} else {
var remoteAddresses = firewallRule.RemoteAddresses;
firewallRule.RemoteAddresses = remoteAddresses + "," + ip;
}
}

Related

System.ArgumentNullException: 'value can't be null Parametre name: source'

I have a program which connects to a site and gets the list of orders using soap api. But i have a really strange issue. When a i try to get the orders of a day which there is no orders and then try get list of orders of a day i get this error. But strange thing is if a put a break point to line where i got the error and evalute the program step by step i don't get any errors. How could that happen. herre is the code.
https://api.n11.com/ws/OrderService.wsdl
using n11.Deneme.Forms.com.n11.api;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace n11.Deneme.Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strStartDate = "18/01/2020";
string strEndDate = "18/01/2020";
long totalCountValue = 50;
int currentPageValue = 0;
int pageCountValue = 1;
int pageSizeValue = 50;
Authentication auth = new Authentication();
auth.appKey = "b891a6b9-cb97-4a7e-9ffb-f7b1e2a593e8";
auth.appSecret = "pHCjYYadxwTG64Ej";
OrderSearchPeriod orderSearchPeriod = new OrderSearchPeriod();
orderSearchPeriod.startDate = strStartDate;
orderSearchPeriod.endDate = strEndDate;
OrderDataListRequest orderDataListRequest = new OrderDataListRequest();
//orderDataListRequest.status = "1";
orderDataListRequest.period = orderSearchPeriod;
//orderDataListRequest.orderNumber = "209524598478";
PagingData pagingData = new PagingData();
pagingData.currentPage = currentPageValue;
pagingData.pageCount = pageCountValue;
pagingData.pageSize = pageSizeValue;
pagingData.totalCount = totalCountValue;
DetailedOrderListRequest request = new DetailedOrderListRequest();
request.auth = auth;
request.pagingData = pagingData;
request.searchData = orderDataListRequest;
OrderServicePortService port = new OrderServicePortService();
DetailedOrderListResponse response = port.DetailedOrderList(request);
List<DetailedOrderData> orderList = response.orderList.ToList();
foreach (var order in orderList)
{
MessageBox.Show(order.totalAmount.ToString() + " - " + order.orderNumber + " - " + order.citizenshipId + " - " + order.createDate);
long orderIdValue = order.id;
OrderDataRequest orderDataRequest = new OrderDataRequest();
orderDataRequest.id = orderIdValue;
OrderDetailRequest orderdetailrequest = new OrderDetailRequest();
orderdetailrequest.auth = auth;
orderdetailrequest.orderRequest = orderDataRequest;
OrderServicePortService port1 = new OrderServicePortService();
OrderDetailResponse orderDetailResponse = port1.OrderDetail(orderdetailrequest);
OrderDetailData orderDetail = orderDetailResponse.orderDetail;
MessageBox.Show(orderDetail.orderNumber);
List<OrderSearchData> orderItemList = orderDetail.itemList.ToList();
foreach (var item in orderItemList)
{
MessageBox.Show(item.shipmentInfo.campaignNumber);
}
}
}
}
}
If you're getting the error on the line:
List<DetailedOrderData> orderList = response.orderList.ToList(); //I GOT THE ERROR ON THIS LINE
then the thing to do is to look at how response.orderList gets a value. In particular, does it do something with threads, tasks, timers, external events, or anything else like that - which could mean that it gets populated shortly after the initial return from DetailedOrderList, which could explain why it works when you debug and step through (adding a crucial delay into things).
You could also simply do:
var tmp = response.orderList;
if (tmp == null) throw new InvalidOperationException(
"hey, response.orderList was null! this is not good!");
List<DetailedOrderData> orderList = tmp.ToList();
return orderList;
which would make it very clear and explicit that this is what is happening. If you don't get this exception, but something else, then: more debugging needed!
if(response.orderList == null)
{
var temp = button1_Click.PerformClick();
return temp;
}
else
{
List<DetailedOrderData> orderList = response.orderList.ToList();
return orderList;
}

EWS C# error: does not exist in current context

I'm trying to write a program to read through an exchange mailbox. I'm very new to c#, so please excuse if the error is too obvious.
Here's the code and it fails when I try to bind the EmailMessage and gives me the error - "The name 'id' does no exist in the current context"
using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ResetOraclePassword
{
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("abc#xyz.com", "xxxxxxx");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("abc#xyz.com", RedirectionUrlValidationCallback);
Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
PropertySet propSet = new PropertySet(EmailMessageSchema.InternetMessageHeaders, EmailMessageSchema.Body, EmailMessageSchema.HasAttachments, EmailMessageSchema.Attachments,
EmailMessageSchema.Subject, EmailMessageSchema.From, EmailMessageSchema.Sender, EmailMessageSchema.DisplayCc, EmailMessageSchema.DisplayTo, EmailMessageSchema.DateTimeReceived,
EmailMessageSchema.InternetMessageId);
propSet.RequestedBodyType = BodyType.Text;
EmailMessage abc = EmailMessage.Bind(service, id, propSet);
Console.WriteLine(abc.Subject);
Console.WriteLine(abc.InternetMessageId);
Console.WriteLine(abc.DateTimeReceived.ToString());
Console.WriteLine(abc.From.Name);
Console.WriteLine(abc.DisplayTo);
Console.WriteLine(abc.DisplayCc);
Console.WriteLine(abc.Body.Text);
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
}
the error should be in this line
EmailMessage abc = EmailMessage.Bind(service, id, propSet);
it said that idis not defined in your code, so you need to initialize id in your code. For example, if id is string then you can define like
string id = "any value";

Setting first slide to display using PowerPoint-Api

I use NetOffice.PowerPointApi to play some Powerpoint-Slides of an existing PPTX. This is how this is done:
PowerPoint.Application powerApplication = new PowerPoint.Application();
PowerPoint.Presentation presentation = powerApplication.Presentations.Open("C:\\dev\\test.pptx", MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);
// presentation.SlideShowSettings.StartingSlide = 2;
presentation.SlideShowSettings.Run();
while (powerApplication.ActivePresentation.SlideShowWindow.View.CurrentShowPosition < 4)
{
System.Threading.Thread.Sleep(2000);
powerApplication.ActivePresentation.SlideShowWindow.View.Next();
}
Now my plan was to display slide 3 to 4.
But when I set the startingSlide (commented out in my example) I receive an error on powerApplication.ActivePresentation.SlideShowWindow.View.CurrentShowPosition :
{"SlideShowView.CurrentShowPosition : Invalid request. There is
currently no slide show view for this presentation."}
This only happens when I set the property StartingSlide. If I don't, the presentation runs from the first until the 4th slide.
You need to set more properties of the SlideShowSettings object:
using NetOffice.OfficeApi.Enums;
using NetOffice.PowerPointApi.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using PowerPoint = NetOffice.PowerPointApi;
namespace PlayPowerPoint
{
class Program
{
static void Main(string[] args)
{
using (var app = new PowerPoint.Application())
{
var presentation = app.Presentations.Open(Path.GetFullPath("Test.pptx"), MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
var slideShowSettings = presentation.SlideShowSettings;
slideShowSettings.StartingSlide = 2;
slideShowSettings.EndingSlide = 4;
slideShowSettings.RangeType = PpSlideShowRangeType.ppShowSlideRange;
slideShowSettings.AdvanceMode = PpSlideShowAdvanceMode.ppSlideShowManualAdvance;
slideShowSettings.Run();
var slideShowView = presentation.SlideShowWindow.View;
while (slideShowView.CurrentShowPosition < slideShowSettings.EndingSlide)
{
Thread.Sleep(2000);
slideShowView.Next();
}
presentation.Saved = MsoTriState.msoTrue;
presentation.Close();
app.Quit();
}
}
}
}

Google Analytics API for .NET

I am trying to find a stable and up to date example of a Google Analytics Reporting handler in .NET. Any information on the matter will be greatly appreciated. I have searched, and found nothing that really is for current use in .NET. I have also noticed, that the friendly friend Google did not create a library for it, but did under Java. At least from what I was able to see. Does anyone have a reference I could view, or a link with some good examples of setting up a reporting tool with this API?
Thanks in advance. :)
Here is my basic working example I finally got. Hopefully this helps, enjoy!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Analytics;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Gongos.AnalyticsAPI
{
public partial class _Default : Page
{
public string VisitsNumber()
{
string visits = string.Empty;
string username = "******** --> Your email";
string pass = "********** --> Your password";
string gkey = "?key= **** --> Your APY key <-- ****";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:********";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
query1.GAStartDate = new DateTime(2013, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
}
}

C#: get information about computer in domain

What classes should I use in C# in order to get information about a certain computer in my network? (Like who is logged on that computer, what Operating System is running on that computer, what ports are opened etc)
Checkout System.Management and System.Management.ManagementClass. Both are used for accessing WMI, which is how to get the information in question.
Edit: Updated with sample to access WMI from remote computer:
ConnectionOptions options;
options = new ConnectionOptions();
options.Username = userID;
options.Password = password;
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope;
scope = new ManagementScope("\\\\" + ipAddress + "\\root\\cimv2", options);
scope.Connect();
String queryString = "SELECT PercentProcessorTime, PercentInterruptTime, InterruptsPersec FROM Win32_PerfFormattedData_PerfOS_Processor";
ObjectQuery query;
query = new ObjectQuery(queryString);
ManagementObjectSearcher objOS = new ManagementObjectSearcher(scope, query);
DataTable dt = new DataTable();
dt.Columns.Add("PercentProcessorTime");
dt.Columns.Add("PercentInterruptTime");
dt.Columns.Add("InterruptsPersec");
foreach (ManagementObject MO in objOS.Get())
{
DataRow dr = dt.NewRow();
dr["PercentProcessorTime"] = MO["PercentProcessorTime"];
dr["PercentInterruptTime"] = MO["PercentInterruptTime"];
dr["InterruptsPersec"] = MO["InterruptsPersec"];
dt.Rows.Add(dr);
}
Note: userID, password, and ipAddress must all be defined to match your environment.
Here is an example of using it in like an about box. MSDN has the rest of the items you can all.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
namespace About_box
{
public partial class About : Form
{
public About()
{
InitializeComponent();
FormLoad();
}
public void FormLoad()
{
SystemInfo si;
SystemInfo.GetSystemInfo(out si);
txtboxApplication.Text = si.AppName;
txtboxVersion.Text = si.AppVersion;
txtBoxComputerName.Text = si.MachineName;
txtBoxMemory.Text = Convert.ToString((si.TotalRam / 1073741824)
+ " GigaBytes");
txtBoxProcessor.Text = si.ProcessorName;
txtBoxOperatingSystem.Text = si.OperatingSystem;
txtBoxOSVersion.Text = si.OperatingSystemVersion;
txtBoxManufacturer.Text = si.Manufacturer;
txtBoxModel.Text = si.Model;
}
}
}
WMI Library and here is a VB.net example. It shouldn't be difficult to convert it to C#
Look into the WMI library.

Categories