Questions tagged [extension-methods]

0

votes
2

answer
34

Views

How to update a global variable inside `where` clause in LINQ?

I want to filter a list using LINQ with Where extension method. But apart from filtering I also want to update a global variable inside Where. However I cannot do it. Consider this example: var list = new List { '1', '2', '3', '4', '5' }; bool flag = false; var newList = list.Where(item => { flag =...
1

votes
1

answer
43

Views

How to define an extention method for a non-generic array?

I cannot figure out what is the correct syntax to define an extension method on a non-generic array. This question deals with generic arrays, but trying a similar construct for a byte array doesn't work. I have tried a lot of options: type Byte ``[]`` with type byte ``[]`` with type Byte array with...
Kapol
1

votes
2

answer
71

Views

invoke the extension method of a class without using static class but by using class iteslf using reflection

I want invoke Method2 which is an extension method of a MyClass using MyClass type. I am wondering if this is possible or not. using System; using System.Linq; using System.Reflection; namespace ConsoleApplication9 { public static class MyClassStatic { public static void Method2(this ConsoleApp2.MyC...
D J
1

votes
0

answer
43

Views

I have trouble with Message Filter Extension about extracting time or state of message handled

I'm building an app that has Message Filter Extension. And I need to know what message was filtered. But I don't have permission to write in share groups. What I need to know just time and state of message. I have tried so many ways but they did't work .
Huy Bùi
1

votes
1

answer
50

Views

LinqToSql - Extension Method Resolution

I understand the preference is given to instance method over extension method during compile time resolution. However for LinqToSQL (or for LinqtoXXX) : Table orders = context.Orders var query = orders.Where(o=>o.name=='xyz') What is deciding factor for resolving above Where method of Queryable clas...
Rahul Agarwal
0

votes
3

answer
36

Views

How do I find properties and fields for a type and then read them from a collection of that type?

i have list of T and need to create a string joined by '\t' with several properties of this type. string str = '1,2,3;2,3,4;4,5,6'; var arr = str .Split(';') .Select(x => x.Split(',')) .Select(x => new { first = x[0], second = x[1], third = x[2] }) .ToList(); now arr is: Enumerable.WhereSelectArra...
1

votes
0

answer
33

Views

Is there any way of extending the Point (or any other) type with overloaded operators?

In a loop within an OnPaint event, I draw a string using DrawString. Before drawing the string, the client rectangle oRect needs to be offset by some pixels. Being in a loop, it is clear that this offsetting must be undone, or they will add up. This works as intended: Protected Overrides Sub OnPaint...
Herb
1

votes
1

answer
170

Views

Chrome.tabs.executeScript(); + .addEventListener(“click”, …); to inject code into active webpage through chrome extension

I am trying to make a chrome extension that injects code into the active webpage through the popup.html file... popup.html > hello this is a test document.getElementById('Mr_Button-Click_Extend').addEventListener('click', TheGreatEmbed() { chrome.tabs.executeScript(null, {file: 'js/inject.js'}); })...
1

votes
1

answer
20

Views

Extending Swift type with method that requires a generic

My question is about extending a type with a method that requires a generic. I want to extend IndexPath and add a method to check if it's valid in a given NSFetchedResultsController. Here's my extension: public extension IndexPath { func isValid(in fetchedResultsController: NSFetchedResultsControlle...
nambatee
1

votes
1

answer
72

Views

Why can't I reference extension methods with internal visibility from my .cshtml pages? [duplicate]

This question already has an answer here: How come internal members in my view model aren't accessible in the view? 1 answer I have an ASP.NET Core 2.1 default project (upgraded from 2.0 without using the new 'default UI' facilities, as the plan is to customise the default views and controllers). I...
Hammerite
1

votes
0

answer
84

Views

Trying to write patch function for data classes in kotlin

Here is my problem. Let's say we have a data class User data class User(var name: String? = null, var age: Int? = null) And we have 4 user objects val oldUser = User('user1', 10) val newUser1 = User('user2', null) val newUser2 = User(null, 60) val newUser3 = User(null, null) I want to write an exte...
Prashant Gupta
1

votes
0

answer
238

Views

How to add extension method in .net core api controller

I have to a modify the IActionResult on bases of certain property of my custom object I am trying different way to change but neither worked public static class ExtensionMethods { public static IActionResult Change(this Controller controller, ExternalResponse obj) { if (case 1) { return Ok(extResp)...
Kamran Shahid
1

votes
3

answer
60

Views

Is it possible to get the original type of a list when all you have is a “WhereEnumerableIterator” of that list?

It may be simple but nevertheless it has caused us a bit of headache over the past few hours. Long story short: We need to fix a memory leak and the way to do it is to return the original list without creating a new instance of MyBindingList if ToBindingList is invoked on a list that is already of t...
kerbou
1

votes
1

answer
30

Views

is there any workaround to put stored properties into extensions in swift?

I'm creating my project all in code and it was a bit confusing and difficult to read because there were several lines just to set up UIElements in my code... so I tried to insert this bulky part into an extension and got an error saying that stored properties can't go into extensions, after that my...
Lucas
1

votes
1

answer
54

Views

How can we create extension methods for non-global interfaces in TypeScript?

I'm currently learning TypeScript but am thoroughly stumped at how to implement extension methods for non-global interfaces. Consider the following example: say I have an interface defining a Cart like so: interface Cart { id(): string, name(): string, quantity(): number /* Other methods */ } Then,...
M B
1

votes
0

answer
32

Views

Using Extension To Access CollectionView In Separate Class

I have a class called PickerFilterClass that access the YNDropDownView library and in there I create a pickerview in PickerFilterClass's extension. I want to the pickerview help sort a collectionview in another class called RestaurantDetails. I am trying to use the pickerview didselect function to a...
A True Novice
1

votes
0

answer
52

Views

ASP.NET MVC 5 with NUnit and Moq; how to mock RoleManager so it is possible to setup it's extension methods?

I have ASP.NET MVC 5 (.NET Framework) app with Entity Framework 6.2. I'm using NUnit and Moq frameworks for testing. I need to test if roleResult.Succeeded is true when RoleExists() extension(static) method returns false for 'User' role. HomeController.cs : private ApplicationDbContext _db; private...
rafineria888
1

votes
0

answer
34

Views

Is it possible to get rid of recursion in my Combinations extension? Or maybe it is not needed at all?

I have written a small Extension class for generating Combinations of elements (no repetitions and no permutations). I use recursion and I wonder how to get rid of it and if it is needed at all. Could it be that C# compiler will convert it into iterations though (the methods does not seem to be tail...
Dmitry Merkis
1

votes
2

answer
30

Views

Create an extension method to override from different classes

I have different classes that all overrides ToString() function and they all use the same logic And what I'm doing now is that I'm calling a static method for of those classes and I wanted to know its possible to create an extension method that will be called from those all those ToString() methods...
styx
0

votes
0

answer
4

Views

Does UNNotificationServiceExtension allow access to user location iif permissions were granted - iOS

I have an app which sends user's push notifications based on their locations but I would like to do a second location check on the client just before displaying the push notification (since server-side data can often be outdated or incorrect) By setting mutable-content to 1 in the PUSH payload and i...
Zigglzworth
1

votes
1

answer
35

Views

Implement a Kotlin interface in another file

I'd like to implement some interface methods in another file, using extensions. I have a feeling it's not possible, but I'd love to do that. Is this possible? Here is the idea : MyClass.kt class MyClass : MyInterface { } MyClassExtension.kt override MyClass.MyInterface.method1() { } override MyClas...
lorenzo
1

votes
0

answer
30

Views

TypeScript extend native objects in a safe way like extension functions via TS transformer

TypeScript provides ability to transform AST during compilation. I wonder if it could be used to extend native objects Object, Array, String in a safe way without tainting its prototypes. Let's add isEmpty() method to Object, Array, String etc. First, we trick TypeScript with a false declaration th...
Alexey Petrushin
1

votes
0

answer
44

Views

Action Extensions - how do I know when a host app support modification in place?

I'm following a tutorial to create a simple Action Extension for text. Action extension is triggered as a modal overlay from the “Share…” button in the systemwide text selection context menu (or using the Action button in apps that handle simple text and support it). The modified are made on...
Cue
1

votes
0

answer
87

Views

R: Expand an S3 method defined in another package

Let's say that package A defines and documents foo() and implements it for bar1 objects. In a new package B, I would like to expand this method and add its support for bar2 objects. Currently, I start by reexporting the method: #' @rdname foo #' @importFrom A foo #' @export A::foo And then went on e...
1

votes
1

answer
185

Views

How do I use linq to get the difference of a List<byte[]> and an anonymous type with a byte[] property?

I am new to Linq and extension methods and I guess I just can't grasp the use of all the extension methods yet. I am reading a bunch of files, and after one has been read, I'm storing the hash value of the file into a database (the file names change, and they are moved around). Periodically, I want...
scottm
1

votes
1

answer
2.5k

Views

Extending IEnumerable to Return BindingList

In a previous question on Stack Overflow, I had run into an issue with returning an EF query to the DataGridView. Of course I'd run into an issue. However, I added an extension method that still has me baffled since it isn't working. It seems like it should, but for some reason it's not. public stat...
Jason N. Gaylord
1

votes
5

answer
204

Views

php extending classes

I'm using a salesforce class called SforceEnterpriseClient. I've referenced that class many places in my application. I want to extend that class to give it the ability to return a single array from a 1 row recordset, right now the record set is about 3 levels deep. There's a few other things I w...
bbutle01
1

votes
1

answer
437

Views

RenderAction in an HtmlHelperExtension Method?

I am trying to call the RenderAction Extension Method within my own Html Helper: System.Web.Mvc.Html.ChildActionExtensions.RenderAction(helper, 'account', 'login'); this is so that along with some additional logic, I would like all html helpers to use a common method name structure when calling it o...
TimLeung
1

votes
1

answer
602

Views

Shorthand for instantiation and initialization using an extension method

Is there any shorthand for using an extension method to instantiate and initialise an object? My aim is to abstract-away and encapsulate the code required to instantiate and initialise an instance of MyType suitable for unit testing. Example: //... //convoluted client code - I'd like to avoid the nu...
Ben
1

votes
1

answer
187

Views

Get the object instance which contains a specified property

This question will probably take a while to explain, and I'll need to provide background... This is just something I'm playing about with and isn't for production, but at the moment I have some code which looks like this: var myDataModel = new DataModel(); myDataModel.PropertyChanged += myDataModel_...
David_001
1

votes
2

answer
840

Views

Returning a list of items from Sitecore XSLT helper function

I'd like to return a list of items from an XSLT helper function in Sitecore. The items could conceivably be from multiple different places inside the content tree, so a simple XPath expression can't be used. I suspect that I need to do something with the XPathNodeIterator class, however I can't qui...
Matt
1

votes
4

answer
115

Views

Converting public method to extension method

In my project's core library we have a very big class, which is tending to become a God object. One of the reasons is that, over a period of time, tasks which should have been in different modules have been put into this class. For ex - class HugeClass{ public void DoModuleXJob(){} public void DoMod...
Unmesh Kondolikar
1

votes
2

answer
1.3k

Views

Few GroupJoin in one query

I'm trying to write ObjectQuery with few consistent GroupJoin, it means that there should be one main table selection + few additional LEFT JOIN. I'm doing it as following, with SelectMany method, because without it I can't access field RoleID : var routesQuery = entities.Routes.Join( entities.Loca...
Anonymous
1

votes
1

answer
292

Views

Trying to separate code in a client server model where the client isn't trusted and with minimal duplication

I am working on a client/server game (C#.NET) where I do not want to trust the client to hold any of my server side application code, but want to share objects. For example imagine you have a right hand weapon slot and a backpack that can carry additional items. Now there's a lot of server side cod...
deepee1
1

votes
1

answer
394

Views

How can I constrain T to support DataContractJsonSerializer, and not implement ISerializable everywhere?

I'm working on this extension method and am trying to constrain T so that the method doesn't apply to EVERY object... just the ones that the DataContractJsonSerializer works well with public static string ToJSONString(this object obj) { using (var stream = new MemoryStream()) { var ser = new DataCon...
random65537
1

votes
1

answer
121

Views

non-explicit extension of classes?

Scenario The system has classes declared in /system/classes/. The application has classes declared in /application/classes/. If there is class in the application folder that has the same name as a class in the system folder then the class in the application folder should extend the class in the sys...
Hailwood
1

votes
2

answer
653

Views

VB.NET Extension methods error

''' ''' Transforms an item to a list of single element containing this item. ''' ' _ Public Function ToList(Of T)(ByVal item As T) As List(Of T) Dim tList As New List(Of T) tList.Add(item) Return tList End Function usage Dim buttonControl As New System.Windows.Forms.Button Dim controls = buttonCo...
serhio
1

votes
3

answer
2k

Views

Problems with ForEach extension method over IEnumerable<Request.Files>

While doing some basic validation on the ASP.Net (4.0) Request.Files (upload) collection I decided to try it with LINQ. The collection is IEnumerable and so doesn't offer ForEach. Foolishly I decided to build an extension method that would do the job. Sorry to say not so much success... Running the...
Serexx
1

votes
2

answer
931

Views

Extension Method To Take A Dynamically Built Search Expression?

I think we are basically looking for a extension method that could take in an IQueryable and return an IQueryable based on an entire query statement and not just the where statement. Example of what we would like for a Search Method: IRepository repository = new Repository(); var results = repositor...
Blane Bunderson
1

votes
2

answer
2k

Views

Extension method used to prevent SharePoint list item event receiver help

I came across this post with a great solution to the problem of preventing the event receiver on an SPListItem firing when performing the update from outside the event receiver. The code works 100% as described and I'm impressed with the solution, the problem is I don't fully understand it. To keep...
Mark

View additional questions