the method does not exist in the current context [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
My problem is
"Affiche()" does not exist for the current context.
class OPPSVotesStatistiques
The code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.Configuration;
namespace Components.Jobs
{
class OPPSVotesStatistiques : SPJobDefinition
{
private Pmail p;
public OPPSVotesStatistiques()
: base()
{
}
public OPPSVotesStatistiques(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
{
this.Title = "ListLogger";
}
public override void Execute(Guid contentDbId)
{
Pmail p = new Pmail();
InsretListAvis addAvis = new InsretListAvis();
List<AttributMail> listMail = Pmail.Affiche();
foreach (AttributMail m in listMail)
{
info = addAvis.Insert(m.Projet, m.Phase, m);
}}}
class Pmail
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Text.RegularExpressions;
namespace Components.MailVote
{
class Pmail
{
public Pmail()
{
}
public static List<AttributMail> Affiche()
{
List<AttributMail> lmail = new List<AttributMail>();
try
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
//service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );
service.Credentials = new WebCredentials("mail#site.com", "pass");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("mail#site.com", RedirectionUrlValidationCallback);
Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
//The search filter to get unread email
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
itempropertyset.RequestedBodyType = BodyType.Text;
ItemView view = new ItemView(50);
view.PropertySet = itempropertyset;
//Fire the query for the unread items
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
foreach (Item item in findResults.Items)
{
AttributMail m = new AttributMail();
item.Load(itempropertyset);
m.From = (item as EmailMessage).Sender.Name;
m.Sujet = item.Subject;
m.Txt = item.Body;
m.Date = item.DateTimeReceived.TimeOfDay.ToString();
m.Cc = item.DisplayCc;
lmail.Add(m);
} }
catch(Exception ex){
}
return lmail;}}}
it's a timer job to read mails and to insert data into SPlist .

Make Pmail.affiche() public.
So,
public class Pmail
{
public List<AttributMail> affiche()
{
...
}
}
Also, it is C# convention to name methods with uppercase, so Affiche()
EDIT:
Okay, now we have the information, the problem is it's static like I said in the comments!
The code you posted must work:
Pmail.Affiche();
Pmail p = new Pmail();
p.Affiche(); // will not work as you can't call a static method on an instance.
So
public override void Execute(Guid contentDbId)
{
InsretListAvis addAvis = new InsretListAvis();
List<AttributMail> listMail = Pmail.Affiche(); // static call
foreach (AttributMail m in listMail)
{
info = addAvis.Insert(m.Projet, m.Phase, m);
}
}

Related

Xamarin.Forms ios WebViewRenderer sharing Cookies

I'm using a WebViewRenderer to setup the cookie policy and also to share cookies from a login request from an HTTPClient. It turns out that as much as I give the set:
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
When debugging in the iphone simulator and running the webview it is indicated in the browser that the cookies policy is not enabled, so the user can not log in because the webview runs an iframe from a secure environment. Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Projeto.Custom;
using Projeto.iOS.Renderers;
using Xamarin.Forms.Platform.iOS;
using WebKit;
using System.IO;
using System.Net;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace Mynamespace.iOS.Renderers
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if(Control == null)
{
var userController = new WKUserContentController();
var config = new WKWebViewConfiguration {
UserContentController = userController };
var webView = new WKWebView(Frame, config);
SetNativeControl(webView);
}
if(e.OldElement != null)
{
var hybrid = e.OldElement as CustomWebView;
hybrid.Cleanup();
}
if(e.NewElement != null)
{
var baseUrl = new NSUrl(NSBundle.MainBundle.BundlePath,
true);
string content = Element.Uri;
Control.LoadHtmlString(content, baseUrl);
var cookieUrl = new
Uri("https://secure.gooddata.com/gdc/account/login");
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
cookieJar.DeleteCookie(aCookie);
}
var jCookies =
CustomCookie.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies =
(from object jCookie in jCookies
where jCookie != null
select (Cookie)jCookie
into netCookie
select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
}
}
}
}
If anyone can tell me the best way to enable cookie policy in ios native WebView, I will be grateful.

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";

Get Value from Dropdown List in MVC

On submit the contact form sends out an email to the specified email address in the web.config file. However at the moment it is posting the ID of the "Selected Services" - how do i get the value rendering instead of the ID? I've tried going through the list after appending the . to see what is available to me, i can't find value.
The values are already defined in Umbraco using a custom datatype.
Here is the surface controller;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.XPath;
using Umbraco.Core.Services;
using Umbraco.Web.Mvc;
/// <summary>
/// Summary description for ContactSurfaceController
/// </summary>
namespace LiquidThinker2015
{
public class ContactSurfaceController : SurfaceController
{
public object XPathModeIterator { get; private set; }
public ActionResult ShowForm()
{
ContactModel myModel = new ContactModel();
List<SelectListItem> ListOfServices = new List<SelectListItem>();
XPathNodeIterator iterator = umbraco.library.GetPreValues(1435);
iterator.MoveNext();
XPathNodeIterator preValues = iterator.Current.SelectChildren("preValue", "");
while (preValues.MoveNext())
{
string preValue = preValues.Current.GetAttribute("id", "");
ListOfServices.Add(new SelectListItem
{
Text = preValues.Current.Value,
Value = preValues.Current.GetAttribute("id","")
});
myModel.ListOfServices = ListOfServices;
}
return PartialView("ContactForm", myModel);
}
public ActionResult HandleFormPost(ContactModel model)
{
var newComment = Services.ContentService.CreateContent(model.Name + " - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"), CurrentPage.Id, "ContactFormula");
//DataTypeService myService = new DataTypeService();
//var SelectedService = myService.GetAllDataTypeDefinitions().First(x => x.Id == 1435);
//int SelectedServicePreValueId = myService.GetPreValuesCollectionByDataTypeId(SelectedService.Id).PreValuesAsDictionary.Where(x => x.Value.Value == model.SelectedService).Select(x => x.Value.Id).First();
newComment.SetValue("contactName", model.Name);
newComment.SetValue("companyName", model.Company);
newComment.SetValue("emailFrom", model.Email);
newComment.SetValue("telephoneNumber", model.Telephone);
newComment.SetValue("dropdownServices", model.SelectedService);
newComment.SetValue("contactMessage", model.Message);
Services.ContentService.SaveAndPublishWithStatus(newComment);
//Send out email
if (ModelState.IsValid)
{
var sb = new StringBuilder();
sb.AppendFormat("<p>Name: {0}</p>", model.Name);
sb.AppendFormat("<p>Company: {0}</p>", model.Company);
sb.AppendFormat("<p>Email: {0}</p>", model.Email);
sb.AppendFormat("<p>Phone: {0}</p>", model.Telephone);
sb.AppendFormat("<p>Service: {0}</p>", model.SelectedService); //THIS LINE HERE
sb.AppendFormat("<p>Message: {0}</p>", model.Message);
SmtpClient smtp = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress ma = new MailAddress(model.Email);
message.Subject = ConfigurationManager.AppSettings["ContactFormSubject"];
message.To.Add(new MailAddress(ConfigurationManager.AppSettings["ContactFormTo"]));
message.CC.Add(new MailAddress(ConfigurationManager.AppSettings["ContactFormCC"]));
message.From = ma;
message.Sender = new MailAddress(model.Email);
message.Body = sb.ToString();
message.IsBodyHtml = true;
try
{
smtp.Send(message);
}
catch (SmtpException smtpEx)
{
// Log or manage your error here, then...
return RedirectToUmbracoPage(1084); // Redirect to homepage.
}
return RedirectToUmbracoPage(1454);
}
return RedirectToUmbracoPage(1454);
}
}
}
Edit:
#co0ke when i do that i get this;
Or should i just try passing in "1435"?
You can use the method on the UmbracoHelper named .GetPreValueAsString(id) and pass in the id of the prevalue.
The UmbracoHelper is available as a property named 'Umbraco' on the PluginController which SurfaceController inherits from.

Send email containing pdf based on items in table

I have a program that I lost the source code to and cannot figure out what I am doing wrong now that we had an IP change. What I am trying to do is step through a table and have it send emails with the corresponding report. Any ideas what is going wrong? I don't get any errors but I also don't get any emails (and yes the SMTP server works).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Web;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace AutomatedReporting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
}
dc.ExecuteCommand("TRUNCATE TABLE reportsSent1");
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.***.***.***/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.***.***.***/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
var matchedDocument = (from c in db.GetTable<Document>()
where c.DocIDKey == SelectedRow.DocIDKey
select c).SingleOrDefault();
db.Documents.DeleteOnSubmit(matchedDocument);
db.SubmitChanges();
var matchedEmail = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Email).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("Reports#acmetaxabstracts.com", matchedEmail, "Report for property located at " + matchedAdd, "Attached is the Tax Information Certificate for the above captioned property");
MailAddress copy = new MailAddress("acmetaxabstracts#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.***.***.***");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
//db.reportsSent1s.DeleteOnSubmit(matchedItem);
//db.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}

Right settings for firewall rule 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;
}
}

Categories