how can I get ipAddress info from criterion? - c#

I'm working with Google Adwords and currently can't get specific info. On my Adwords account I set 'IP address exclusion' with 3 IPs. I want to get this IPs from my code:
AdWordsUser user = new AdWordsUser();
var campaignService = (CampaignCriterionService)user.GetService(AdWordsService.v201506.CampaignCriterionService);
int offset = 0;
int pageSize = 500;
var page = new CampaignCriterionPage();
String awql = "SELECT Id where IsNegative = true ORDER BY Id ASC LIMIT " + offset + "," + pageSize;
try
{
do
{
page = campaignService.query(awql);
// Display the results.
if (page != null && page.entries != null)
{
int i = offset;
foreach (var item in page.entries)
{
var t = item; //my work logic here ....
i++;
}
}
offset += pageSize;
} while (offset < page.totalNumEntries);
Debug.WriteLine("Number of items found: {0}", page.totalNumEntries);
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to retrieve campaigns", e);
}
Query returns number of resuls: 3, but without actual info about ipAddress( ipAddress contains null) .
what can I do?

Unfortunately I do not believe that AWQL provides a selector for the Address of a blocked IP. In any case, it is certainly NOT supplied with the AWQL statement you have used above which is only bringing back the Id field:
String awql = "SELECT Id where IsNegative = true ORDER BY Id ASC LIMIT " + offset + "," + pageSize; try
This is why the value is null in your response.
The only way I believe it is possible is to get your hands dirty with the Selector and Predicate objects for that service and use the get() method rather than the query() one.
This solution works for me (admittedly with a later version of the API)
var campaignCriterionService = (CampaignCriterionService)user.GetService(AdWordsService.v201601.CampaignCriterionService);
int offset = 0;
int pageSize = 500;
var page = new CampaignCriterionPage();
try
{
do
{
page = campaignCriterionService.get(new Selector
{
fields = new string[] { IpBlock.Fields.Id, IpBlock.Fields.IpAddress },
predicates = new Predicate[]
{
new Predicate
{
field = IpBlock.Fields.CriteriaType,
#operator = PredicateOperator.EQUALS,
values = new string[] { "IP_BLOCK" }
}
}
});
// Display the results.
if (page != null && page.entries != null)
{
int i = offset;
foreach (var item in page.entries)
{
var t = item; //my work logic here ....
i++;
}
}
offset += pageSize;
} while (offset < page.totalNumEntries);
Debug.WriteLine("Number of items found: {0}", page.totalNumEntries);
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to retrieve campaigns", e);
}

Related

Return two collections in one

how can i add collection to another collection? I am returnging one collection _lastOpenedArticles and if that collection has less than 3 articles i need to add articles from allUsersArticles. However i keep getting article from collection _lastOpenedArticles 3 times. Can you help please.
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
{
foreach (var article in _lastOpenedArticles.Take(3))
{
var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var newCell = new ArticleDetailData()
{
Author = article.Author,
Id = article.Id,
};
if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
{
newCell.BackgroundImage = article.Id.ArticleImageFile();
}
else
{
newCell.BackgroundImage = filename;
}
var sec = article.Category;
if (sec == null)
{
newCell.Section = " ";
}
else
{
newCell.Section = article.Category;
}
LastThreeArticles.Add(newCell);
if (_lastOpenedArticles.Count < 3)
{
foreach (var art in allUserArticles.Take(3))
{
filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var cell = new ArticleDetailData()
{
Author = article.Author,
BackgroundImage = filename,
Id = article.Id,
};
sec = article.Category;
if (sec == null)
{
cell.Section = " ";
}
else
{
cell.Section = article.Category;
}
LastThreeArticles.Add(cell);
}
await FillAnonymousArticles(allUserArticles);
}
}
}
else
{
await FillAnonymousArticles(allUserArticles);
}
}
Instead of checking the count in the for loop, I'd propose to move the check whether you already have 3 articles after the loop. So you avoid to get the articles 3 times (once for each run of the loop):
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
{
foreach (var article in _lastOpenedArticles.Take(3))
{
var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var newCell = new ArticleDetailData()
{
Author = article.Author,
Id = article.Id,
};
if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
{
newCell.BackgroundImage = article.Id.ArticleImageFile();
}
else
{
newCell.BackgroundImage = filename;
}
var sec = article.Category;
if (sec == null)
{
newCell.Section = " ";
}
else
{
newCell.Section = article.Category;
}
LastThreeArticles.Add(newCell);
}
// Move this check out of the for loop
if (_lastOpenedArticles.Count < 3)
{
foreach (var art in allUserArticles.Take(3))
{
filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var cell = new ArticleDetailData()
{
Author = article.Author,
BackgroundImage = filename,
Id = article.Id,
};
sec = article.Category;
if (sec == null)
{
cell.Section = " ";
}
else
{
cell.Section = article.Category;
}
LastThreeArticles.Add(cell);
}
await FillAnonymousArticles(allUserArticles);
}
}
else
{
await FillAnonymousArticles(allUserArticles);
}
}
In addition, you could use Linq to create a union of the lists. This will result in much shorter code, for example:
_lastOpenedArticles
.Union(allUserArticles)
.Take(3)
.Select(x => ConvertToCell(x)) // You need this method that converts the articles to a cell
.ToArray(); // If you need a list, you can also use ToList()
_lastOpenedArticles.AddRange(allUserArticles)
_lastOpenedArticles.Concat(allUserArticles)
the last one returns IEnumerable<T> and first one is void. Take one that suits you better

I Need to insert Exception details into sql server database

My issue is that i have an aspx page which is having try and catch bocks in its code file which will handle exception using exception object in catch,now when the program execution reaches this catch block it calls the public method GetExceptionDetails which will return a long string text containing the values of all the properties of exception but not property's name in it.Now when i insert the properties values into table object's field of database everything is right upto the point when the code reaches at db.submitchanges(),in which an exception statement pops out which reads sqldatetimeoverflow and under sqltypesexception.Please help me figure out the issue in this,Below is the whole code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5
{
public partial class EnterMarks : System.Web.UI.Page
{
public float average,total;
public string grade,chk,exmessage;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["StudentID"] != null)
{
Label1.Text = Request.QueryString["StudentID"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<int> stdID = new List<int>();
tblGrade tb = new tblGrade();
total = (float)(Convert.ToDouble(TextBox1.Text) + Convert.ToDouble(TextBox2.Text) + Convert.ToDouble(TextBox3.Text));
average = total / 3;
if (average > 85 && average < 90)
{
grade = "AA";
}
else if(average>80 && average<85)
{
grade = "A";
}
else if (average > 75 && average < 80)
{
grade = "BB";
}
else if (average > 70 && average < 75)
{
grade = "B";
}
else if (average > 65 && average < 70)
{
grade = "C";
}
else if (average > 60 && average < 65)
{
grade = "CC";
}
else if (average > 55 && average < 60)
{
grade = "D";
}
else
{
grade = "DD";
}
//var query = from m in db.tblGrades
// where m.StudentID == Convert.ToInt32(Request.QueryString["StudentID"])
// select m;
// foreach (var q in query)
//{
tb.StudentID = Convert.ToInt32(Request.QueryString["StudentID"]);
tb.Grade = grade;
db.tblGrades.InsertOnSubmit(tb);
db.SubmitChanges();
Response.Redirect("WebForm1.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
//var query1 = from n in db.tblContacts where n.StudentID == int.Parse(TextBox4.Text) select n;
tblExcDet te = new tblExcDet();
var query1 = from n in db.tblContacts select n.StudentID;
//try
//{
foreach (var q in query1)
{
if (q.Equals((int.Parse(TextBox4.Text))))
{
Label2.Text = "ID Found";
}
}
try
{
int? i = null;
tblContact tc = new tblContact();
tc.StudentID = (int)i ;
//db.tblContacts.InsertOnSubmit(tc);
db.SubmitChanges();
}
catch (Exception ex)
{
exmessage = GetExceptionDetails(ex);
te.ExMessage = exmessage.Split('*')[0];
te.ExData = exmessage.Split('*')[1];
te.ExInner = exmessage.Split('*')[2];
te.ExTargetSite = exmessage.Split('*')[3];
te.ExStackTrace = exmessage.Split('*')[4];
te.ExHelplink = exmessage.Split('*')[5];
te.ExSource = exmessage.Split('*')[6];
te.ExHresult = exmessage.Split('*')[7];
db.tblExcDets.InsertOnSubmit(te);
db.SubmitChanges();
Label2.Text = "Can't assign null value into a table id";
}
}
//public static string GetExceptionDetails(Exception ex)
//{
// var properties = ex.GetType().GetProperties();
// var fields = properties.Select(property=>new{
// name = property.Name,value = property.GetValue(ex,null)
// }).Select(x => String.Format(
// "{0} = {1}",
// x.name,
// x.value != null ? x.value.ToString() : String.Empty
// ));
// return String.Join("*", fields);
//}
public static string GetExceptionDetails(Exception ex)
{
var properties = ex.GetType().GetProperties();
var fields = properties.Select(property => new
{
name = property.Name,
value = property.GetValue(ex, null)
}).Select(x => String.Format(
"{0}",
x.value != null ? x.value.ToString() : String.Empty
));
return String.Join("*", fields);
}
}
}
Also here i'm using LINQ structure to insert data into sql server database.
Do you have the field set as autogenerated in the designer? If that's not the problem, I'd suggest setting up logging of the data context actions to the console and checking the actual SQL generated to make sure that it's inserting that column, then trace backward to find the problem.
context.Log = Console.Out;
FWIW, I often set my "CreatedTime" and "LastUpdatedTime" columns up as autogenerated (and readonly) in the designer and give them a suitable default or use a DB trigger to set the value on insert or update. When you set it up as autogenerated, it won't include it in the insert/update even if modified. If the column doesn't allow nulls, then you need to supply an alternate means of setting the value, thus the default constraint and/or trigger.
You might also want to try an explicit cast to
SqlDbType.DateTime
before doing updatechanges

Index was out of range. Must be non-negative and less than the size of the collection in List<string>

I am using List object to store the user property.
My code is:
string department=string.Empty;
List<string> otherDepartments = new List<string>();
int no;
string result = string.Empty;
string queryText = string.Empty;
using (SPSite siteCollection = SPContext.Current.Site)
{
using(SPWeb site = siteCollection.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUser spUser = site.CurrentUser;
SPServiceContext context = SPServiceContext.GetContext(siteCollection);
UserProfileManager upm = new UserProfileManager(context);
UserProfile profile = upm.GetUserProfile(spUser.LoginName);
department = profile["oiplbDepartment"].Value.ToString();
UserProfileValueCollection otherDept = profile["oiplbOtherDepartments"];
if (otherDept.Count != 0)
{
foreach (var prop in otherDept)
{
otherDepartments.Add(prop.ToString());
}
}
Label1.Text = department + " Ohter Departments " + otherDepartments;
});
SPList list = site.Lists["Events"];
SPListItemCollection itemColl;
SPQuery query = new SPQuery();
no = 1 + otherDepartments.Count;
for (int i = 1; i <= no; i++)
{
if (no == 1)
{
result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>"+department+"</Value></Eq>"+"</or>";
break;
}
else if (i == 2)
{
result = "<or> <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + department + "</Value></Eq>" +
"<Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + otherDepartments[i-1] + "</Value></Eq>";
}
else if(i >= 3)
{
result = generateOr(result,otherDepartments[i-1]);
}
}
queryText = "<where>"+result +"</Where>";
query.Query = queryText;
itemColl = list.GetItems(query);
Grid.DataSource = itemColl.GetDataTable();
Grid.DataBind();
}
}
public static string generateOr(string temp, string value)
{
string r = "<or>" + temp + " <Eq><FieldRef Name='oiplbDepartment' /><Value Type='TaxonomyFieldType'>" + value + "</Value></Eq> </or>";
return r;
}
I am getting the above mentioned error when I run the program.
I am inserting a value if and only if the properties are available otherwise not.
But why am I getting the error?
Its because of
no = 1 + otherDepartments.Count;
change it to
no = otherDepartments.Count;
Even if you subtract 1 from i before you access the item in the list your for-loop loops until i == no. So you could also change i <= no to i < no
for (int i = 1; i < no; i++)

EXCEPTION: object instance has been disposed and can no longer be used for operations that requires a connection

I searched for the solutions in some of the questions that resembles this problem, but couldn solve it, so kindly provide a clear idea about how to solve this.
Order orderDetails= createOrder();
long voucherId = (long)orderDetails.Vouchers.FirstOrDefault().Number; // exception here..
and the createOrder function returns the orderDetails of type Order.
Vouchers is my voucher table,
Number is a column's name in the voucher table.
I have no idea, why how to solve this exception. Any idea about it ?
PART I :
*EDIT:*
private Order createOrder()
{
IList<OfferInfo> offerInformation = new List<OfferInfo>();
OfferInfo offer = new OfferInfo()
{
OfferId = 2,
Message = "test msg",
CreatedDate = System.DateTime.Now,
Gender = "male",
ReceiverName = "john",
ReceiverEmail = "ebenezar#gmail.com"
};
offerInformation.Add(offer);
Order order = new Order();
order.Id = 721;
order.Amount = 1000;
order.CreatedDate = System.DateTime.Now;
order.User = userDetails;
return BLOrder.CreateOrder(order, offerInformation);
}
NOTE:
It inturns call the CreateOrder from the BLOrder which returns the retrieved data in Order type. ( if var is of Order type and is returned, it will have something like, var.xxx="some value" , var.yyy="some value"..)
PART II:
public static Order CreateOrder(Order order, IList<OfferInfo> offerList)
{
order = CreateNewOrder(order, offerList);
Intreat.MSMQ.MSMQHelper.AddOffers(order, offerList);
return order;
}
private static Order CreateNewOrder(Order order, IList<OfferInfo> offerList, bool updateUser = true)
{
try
{
if (updateUser)
{
VerifyUserDetails(order.User);
senderUserId = BLUser.UpdateUser(order.User);
order.User = null;
Logger.WriteLog("Sender user added/updated successfully. UserID:" + senderUserId.ToString());
}
else
senderUserId = order.UserId;
if (order.Company != null)
order.CompanyId = BLCompany.UpdateCompany(order.Company).Id;
VerifyOrderDetails(order, offerList);
using (IntreatEntities intreat = new IntreatEntities())
{
foreach (OfferInfo offer in offerList)
{
orderAmt = (double)((from po in intreat.PartnerOffers
where po.Id == offer.OfferId
select po.Price * offer.Quantity).ToList()).Sum();
order.Amount += orderAmt;
if (offer.IsPos)
tableOrderAmt += orderAmt;
}
if ((tableOrderAmt > 0) && (order.TipPercentage != null) && (order.TipPercentage.Value) > 0)
{
double tipAmt = (tableOrderAmt * (order.TipPercentage.Value * .01));
order.TipAmount = Math.Round(tipAmt);
order.Amount = (double)(order.Amount + order.TipAmount);
}
order.CreatedDate = DateTime.Now;
order.UserId = (Guid)senderUserId;
Logger.WriteLog(string.Format(CultureInfo.InvariantCulture, "order.TableNumber:{0}", order.TableNumber == null ? "(empty)" : order.TableNumber.ToString()));
intreat.Orders.AddObject(order);
intreat.SaveChanges();
Logger.WriteLog("Order added successfully. OrderId:" + order.Id.ToString(CultureInfo.InvariantCulture));
}
return order;
}
catch (Exception ex)
{
Logger.WriteLog(ex);
throw;
}
}
incorporate this line of code order.Vouchers.Load(); as done below and try
private static Order CreateNewOrder(Order order, IList<OfferInfo> offerList, bool updateUser = true)
{
try
{
Guid? senderUserId = null;
/// Process user first so that, the user details are stored even if there is any error in other areas
///
if (updateUser)
{
VerifyUserDetails(order.User);
/// Create/update sending user.
///
senderUserId = BLUser.UpdateUser(order.User);
order.User = null;
Logger.WriteLog("Sender user added/updated successfully. UserID:" + senderUserId.ToString());
}
else
senderUserId = order.UserId;
/// Add company details before processing the order, so that the company details are stored if there is any error in other areas.
///
if (order.Company != null)
order.CompanyId = BLCompany.UpdateCompany(order.Company).Id;
/// Verify and process order
///
VerifyOrderDetails(order, offerList);
using (IntreatEntities intreat = new IntreatEntities())
{
/// Find total amount for the order
double orderAmt = 0;
double tableOrderAmt = 0;
order.Amount = 0;
foreach (OfferInfo offer in offerList)
{
orderAmt = (double)((from po in intreat.PartnerOffers
where po.Id == offer.OfferId
select po.Price * offer.Quantity).ToList()).Sum();
order.Amount += orderAmt;
//If isPos, consider for tip calculation
if (offer.IsPos)
tableOrderAmt += orderAmt;
}
//check if tip amount has to be calculated, by checking for the tableorderAmt
if ((tableOrderAmt > 0) && (order.TipPercentage != null) && (order.TipPercentage.Value) > 0)
{
double tipAmt = (tableOrderAmt * (order.TipPercentage.Value * .01));
order.TipAmount = Math.Round(tipAmt);
order.Amount = (double)(order.Amount + order.TipAmount);
}
order.CreatedDate = DateTime.Now;
order.UserId = (Guid)senderUserId;
Logger.WriteLog(string.Format(CultureInfo.InvariantCulture, "order.TableNumber:{0}", order.TableNumber == null ? "(empty)" : order.TableNumber.ToString()));
/// Create and save order in db
///
intreat.Orders.AddObject(order);
intreat.SaveChanges();
order.Vouchers.Load();
Logger.WriteLog("Order added successfully. OrderId:" + order.Id.ToString(CultureInfo.InvariantCulture));
}
return order;
}
catch (Exception ex)
{
Logger.WriteLog(ex);
throw;
}
}

Programmatically edit IIS IPGrant Table

I've been working on a programmatic solution to edit the IPGrant table in IIS.
As it stands, I can View the IPGrant list Correctly, and CAN add to it.
However, I cannot remove or replace items in the IPGrant list.
MSDN and such recommend that you write (the values of the old list + the new value) to the List, however I'm finding I'm getting a HResult of "Cannot create file with that name, file already exists".
Adding to the list only works for me If I pass in the new value only.
After some reading:
http://www.west-wind.com/weblog/posts/59731.aspx
http://www.aspdev.org/articles/web.config/
http://www.codeproject.com/KB/security/iiswmi.aspx
http://www.codeproject.com/KB/security/iiswmi.aspx?msg=1739049
http://blogs.msdn.com/b/shawnfa/archive/0001/01/01/400749.aspx
http://msdn.microsoft.com/en-us/library/ms524322%28VS.90%29.aspx
http://www.eggheadcafe.com/software/aspnet/33215307/setting-ip-restrictions-in-iis-7.aspx
I'm finding that there is a compatability issue with IIS 7/6 and using the Metabase - in that one can only add to it, not remove.
Is there a more current method for IIS 7/7.5 that can be used (in c# please) to administrate the IPGrant table.
You can use Microsoft.Web.Administration, or AppCmd, or Javascript (COM - AHADMIN) to do that, here are a few examples on how to remove:
private static void Main() {
using(ServerManager serverManager = new ServerManager()) {
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity");
ConfigurationElementCollection ipSecurityCollection = ipSecuritySection.GetCollection();
ConfigurationElement addElement = FindElement(ipSecurityCollection, "add", "ipAddress", #"169.132.124.234", "subnetMask", #"255.255.255.255", "domainName", #"");
if (addElement == null) throw new InvalidOperationException("Element not found!");
ipSecurityCollection.Remove(addElement);
serverManager.CommitChanges();
}
}
private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues) {
foreach (ConfigurationElement element in collection) {
if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase)) {
bool matches = true;
for (int i = 0; i < keyValues.Length; i += 2) {
object o = element.GetAttributeValue(keyValues[i]);
string value = null;
if (o != null) {
value = o.ToString();
}
if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase)) {
matches = false;
break;
}
}
if (matches) {
return element;
}
}
}
return null;
}
Using Javascript:
var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST";
var ipSecuritySection = adminManager.GetAdminSection("system.webServer/security/ipSecurity", "MACHINE/WEBROOT/APPHOST");
var ipSecurityCollection = ipSecuritySection.Collection;
var addElementPos = FindElement(ipSecurityCollection, "add", ["ipAddress", "169.132.124.234","subnetMask", "255.255.255.255","domainName", ""]);
if (addElementPos == -1) throw "Element not found!";
ipSecurityCollection.DeleteElement(addElementPos);
adminManager.CommitChanges();
function FindElement(collection, elementTagName, valuesToMatch) {
for (var i = 0; i < collection.Count; i++) {
var element = collection.Item(i);
if (element.Name == elementTagName) {
var matches = true;
for (var iVal = 0; iVal < valuesToMatch.length; iVal += 2) {
var property = element.GetPropertyByName(valuesToMatch[iVal]);
var value = property.Value;
if (value != null) {
value = value.toString();
}
if (value != valuesToMatch[iVal + 1]) {
matches = false;
break;
}
}
if (matches) {
return i;
}
}
}
return -1;
}
And Finally AppCmd.exe:
appcmd.exe set config -section:system.webServer/security/ipSecurity /-"[ipAddress='169.132.124.234',subnetMask='255.255.255.255',domainName='']" /commit:apphost

Categories