Rectangle 27 15

Create a helper class to create the client:

I agree with TheWhiteRabbit's answer but if you have a lot of calls using HttpClient the code seems a bit repetitive imo.

public static class ClientHelper
{
    // Basic auth
    public static HttpClient GetClient(string username,string password)
    {
            var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));

            var client = new HttpClient(){
                DefaultRequestHeaders = { Authorization = authValue}
                //Set some other client defaults like timeout / BaseAddress
            };
            return client;
    }

    // Auth with bearer token
    public static HttpClient GetClient(string token)
    {
            var authValue = new AuthenticationHeaderValue("Bearer", token);

            var client = new HttpClient(){
                DefaultRequestHeaders = { Authorization = authValue}
                //Set some other client defaults like timeout / BaseAddress
            };
            return client;
    }
}
using(var client = ClientHelper.GetClient(username,password))
{
    //Perform some http call
}

using(var client = ClientHelper.GetClient(token))
{
    //Perform some http call
}

Does not win a beauty prize but works great :)

public static class HttpClientExtentions
    {
        public static AuthenticationHeaderValue ToAuthHeaderValue(this string username, string password)
        {
            return new AuthenticationHeaderValue("Basic",
        Convert.ToBase64String(
            System.Text.Encoding.ASCII.GetBytes(
                $"{username}:{password}")));
        }
    }
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = _username.ToAuthHeaderValue(_password); 
}

Again I think 2 above options make the client using statement a bit less repetitive. Keep in mind that it's best practice to reuse the HttpClient if you are making multiple http calls but I think that's a bit out of scope for this question.

c# - Setting Authorization Header of HttpClient - Stack Overflow

c# rest oauth windows-runtime
Rectangle 27 15

Create a helper class to create the client:

I agree with TheWhiteRabbit's answer but if you have a lot of calls using HttpClient the code seems a bit repetitive imo.

public static class ClientHelper
{
    // Basic auth
    public static HttpClient GetClient(string username,string password)
    {
            var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));

            var client = new HttpClient(){
                DefaultRequestHeaders = { Authorization = authValue}
                //Set some other client defaults like timeout / BaseAddress
            };
            return client;
    }

    // Auth with bearer token
    public static HttpClient GetClient(string token)
    {
            var authValue = new AuthenticationHeaderValue("Bearer", token);

            var client = new HttpClient(){
                DefaultRequestHeaders = { Authorization = authValue}
                //Set some other client defaults like timeout / BaseAddress
            };
            return client;
    }
}
using(var client = ClientHelper.GetClient(username,password))
{
    //Perform some http call
}

using(var client = ClientHelper.GetClient(token))
{
    //Perform some http call
}

Does not win a beauty prize but works great :)

public static class HttpClientExtentions
    {
        public static AuthenticationHeaderValue ToAuthHeaderValue(this string username, string password)
        {
            return new AuthenticationHeaderValue("Basic",
        Convert.ToBase64String(
            System.Text.Encoding.ASCII.GetBytes(
                $"{username}:{password}")));
        }
    }
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = _username.ToAuthHeaderValue(_password); 
}

Again I think 2 above options make the client using statement a bit less repetitive. Keep in mind that it's best practice to reuse the HttpClient if you are making multiple http calls but I think that's a bit out of scope for this question.

c# - Setting Authorization Header of HttpClient - Stack Overflow

c# rest oauth windows-runtime
Rectangle 27 16

I saw different answers and came up with a class helper:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}

So in View (or master/layout) you can use it like so (Razor syntax):

<div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>

c# - How can I return the current action in an ASP.NET MVC view? - Sta...

c# asp.net-mvc
Rectangle 27 2

I'm assuming the Helper Class is not Spring-managed. There is the option of using @Configurable (requires AspectJ) for this class. Take a look at the Documentation for more info.

Example : I have too much code in one method in @Service and I want to create a new class out of it (class that represents Video). I'm doing it through "new" operator and passing that object in constructor, but I also have to pass a repository with it, because I cannot autowire in that class. Is this bad thing to do ?

Can't this logic be abstracted in a dedicated Service bean?

Yes, that's what I tried at first, but I need to use private variables and multiple private methods. Is this thing that should be done in service bean ?

Say you have ServiceA that is the one we are talking about. With all the private methods and other Beans that are needed for the say HelperA class. It sounds like HelperA is dependent on ServiceA rather then other way around? If this is not the case please post some code since this gets hard to track

Ok I understand. Basically the VideoUploadHelper class has no reason for existence since it requires all dependencies of VideoUploadService, the VideoUploadService itself along with the Model. You can do all that within VideoUploadService directly. But not on Private methods but rather on Protected so you are able to test them. By the way is this a Controller class? Looks like it because of the Model. Also if both your UploadServices have same Interface I suggest you @Autowired List<UploadService> and iterate on them agnostic of the impl to upload the video.

java - How to get autowired beans in Helper class using Spring - Stack...

java spring spring-mvc spring-boot dependency-injection
Rectangle 27 18

Set a value in the ViewData in the controller rendering your view keye...

Looking through the ASP.NET MVC 2 source code reveals some solutions to this problem. Essentially, any SelectListItem in the SelectList passed in the helper extension method that has the Selected property set to true does not have any bearing over the <option> element rendered with the selected attribute applied for the item.

The selected attribute on <option> elements is determined by

1) checking that the helper extension method was passed a SelectList. If this is null, the framework will look in the ViewData for a value corresponding to the key that is the view model property for which you wish to render the drop down list for. If the value is a SelectList, this will be used to render the <select> including taking any selected values, so long as the model state for the model property is null.

2) If a SelectList has been passed in the helper extension method and the model state for the model property is null, the framework will look in the ViewData for a default value, using the model property name as the key. The value in view data is converted to a string and any items in the SelectList passed to the helper extension method that have a value (if no value is set, then the Text will be checked) that matches the default value will have the Selected property set to true which in turn will render an <option> with the attribute selected="selected".

Putting this together, there are two plausible options that I can see to have an option selected and use the strongly typed DropDownListFor:

Using the following view model

public class CategoriesViewModel
{
    public string SelectedCategory { get; private set ; }
    public ICollection<string> Categories { get; private set; }

    public CategoriesViewModel(string selectedCategory, ICollection<string> categories)
    {
        SelectedCategory = selectedCategory;
        Categories = categories;
    }
}
public class CategoriesController
{
    [HttpGet]
    public ViewResult Select()
    {
        /* some code that gets data from a datasource to populate the view model  */
        ICollection<string> categories = repository.getCategoriesForUser();
        string selectedCategory = repository.getUsersSelectedCategory();

        CategoriesViewModel model = new CategoriesViewModel(selectedCategory, categories);

        return View(model);
    }

    [HttpPost]
    public ActionResult Select(CategoriesViewModel model)
    {
        /* some code that does something */
    }
}

and in the strongly typed view

<%: Html.DropDownListFor(m => m.SelectedCategory, Model.Categories.Select(c => new SelectListItem { Text = c, Value = c }), new { @class = "my-css-class" }) %>

@RickAndMSFT Your example links do not use DropDownListFor, so not much of a help.

asp.net mvc - DropDownListFor in EditorTemplate not selecting value - ...

asp.net-mvc
Rectangle 27 18

Set a value in the ViewData in the controller rendering your view keye...

Looking through the ASP.NET MVC 2 source code reveals some solutions to this problem. Essentially, any SelectListItem in the SelectList passed in the helper extension method that has the Selected property set to true does not have any bearing over the <option> element rendered with the selected attribute applied for the item.

The selected attribute on <option> elements is determined by

1) checking that the helper extension method was passed a SelectList. If this is null, the framework will look in the ViewData for a value corresponding to the key that is the view model property for which you wish to render the drop down list for. If the value is a SelectList, this will be used to render the <select> including taking any selected values, so long as the model state for the model property is null.

2) If a SelectList has been passed in the helper extension method and the model state for the model property is null, the framework will look in the ViewData for a default value, using the model property name as the key. The value in view data is converted to a string and any items in the SelectList passed to the helper extension method that have a value (if no value is set, then the Text will be checked) that matches the default value will have the Selected property set to true which in turn will render an <option> with the attribute selected="selected".

Putting this together, there are two plausible options that I can see to have an option selected and use the strongly typed DropDownListFor:

Using the following view model

public class CategoriesViewModel
{
    public string SelectedCategory { get; private set ; }
    public ICollection<string> Categories { get; private set; }

    public CategoriesViewModel(string selectedCategory, ICollection<string> categories)
    {
        SelectedCategory = selectedCategory;
        Categories = categories;
    }
}
public class CategoriesController
{
    [HttpGet]
    public ViewResult Select()
    {
        /* some code that gets data from a datasource to populate the view model  */
        ICollection<string> categories = repository.getCategoriesForUser();
        string selectedCategory = repository.getUsersSelectedCategory();

        CategoriesViewModel model = new CategoriesViewModel(selectedCategory, categories);

        return View(model);
    }

    [HttpPost]
    public ActionResult Select(CategoriesViewModel model)
    {
        /* some code that does something */
    }
}

and in the strongly typed view

<%: Html.DropDownListFor(m => m.SelectedCategory, Model.Categories.Select(c => new SelectListItem { Text = c, Value = c }), new { @class = "my-css-class" }) %>

@RickAndMSFT Your example links do not use DropDownListFor, so not much of a help.

asp.net mvc - DropDownListFor in EditorTemplate not selecting value - ...

asp.net-mvc
Rectangle 27 327

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

I could not find this class. I use NewtonSoft Json.net 3.5.

It appears this functionality has been moved to the Newtonsoft.Json.Converters.XmlNodeConverter class in JSON.NET 3.5: james.newtonking.com/projects/json/help/html/

I looked at there but your examples codes are not there. Any example codes to use the new libraries to do the conversions?

Surprise surprise -- this is the impedance between XML and JSON, and the reason why it is (IMO) not a good idea to directly convert between the two. But, hey, there are lots of devs who strongly disagree here (as per downvotes on my answer) and don't mind these accidental data conversions or potential data loss...

@StaxMan: I think everyone can agree that there's no standardized way to represent an XML document in JSON format. Your answer was probably downvoted because it didn't actually answer the question. The OP wasn't asking if he should do the conversion, but rather if he could do it using tools already at his disposal.

c# - How to convert JSON to XML or XML to JSON? - Stack Overflow

c# json xml json.net
Rectangle 27 327

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

I could not find this class. I use NewtonSoft Json.net 3.5.

It appears this functionality has been moved to the Newtonsoft.Json.Converters.XmlNodeConverter class in JSON.NET 3.5: james.newtonking.com/projects/json/help/html/

I looked at there but your examples codes are not there. Any example codes to use the new libraries to do the conversions?

Surprise surprise -- this is the impedance between XML and JSON, and the reason why it is (IMO) not a good idea to directly convert between the two. But, hey, there are lots of devs who strongly disagree here (as per downvotes on my answer) and don't mind these accidental data conversions or potential data loss...

@StaxMan: I think everyone can agree that there's no standardized way to represent an XML document in JSON format. Your answer was probably downvoted because it didn't actually answer the question. The OP wasn't asking if he should do the conversion, but rather if he could do it using tools already at his disposal.

c# - How to convert JSON to XML or XML to JSON? - Stack Overflow

c# json xml json.net
Rectangle 27 309

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

I could not find this class. I use NewtonSoft Json.net 3.5.

It appears this functionality has been moved to the Newtonsoft.Json.Converters.XmlNodeConverter class in JSON.NET 3.5: james.newtonking.com/projects/json/help/html/

I looked at there but your examples codes are not there. Any example codes to use the new libraries to do the conversions?

Surprise surprise -- this is the impedance between XML and JSON, and the reason why it is (IMO) not a good idea to directly convert between the two. But, hey, there are lots of devs who strongly disagree here (as per downvotes on my answer) and don't mind these accidental data conversions or potential data loss...

@StaxMan: I think everyone can agree that there's no standardized way to represent an XML document in JSON format. Your answer was probably downvoted because it didn't actually answer the question. The OP wasn't asking if he should do the conversion, but rather if he could do it using tools already at his disposal.

c# - How to convert JSON to XML or XML to JSON? - Stack Overflow

c# json xml json.net
Rectangle 27 9

Yes, it's perfectly reasonable to want to extract your functionality out into another method. The best way to do this in my opinion is using a class continuation, which you can put your private method declarations in. It can go above your @implementation block in your .m file, so it's not in the public header.

@interface MyClass ()
- (void)_privateMethod:(id)arg;
@end

The difference between a class continuation and a normal category (such as @interface MyClass (PrivateMethods)) is that the compiler will require you to implement the methods in your main @implementation block, rather than having a separate @implementation MyClass (PrivateMethods) block. This is arguably desirable when implementing helper methods like you described.

About prefixing methods with an underscore: "Dont use the underscore character as a prefix for your private methods. Apple reserves this convention."

ClassA
MyClass
ClassA.h
@interface ClassA /*public methods declarations*/ @end
ClassA.m
@interface ClassA () /*private method declarations*/ @end
@implementation ClassA /*both private & public method implementations*/ @end

c# - Proper Objective-C Helper "Wannabe" Private methods? - Stack Over...

c# objective-c private-members
Rectangle 27 16

Try using the proper overload of the ActionLink helper (yeah there are gazillions of overloads):

@Html.ActionLink(
    "Sign Out",                    // linkText
    "LogOff",                      // actionName
    "Account",                     // routeValues
    new { @class = "btn blue" }    // htmlAttributes
)

See why your code is not working?

Yeah, Microsoft did a hell of a mess with those overload and if you are not careful you get caught into the trap.

Solution: read MSDN or use Visual Studio Intellisense (F12 while your cursor is over the ActionLink helper).

For that reason I prefer to write it in a mode explicit manner using C# 4.0 named parameters:

@Html.ActionLink(
    linkText:       "Sign Out",
    actionName:     "LogOff",
    controllerName: "Account",
    routeValues:    null,
    htmlAttributes: new { @class = "btn blue" }
)

razor - Adding a class to Html.ActionLink - ASP.NET MVC 3 - Stack Over...

asp.net-mvc-3 razor
Rectangle 27 13

No, there is no way to declare local functions in a class. You can of course declare (static) helper methods and mark them as "private" using underscore prefixes, but that's probably not what you want. And you can always declare the local function inside of a method.

But if you need it multiple times then the only way to go is to place it next to the class. If you are writing a script, an IEFE will be necessary as usual. If you're writing an ES6 module (which is the preferred solution), privacy is trivial: just don't export the function.

If you place the function next to the class, it won't have access to this, so you'll have to pass it as a parameter.

@DanDascalescu Sure, I think the OP did deliberately ask for a function though not a method.

javascript - How to declare local function inside ES6 class? - Stack O...

javascript class ecmascript-6
Rectangle 27 41

Reachability is a network helper utility class, its used to get various informations about the connection status

What is the main purposes of Reachability?

  • and to register your listeners to get informed when connectivity changes

Is this the main purpose of Reachability, to show the user a message?

No of course, its main usage is either to test if there is internet connectivity, or to get notified if the connectivity changes

Yes you could use it, for example what i normally do in my project is to save all the request that has been made to a remote server, lets say i want to download 10 files,

When any file fails the download process due to no internet connection, i save them to an array of failed downloads,

When reachability informs me that the internet connection has been restored, i iterate through this array and start the download process again

What is the proper use of Reachability?

Yes that is what i do, in my projects i only have 1 instance of a download manager class, and this class has the only alive instance of Reachability

Or should I check myself the reachability status before every network request?

You can do that without having multiple instance of Reachability classes, what i normally do, is to have a method inside my download manager that tells me using Reachability if there is connection or not.

Is it enough to use reachabilityWithHostName or do I need also reachabilityForLocalWiFi and reachabilityForInternetConnection?

Am not sure about this one, but what i normally do is to test connectivity on all the means, i dont differentiate between 3g or wifi, however there are some implementation that this info (wifi or 3g) could be useful

Thanks for your reply, can u please check the "one more thing" that I added to the question

Am completely unaware of that, i have 5+ apps on the appstore, they all use Reachability, i used reachability as i described above in the answer, so i dont know about what must be implemented, i normally implement what i need

You said that one of the main purpose of reachability is "to register your listeners to get informed when connectivity changes", but it does not give callback every time (try to switch routers and check).

iphone - How to use iOS Reachability - Stack Overflow

iphone objective-c ios nsurlconnection reachability
Rectangle 27 4

You could use a helper class like that:

public class DefaultValueHelper
{
    public static void InitializeDefaultValues<T>(T obj)
    {
        var properties =
            (from prop in obj.GetType().GetProperties()
             let attr = GetDefaultValueAttribute(prop)
             where attr != null
             select new
             {
                Property = prop,
                DefaultValue = attr.Value
             }).ToArray();
        foreach (var p in properties)
        {
            p.Property.SetValue(obj, p.DefaultValue, null);
        }

    }

    private static DefaultValueAttribute GetDefaultValueAttribute(PropertyInfo prop)
    {
        return prop.GetCustomAttributes(typeof(DefaultValueAttribute), true)
                   .Cast<DefaultValueAttribute>()
                   .FirstOrDefault();
    }
}

And call InitializeDefaultValues in the constructor of your class.

class Foo
{
    public Foo()
    {
        DefaultValueHelper.InitializeDefaultValues(this);
    }

    [DefaultValue("(no name)")]
    public string Name { get; set; }
}

EDIT: updated version, which generates and caches a delegate to do the initialization. This is to avoid using reflection every time the method is called for a given type.

public static class DefaultValueHelper
{
    private static readonly Dictionary<Type, Action<object>> _initializerCache;

    static DefaultValueHelper()
    {
        _initializerCache = new Dictionary<Type, Action<object>>();
    }

    public static void InitializeDefaultValues(object obj)
    {
        if (obj == null)
            return;

        var type = obj.GetType();
        Action<object> initializer;
        if (!_initializerCache.TryGetValue(type, out initializer))
        {
            initializer = MakeInitializer(type);
            _initializerCache[type] = initializer;
        }
        initializer(obj);
    }

    private static Action<object> MakeInitializer(Type type)
    {
        var arg = Expression.Parameter(typeof(object), "arg");
        var variable = Expression.Variable(type, "x");
        var cast = Expression.Assign(variable, Expression.Convert(arg, type));
        var assignments =
            from prop in type.GetProperties()
            let attr = GetDefaultValueAttribute(prop)
            where attr != null
            select Expression.Assign(Expression.Property(variable, prop), Expression.Constant(attr.Value));

        var body = Expression.Block(
            new ParameterExpression[] { variable },
            new Expression[] { cast }.Concat(assignments));
        var expr = Expression.Lambda<Action<object>>(body, arg);
        return expr.Compile();
    }

    private static DefaultValueAttribute GetDefaultValueAttribute(PropertyInfo prop)
    {
        return prop.GetCustomAttributes(typeof(DefaultValueAttribute), true)
                   .Cast<DefaultValueAttribute>()
                   .FirstOrDefault();
    }
}

@DustinDavis, yes, but it doesn't mean you should never use it... Of course this is not a good solution if you must create many instances of the class.

Of course, an option would be to generate and cache a delegate that initializes the properties. That way the reflection would be done only once.

Of course. I use it often, but i assume he is going to want this functionality on a big scale. It would be nice if there were some attribute framework that we could work with.

Put up an example of the delegate cache and i'll give you +1

visual studio 2010 - How do you give a C# Auto-Property a default valu...

c# visual-studio-2010 .net-4.0 postsharp
Rectangle 27 73

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

In your controller, you might have an action like:

[HttpPost]
public ActionResult MyAction(MyModel model) 
{
}

And a model like:

public class MyModel 
{
    public string Name { get; set; }
}

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

Thanks Kirk, good info on what happens in the controller and model as well.

Actually, you get a COMPILER error, not a RUNTIME error if you rename the property. That's the point, failing on compile, not run.

@Mystere Man, the views are usually not compiled (when you build your solution). It is a manual step to have VS compile them for you.

Well actually it is a compile error that happens at runtime (usually).

Html.Hidden("Name", "Value")
<input id="Name" name="Name" type="hidden" value="Value">

c# - What is the difference between Html.Hidden and Html.HiddenFor - S...

c# asp.net-mvc model-view-controller html-helper
Rectangle 27 172

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module.

By the way, using Module is not really subjective and it's not deprecated. Indeed you must use a Module when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it's required to use Modules.

Quite right, although I can use a private constructor to prevent instantiation and the NotInheritable modifier. Slightly uglier than a plain old Module, but has the same effect. Thanks for the pointer to the use of Modules in the Framework; I'll look into that.

Under the hood, they are just compiled to classes with [StandardModule] attribute. Also, using Module forces you not to have non-Shared things there which is a good thing.

Modules are not the same as static classes in C#. Methods in a module are effectively global if they are in an imported namespace.

@JaredPar: My wording is probably bad. I should have said VB counterparts to C# static classes. From that statement, I meant to say using a Module makes sense where you'd write a static class in C#.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Classes vs. Modules in VB.NET - Stack Overflow

vb.net
Rectangle 27 3

You can actually bind to static properties as long as the class is not a static class. So using the previous example of the Helper class:

public class Helper
{
    public static string Value{ get {return Page.Test;} }
}

The XAML will stay the same.

Hi Sam, will it notify the binding if the value of Page.Test has been updated?

Hmmm, I cannot get it working. What the xaml syntax, can you add it here

c# - Using static objects in XAML that were created in code in Silverl...

c# .net wpf silverlight xaml
Rectangle 27 338

Here's a nice and simple cache helper class/service I use:

using System.Runtime.Caching;  

public class InMemoryCache: ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}
cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())

I've adapted this so that the caching mechanism is used per user session by using HttpContext.Current.Session instead. I've also put a Cache property on my BaseController class so its easy access and updated the constructor allow for DI for unit testing. Hope this helps.

This class shouldn't depend on HttpContext. I simplified it just for example purpose here. Cache object must be inserted through constructor - it can be replaced then with other caching mechanisms . All this is achieved with IoC/DI, along with static (singleton) life cycle.

This is a basic setup that will work. There are only two things I don't like about it: it requires the code know about both the repository and the caching and it also requires that you know the cache key when asking for the data. This means that you run the risk of having two keys for the same data. Also, it is a pain to look up the key. The caching should be baked in and automated somewhere.

@Brendan - and worse still, it has magic strings in place for the cache keys, rather than inferring them from the method name and parameters.

This is an awesome low level solution. Like others have alluded to, you'd want to wrap this in a type safe, domain-specific class. Accessing this directly in your controllers would be a maintenance nightmare because of the magic strings.

asp.net mvc - How to cache data in a MVC application - Stack Overflow

asp.net-mvc database caching
Rectangle 27 338

Here's a nice and simple cache helper class/service I use:

using System.Runtime.Caching;  

public class InMemoryCache: ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}
cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())

I've adapted this so that the caching mechanism is used per user session by using HttpContext.Current.Session instead. I've also put a Cache property on my BaseController class so its easy access and updated the constructor allow for DI for unit testing. Hope this helps.

This class shouldn't depend on HttpContext. I simplified it just for example purpose here. Cache object must be inserted through constructor - it can be replaced then with other caching mechanisms . All this is achieved with IoC/DI, along with static (singleton) life cycle.

This is a basic setup that will work. There are only two things I don't like about it: it requires the code know about both the repository and the caching and it also requires that you know the cache key when asking for the data. This means that you run the risk of having two keys for the same data. Also, it is a pain to look up the key. The caching should be baked in and automated somewhere.

@Brendan - and worse still, it has magic strings in place for the cache keys, rather than inferring them from the method name and parameters.

This is an awesome low level solution. Like others have alluded to, you'd want to wrap this in a type safe, domain-specific class. Accessing this directly in your controllers would be a maintenance nightmare because of the magic strings.

asp.net mvc - How to cache data in a MVC application - Stack Overflow

asp.net-mvc database caching
Rectangle 27 338

Here's a nice and simple cache helper class/service I use:

using System.Runtime.Caching;  

public class InMemoryCache: ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}
cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())

I've adapted this so that the caching mechanism is used per user session by using HttpContext.Current.Session instead. I've also put a Cache property on my BaseController class so its easy access and updated the constructor allow for DI for unit testing. Hope this helps.

This class shouldn't depend on HttpContext. I simplified it just for example purpose here. Cache object must be inserted through constructor - it can be replaced then with other caching mechanisms . All this is achieved with IoC/DI, along with static (singleton) life cycle.

This is a basic setup that will work. There are only two things I don't like about it: it requires the code know about both the repository and the caching and it also requires that you know the cache key when asking for the data. This means that you run the risk of having two keys for the same data. Also, it is a pain to look up the key. The caching should be baked in and automated somewhere.

@Brendan - and worse still, it has magic strings in place for the cache keys, rather than inferring them from the method name and parameters.

This is an awesome low level solution. Like others have alluded to, you'd want to wrap this in a type safe, domain-specific class. Accessing this directly in your controllers would be a maintenance nightmare because of the magic strings.

asp.net mvc - How to cache data in a MVC application - Stack Overflow

asp.net-mvc database caching