Examining the documentation at datastax on the cassandra c# driver (cassandra C# driver documentation), the following code is presented:
// Update
users.Where(u => u.UserId == "john")
.Select(u => new User { LastAccess = TimeUuid.NewId()})
.Update()
.Execute();
I decided to create a repository like this:
public bool Update(Func<T,bool> whereExpression,Func<T,T> selectExpression)
{
try
{
this.AllRecords
.Where(whereExpression)
.Select(selectExpression)
.Update()
.Execute();
}
catch (Exception)
{
throw;
}
}
I received the following error:
Error 1 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Update' and no extension method 'Update' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)
I have imported all the necssary namespaces
using System.Linq;
using Cassandra.Data.Linq;
The problem lies with the construction of your method parameters. If you inspect the Cassandra.Data.Linq namespace, the Where extension method is presented as:
public static CqlQuery<TSource> Where<TSource>(this CqlQuery<TSource> source, Expression<Func<TSource, bool>> predicate);
Hence, you should update your code as:
public bool Update(Expression<Func<T,bool>> whereExpression, Expression<Func<T,T>> selectExpression)
{
try
{
this.AllRecords
.Where(whereExpression)
.Select(selectExpression)
.Update()
.Execute();
}
catch (Exception)
{
throw;
}
}
Also, don't forget to import the following namespace for this to work:
using System.Linq;
using System.Linq.Expressions;
using Cassandra.Data.Linq;
That's all that you need to do to get this working...
Related
I tried making an addon using the existing selenium addon codes and resources.
I was able to make an addon with just one command (for testing) to open Flipkart.
I used the selenium.open command code and edited it slightly by entering default value of URL argument as (flipkart.com).
I was successfully able to build my solution (I made sure to add all the nuget packages and other necessities)
Now when I try to load the addon in my studio, I'm getting an error mentioning that it expected command postfix for the FlipkartOpen command.
Can anyone please let me know the reason for this error and maybe a possible solution to fix it?
Here's the error image: G1ANT Studio Error for New Addon.
And here's my code sample:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using G1ANT.Language;
using OpenQA.Selenium;
namespace G1ANT.Addon.Flipkart.Commands
{
[Command(Name = "Flipkart.Open", Tooltip = "This command opens flipkart in a web browser provided in the Argument.")]
public class FlipkartOpen : Command
{
public FlipkartOpen(AbstractScripter scripter) : base(scripter)
{
}
public class Arguments : CommandArguments
{
// Enter all arguments you need
[Argument(Required = true, Tooltip = "Name of a web browser")]
public TextStructure Type { get; set; } = new TextStructure(string.Empty);
[Argument(DefaultVariable ="Url", Tooltip = "Website Url")]
public TextStructure Url { get; set; } = new TextStructure("www.flipkart.com");
[Argument(DefaultVariable = "timeoutselenium", Tooltip = "Specifies time in milliseconds for G1ANT.Robot to wait for the command to be executed")]
public override TimeSpanStructure Timeout { get; set; } = new TimeSpanStructure(SeleniumSettings.SeleniumTimeout);
[Argument(Tooltip = "By default, waits until the webpage fully loads")]
public BooleanStructure NoWait { get; set; } = new BooleanStructure(false);
[Argument(Tooltip = "Result variable")]
public VariableStructure Result { get; set; } = new VariableStructure("result");
}
// Implement this method
public void Execute(Arguments arguments)
{
try
{
SeleniumWrapper wrapper = SeleniumManager.CreateWrapper(
arguments.Type.Value,
arguments.Url?.Value,
arguments.Timeout.Value,
arguments.NoWait.Value,
Scripter.Log,
Scripter.Settings.UserDocsAddonFolder.FullName);
int wrapperId = wrapper.Id;
OnScriptEnd = () =>
{
SeleniumManager.DisposeAllOpenedDrivers();
SeleniumManager.RemoveWrapper(wrapperId);
SeleniumManager.CleanUp();
};
Scripter.Variables.SetVariableValue(arguments.Result.Value, new IntegerStructure(wrapper.Id));
}
catch (DriverServiceNotFoundException ex)
{
throw new ApplicationException("Driver not found", ex);
}
catch (Exception ex)
{
throw new ApplicationException($"Error occured while opening new selenium instance. Url '{arguments.Url.Value}'. Message: {ex.Message}", ex);
}
}
}
}
To remove this error, when you add new class, write Command.cs at the end while adding. Try FlipkartopenCommand.cs
This should remove your error.
I am developing an ASP.NET application that uses ODataApiController. The application shows users a grid by querying data and showing it in a table. I would like the ability to export to a number of different formats, including CSV and a custom XML format. Ideally, I would just take the same OData query the grid uses, set the Accepts header, and get back CSV or XML.
I've created MediaTypeFormatters to do what I need, but they only work with "regular" ApiController, not ODataApiController. Looking at the code in github, I see that OData has it's own MediaTypeFormatter scheme to handle various cases, and built in XML and JSON formatters. But I can't see how to hook into this to provide custom formats. I've attempted inheriting ODataMediaTypeFormatter, but a breakpoint set on it never hits.
I am only really interested in output formats here. How can I extend OdataApi to output different formats?
You can use MediaTypeFormatter on OData queries as well. Just add a new class to your project that inherit MediaTypeFormatter. Then add this to your WebApiConfig file on Register:
config.Formatters.Add(new JSONPFormatter(new QueryStringMapping("$format","jsonp","application/javascript")));
If you then query your entity with the $format=jsonp it will return the entity as JSONP. You can also request it with the contenttype application/javascript to get a JSONP return.
Here is a full example for a MediaFormatter for JSONP return. You could easily change it for your need:
using MyProject.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.ServiceModel.Syndication;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using Newtonsoft.Json;
namespace SMSIdent.Modules.Formatter
{
/// <summary>
/// Adds a $format=jsop to all odata query
/// </summary>
public class JSONPFormatter : MediaTypeFormatter
{
private readonly string jsMIME = "application/javascript";
public JSONPFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(jsMIME));
}
public JSONPFormatter(MediaTypeMapping mediaTypeMapping) : this()
{
MediaTypeMappings.Add(mediaTypeMapping);
}
//THis checks if you can POST or PUT to this media-formater
public override bool CanReadType(Type type)
{
return false;
}
//this checks if you can GET this media. You can exclude or include your Resources by checking for their types
public override bool CanWriteType(Type type)
{
return true;
}
//This actually takes the data and writes it to the response
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
//you can cast your entity
//MyType entity=(MyType) value;
var callback=HttpContext.Current.Request.Params["callback"];
return Task.Factory.StartNew(() =>
{
using (StreamWriter sw = new StreamWriter(writeStream))
{
if (string.IsNullOrEmpty(callback))
{
callback = "values";
}
sw.Write(callback + "(" + JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}) + ")");
}
});
}
}
}
Note: I'am using Web API 2. I don't know exactly if it also works in Web Api 1.
We have a generic repository done with code-first technique. As the code is in testing we realized that the generic repository is relatively slower than that of directly accessing the DBContext and loading data. In order to simulate the issue for you all, we simplify the generic repository wrote a new code and that code is pasted below..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DemoTest.Bll.Models;
using DemoTest.Bll.DB;
using MasIt.Common.BackEnd;
using System.Data.Entity;
namespace DemoTest.Bll.Handlers
{
public abstract class MyHandlerBase<E, T>
where E : DbSet<T>
where T : class, IBaseObject
{
public MyHandlerBase(E mySet)
{
dbSet = mySet;
}
public E dbSet;
protected IEnumerable<T> GetAllNew(Func<T, bool> predicate)
{
try
{
return dbSet.Where(predicate).AsEnumerable();
}
catch { return null; }
}
}
public class StudentHandler : MyHandlerBase<DbSet<Student>, Student>
{
public StudentHandler()
:base(DemoDBContext.GetContext().Students)
{
//_entitySet = new DemoDBContext().Students;
}
public List<Student> getList(bool option1)
{
if (option1)
{
// Option 1 this is very fast and hit the Student Constructor only once
IEnumerable<Student> response1 = this.dbSet.Where(x => x.StudentId == 10).AsEnumerable();
return response1.ToList();
}
else
{
// Option 2 this is very slow and hit the Student Constructor the student record count of the table
IEnumerable<Student> response2 = this.GetAllNew(x => x.StudentId == 10);
return response2.ToList();
}
}
}
}
Can anybody say why Option 2 is slower.. it is not just slow, it hits the Student class constructor many times, while option 1 hits the constructor only once.. So it seems to us that option 1 load only the matching record, where as option 2 load all the records and match them in memory to filter records..
Generic Repository is a must.. Any fix is highly appreciated...
Got the fix...
Replacing
"Func<T, bool> predicate" with
"Expression<Func<E, Boolean>>" predicate did the trick..
Man .. a horrible nightmare is just over..
Just starting messing with repository/interfaces and the like and I have an error when selecting a single record which I can't work out.
My controller has:
public ViewResult Detail(int ID)
{
var Details = (from x in repo.GetBreakdown(ID) select new BreakdownDetailViewModel { }).SingleOrDefault();
return View(Details);
}
The statement repo.GetBreakdown(ID) is underlined with the following error:
Could not find an implementation of the query pattern for source type ''. 'Select' not found.
My Interface is showing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain.Entities;
namespace Domain.Abstract
{
public interface IBreakdownRepository
{
tblBreakdown_Log GetBreakdown(int ID);
IQueryable<tblBreakdown_Log> GetAllBreakdowns { get; }
}
}
And the repository itself has:
public tblBreakdown_Log GetBreakdown(int ID)
{
return (from x in db.tblBreakdown_Logs where x.MB_ID == ID select x).SingleOrDefault();
}
Any ideas on what the issue is here?
Thanks,
Chris
Based on the comment by #Evan
Changed my repository access to:
public IEnumerable<tblBreakdown_Log> GetBreakdown(int ID)
{
return (from x in db.tblBreakdown_Logs where x.MB_ID == ID select x);
}
The interface to the repository now has:
IEnumerable<tblBreakdown_Log> GetBreakdown(int ID);
And my controller access is:
public ViewResult Detail(int ID)
{
var Details = (from x in repo.GetBreakdown(ID) select new BreakdownDetailViewModel {Machine_Status=x.tblMachine_Status.Machine_Status, MB_ID=x.MB_ID});
return View(Details);
}
All working as needed now =]
Here's my issue,
I'm using a namespace to remove ambiguity from a factory class which is creating domain objects from entity framework entity objects (a POCO factory,.. if that makes sense!). Call me old fashioned but I like things this way :-)
The namespaces I'm working with are aliased as such -
using Entities = DataAccess.Models.AccessControl;
using Cases = DomainModel.BusinessObjects.Implimentations.Cases;
Now, the DomainModel.BusinessObjects.Implimentations.Cases namespace only has one type so far called CaseType. However whilst I was working on another type which consumes the CaseType class I noticed that when I 'dot' into the Cases alias, it points to a totally different namespace in my DataAccess assembly and gives me the CaseTypeFactory in intellisense.
So I checked the CaseType and CaseTypeFactory classes and they are namespaced correctly. What in god's name is going on? I really can't work this one out.
Here's the code for the CaseType and CaseTypeFactory if it helps.
CaseTypeFactory
using Domain = DomainModel.BusinessObjects.Implimentations.Cases;
using Entities = DataAccess.Models.AccessControl;
using Interfaces.DataAccess;
namespace DataAccess.Factories.Cases
{
public class CaseTypeFactory :
IEntityPOCOFactory<Domain.CaseType, Entities.CaseType>
{
#region IEntityPOCOFactory<CaseType,CaseType> Members
public Domain.CaseType CreatePOCO(Entities.CaseType entity)
{
return new Domain.CaseType(entity.Id, entity.Name, entity.LastChanged);
}
public IList<Domain.CaseType> CreatePOCOs(
IEnumerable<Entities.CaseType> entities)
{
var toReturn = new List<Domain.CaseType>();
foreach (var entity in entities)
{
toReturn.Add(CreatePOCO(entity));
}
return toReturn;
}
#endregion
}
}
CaseType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.BusinessObjects.Base;
namespace DomainModel.BusinessObjects.Implimentations.Cases
{
public class CaseType : NamedNumberedAndVersioned
{
public CaseType(string name, DateTime lastChanged)
: this(0, name, lastChanged) { }
public CaseType(int id, string name, DateTime lastChanged)
: base(id, name, lastChanged) { }
public void Update(string name)
{
this.Name = name;
}
}
}
It's probably worth mentioning I'm working with .Net 4.0 / VS2010
Any help would be massively appreciated.
Thanks in advance.
Is the code you're writing in the DataAccess.Factories namespace? If so, then Cases will indeed resolve to DataAccess.Factories.Cases first.
Two options:
Use an alias which isn't also the name of another namespace, e.g.
using DomainCases = ...
Use :: instead of . to force it to use the alias:
IEntityPOCOFactory<Cases::CaseType, Whatever>
I'd personally go for the first option to make things clearer... or try to avoid requiring namespace aliases to start with.