I want to set the configuration parameter clientcache.minutesprogrammatically but im struggling with the config design in ImageResizer.
My approach currently is:
var lWebConfigReader = new System.Xml.XmlTextReader(#"Web.config");
var lXmlDocument = new System.Xml.XmlDocument();
lXmlDocument.Load(lWebConfigReader);
var lResizerNode = lXmlDocument.SelectSingleNode("/configuration/resizer");
var lSection = new ImageResizer.ResizerSection(lResizerNode.OuterXml);
var lConfig = new ImageResizer.Configuration.Config(lSection);
int mins = lConfig.get("clientcache.minutes", -1);
...
ImageResizer.Configuration.Config.Current.setConfigXml(lConfig.getConfigXml());
It seems a bit hacky and also doesn't work as the ClientCache plugin doesn't sent the Expires header as it normally should when clientcache.minutes is set.
What could be the issue?
After some digging in the source code i found out that in this particular case you need to alter the global configuration object as the ClientCache plugin reads the parameter via Get() from it. So my current solution is:
// read a XML where a <resizer>...</resizer> is present, in this case a typical Web.config as mentioned in the ImageResizer docs
var lWebConfigReader = new System.Xml.XmlTextReader(#"Web.config");
var lXmlDocument = new System.Xml.XmlDocument();
lXmlDocument.Load(lWebConfigReader);
// read the resizer tag to a node
var lResizerNode = lXmlDocument.SelectSingleNode("/configuration/resizer");
// create a section from the node
var lSection = new ImageResizer.ResizerSection(lResizerNode.OuterXml);
// create a new config object from the section
var lConfig = new ImageResizer.Configuration.Config(lSection);
// override the global configugration with the newly created one
ImageResizer.Configuration.Config.Current.setConfigXml(lConfig.getConfigXml());
// test the Get() call used by the ClientCache plugin
int mins = ImageResizer.Configuration.Config.Current.get("clientcache.minutes", -1);
This code could be placed in a ICurrentConfigProvider implementation or Application_Start() in Global.asax.
Related
I am new to Elasticsearch and NEST etc. using c#. So, far I have learned and managed to write a code to create an index but the problem is how do I create a second table (type). If I create it the same way then it only creates one table and not the second one.
Code:
public static void CreateIndex()
{
ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));
settings.DefaultIndex("store");
ElasticClient client = new ElasticClient(settings);
client.Indices.Delete(Indices.Index("store"));
var indexSettings = client.Indices.Exists("store");
if (!indexSettings.Exists)
{
var response = client.Indices.Create(Indices.Index("store"));
}
}
public static void CreateSeed()
{
int seedValue = 1;
int limitValue = 20000;
IList<stores> List = new List<stores>();
ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));
settings.DefaultIndex("store");
ElasticClient esClient = new ElasticClient(settings);
var item = new store() { ID = seedValue, Title = "item" + seedValue.ToString(), IsPublished = true };
var response = esClient.IndexAsync(item, idx => idx.Index("store"));
}
/// <summary>
///
/// </summary>
public static void CreateMappings()
{
ConnectionSettings settings = new ConnectionSettings(new Uri("http://localhost:9200"));
settings.DefaultIndex("store");
ElasticClient esClient = new ElasticClient(settings);
esClient.Map<stores>(m =>
{
var putMappingDescriptor = m.Index(Indices.Index("store")).AutoMap();
return putMappingDescriptor;
});
}
This create a store index and can be retrieved. However, if I create another table of different name e.g. itemsstore the same way, the older one doesn't exist anywhere.
Why? How do I create a new second table?
Looking at the example given, it looks like this will
delete "store" index
check if the "store" index exists (it won't as it was just deleted)
create a "store" index
set the default index to use as the "store" index (which will be created on indexing the first document, if it doesn't exist)
index store types into a "store" index
create a mapping for the "store" index
In summary, the example looks like it only interacts with a "store" index.
A simple example to create two indices is
var client = new ElasticClient();
var createIndexResponse = await client.Indices.CreateAsync("store");
if (!createIndexResponse.IsValid)
{
// take some action e.g. logging, exception, etc.
// To keep the example simple, just throw an exception
throw new Exception(createIndexResponse.DebugInformation);
}
createIndexResponse = await client.Indices.CreateAsync("itemsstore");
if (!createIndexResponse.IsValid)
{
throw new Exception(createIndexResponse.DebugInformation);
}
The walkthrough on building a Nuget search web application may be useful. The different branches have walkthroughs for different version of the client. For example, the 7.x branch is for NEST 7.x, with 7.x-codecomplete showing the completed example. It'll demonstrate a number of Elasticsearch and search related concepts.
This is a snipped of the c# client I created to query the tensorflow server I set up using this tutorial: https://tensorflow.github.io/serving/serving_inception.html
var channel = new Channel("TFServer:9000", ChannelCredentials.Insecure);
var request = new PredictRequest();
request.ModelSpec = new ModelSpec();
request.ModelSpec.Name = "inception";
var imgBuffer = File.ReadAllBytes(#"sample.jpg");
ByteString jpeg = ByteString.CopyFrom(imgBuffer, 0, imgBuffer.Length);
var jpgeproto = new TensorProto();
jpgeproto.StringVal.Add(jpeg);
jpgeproto.Dtype = DataType.DtStringRef;
request.Inputs.Add("images", jpgeproto); // new TensorProto{TensorContent = jpeg});
PredictionClient client = new PredictionClient(channel);
I found out that most classes needed to be generated from proto files using protoc
The only thing which I cant find is how to construct the TensorProto. The error I keep getting is : Additional information: Status(StatusCode=InvalidArgument, Detail="tensor parsing error: images")
There is a sample client (https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/inception_client.py) byt my Python skills are not sufficient to understand the last bit.
I also implemented that client in another language (Java).
Try to change
jpgeproto.Dtype = DataType.DtStringRef;
to
jpgeproto.Dtype = DataType.DtString;
You may also need to add a tensor shape with a dimension to your tensor proto. Here's my working solution in Java, should be similar in C#:
TensorShapeProto.Dim dim = TensorShapeProto.Dim.newBuilder().setSize(1).build();
TensorShapeProto shape = TensorShapeProto.newBuilder().addDim(dim).build();
TensorProto proto = TensorProto.newBuilder()
.addStringVal(ByteString.copyFrom(imageBytes))
.setTensorShape(shape)
.setDtype(DataType.DT_STRING)
.build();
ModelSpec spec = ModelSpec.newBuilder().setName("inception").build();
PredictRequest r = PredictRequest.newBuilder()
.setModelSpec(spec)
.putInputs("images", proto).build();
PredictResponse response = blockingStub.predict(r);
I am posting this because it might help someone using the VersionOne API SDK Client. I wanted to change the status of a test programmatically, to one of the following categories: Ready, InTesting, Passed, or Failed. I originally tried to change the attribute 'Status.Name' however I would get an error that the attribute is a Read-Only attribute. Another suggestion was to create a new attribute with the same name and that the new attribute would override the previous read-only attribute with the same name. However, it appears that I was looking at it backwards.
internal void TestStatusPassed(string str_TestID)
{
var testId = Oid.FromToken(str_TestID, _context.MetaModel);
var query = new Query(testId);
var testType = _context.MetaModel.GetAssetType("Test");
var sourceAttribute = testType.GetAttributeDefinition("Status.Name");
query.Selection.Add(sourceAttribute);
var result = _context.Services.Retrieve(query);
var test = result.Assets[0];
var oldSource = GetValue(test.GetAttribute(sourceAttribute).Value);
test.SetAttributeValue(sourceAttribute, "Passed");
_context.Services.Save(test);
}
This code will throw an exception "Cannot change a read-only attribute"...
I pulled the XML data for one test from the VersionOne Rest API and noticed a relation named "TestStatus" and then it had a number '9123' assigned to it. So I moved that test manually to 'In Testing' and the "TestStatus" changed to '9121'. Then I moved it to failed and the "TestStatus" changed to '155'. I repeated this with several tests from different testsets and noticed that the numbers for each status were consistent and then changed the code slightly and then I was able to programmatically change the status of each test. I changed "Status.Name" to "Status" and "Passed" to "TestStatus:9123" and now it moves the test into the passed category programmatically.
internal void TestStatusPassed(string str_TestID)
{
var testId = Oid.FromToken(str_TestID, _context.MetaModel);
var query = new Query(testId);
var testType = _context.MetaModel.GetAssetType("Test");
var sourceAttribute = testType.GetAttributeDefinition("Status");
query.Selection.Add(sourceAttribute);
var result = _context.Services.Retrieve(query);
var test = result.Assets[0];
var oldSource = GetValue(test.GetAttribute(sourceAttribute).Value);
test.SetAttributeValue(sourceAttribute, "TestStatus:9123");
_context.Services.Save(test);
}
I'm trying to use libgit2sharp to get a previous version of a file. I would prefer the working directory to remain as is, at the very least restored to previous condition.
My initial approach was to try to stash, checkout path on the file I want, save that to a string variable, then stash pop. Is there a way to stash pop? I can't find it easily. Here's the code I have so far:
using (var repo = new Repository(DirectoryPath, null))
{
var currentCommit = repo.Head.Tip.Sha;
var commit = repo.Commits.Where(c => c.Sha == commitHash).FirstOrDefault();
if (commit == null)
return null;
var sn = "Stash Name";
var now = new DateTimeOffset(DateTime.Now);
var diffCount = repo.Diff.Compare().Count();
if(diffCount > 0)
repo.Stashes.Add(new Signature(sn, "x#y.com", now), options: StashModifiers.Default);
repo.CheckoutPaths(commit.Sha, new List<string>{ path }, CheckoutModifiers.None, null, null);
var fileText = File.ReadAllText(path);
repo.CheckoutPaths(currentCommit, new List<string>{path}, CheckoutModifiers.None, null, null);
if(diffCount > 0)
; // stash Pop?
}
If there's an easier approach than using Stash, that would work great also.
Is there a way to stash pop? I can't find it easily
Unfortunately, Stash pop requires merging which isn't available yet in libgit2.
I'm trying to use libgit2sharp to get a previous version of a file. I would prefer the working directory to remain as is
You may achieve such result by opening two instances of the same repository, each of them pointing to different working directories. The Repository constructor accepts a RepositoryOptions parameter which should allow you to do just that.
The following piece of code demonstrates this feature. This creates an additional instance (otherRepo) that you can use to retrieve a different version of the file currently checked out in your main working directory.
string repoPath = "path/to/your/repo";
// Create a temp folder for a second working directory
string tempWorkDir = Path.Combine(Path.GetTempPath(), "tmp_wd");
Directory.CreateDirectory(newWorkdir);
// Also create a new index to not alter the main repository
string tempIndex = Path.Combine(Path.GetTempPath(), "tmp_idx");
var opts = new RepositoryOptions
{
WorkingDirectoryPath = tempWorkDir,
IndexPath = tempIndex
};
using (var mainRepo = new Repository(repoPath))
using (var otherRepo = new Repository(mainRepo.Info.Path, opts))
{
string path = "file.txt";
// Do your stuff with mainrepo
mainRepo.CheckoutPaths("HEAD", new[] { path });
var currentVersion = File.ReadAllText(Path.Combine(mainRepo.Info.WorkingDirectory, path));
// Use otherRepo to temporarily checkout previous versions of files
// Thank to the passed in RepositoryOptions, this checkout will not
// alter the workdir nor the index of the main repository.
otherRepo.CheckoutPaths("HEAD~2", new [] { path });
var olderVersion = File.ReadAllText(Path.Combine(otherRepo.Info.WorkingDirectory, path));
}
You can get a better grasp of this RepositoryOptions type by taking a look at the tests in RepositoryOptionFixture that exercise it.
I am trying Proof of Concepts based on code at http://msdn.microsoft.com/en-us/library/windowsazure/gg618003. This cache is accesible if I use app.config settings. When I switched the application to use programatic configuration, I consistently get this error. I have already tried Azure cache programatically configuration fail to verify and many other solutions to no avail.
Here's my code snippet.
{code}
String acsKey = "AcsKey removed intentionaly";
DataCacheFactoryConfiguration cacheFactoryConfiguration;
DataCacheSecurity dataCacheSecurity;
DataCacheServerEndpoint[] serverEndpoints = new DataCacheServerEndpoint[1];
SecureString secureAcsKey = new SecureString();
serverEndpoints[0] = new DataCacheServerEndpoint("EndPont removed intentionaly", 22243);
//
// Create SecureString from string
//
foreach (char keyChar in acsKey)
{
secureAcsKey.AppendChar(keyChar);
}
secureAcsKey.MakeReadOnly();
dataCacheSecurity = new DataCacheSecurity(secureAcsKey);
//
// Initialize Factory Configuration
//
cacheFactoryConfiguration = new DataCacheFactoryConfiguration(); // This line throws exception. Note that the key is yet to be assigned to SecurityProperties as per documentation.
cacheFactoryConfiguration.Servers = serverEndpoints;
cacheFactoryConfiguration.SecurityProperties = dataCacheSecurity;
_cacheFactory = new DataCacheFactory(cacheFactoryConfiguration);
_cache = _cacheFactory.GetDefaultCache();
{code}
Try passing all the params at creation and not post creation?
var configFactory = new DataCacheFactoryConfiguration
{
Servers =
new List<DataCacheServerEndpoint>
{new DataCacheServerEndpoint(cacheServer, cachePort)},
SecurityProperties =
new DataCacheSecurity(Encryption.CreateSecureString(cacheAuthorization),
true)
};