ASP.NET Resource handler mechanism in MVC4 - asp.net-mvc-3

Simple. I want to localize my application.
I've googled for days, and tried a million different approaches to reach my resources.
The only way I've been succesful is by using the standard asp.net folders "App_LocalResource", making the resource files public and giving them a Custom Tool Name. In the view I can then import the Custom Tool Name with #using.
My issue is that the language/resource items arent changing when I change the culture.
Here is how I change it in global.asax:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
CultureInfo ci = (CultureInfo)this.Session["Culture"];
if (ci == null)
{
string langName = "en";
string autoLang = "";
if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
{
autoLang = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);
}
if (autoLang == "da")
langName = autoLang;
ci = new CultureInfo(langName);
this.Session["Culture"] = ci;
}
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
So the culture is either da or en. But I noticed that the names of the resource files has to have a specific syntax. There has to be a default (in this case english) with no country/culture code and other that default has be named like reFile.da-DK.resx. It has to have both language and culture code.
I'm affraid the resource handler can recognize my file, because culture is set to "da" and not "da-DK". If I name my da resouce file to resFile.da.resx I cant import the Custom Tool Name which is my resouce files.
What do I do to solve this?

Use the full culture info string, ex:
var info = new CultureInfo("en-US")
Also for best practice move the code out into the Application_BeginRequest method, that's the standard location you'll see this type of code.

Related

Programmatically access TFS annotations to determine owner

I'm working on a project team and our application is in TFS. I'm attempting to determine how many lines of code each team member is responsible. In TFS, I'm aware of the Annotate feature in the Visual Studio interface which allows you to see who last modified each line of code so I know TFS has this information.
I've written a small console app which accesses my TFS project and all its files, but I now need to programmatically access annotations so I can see who the owner of each line is. Here is my existing code:
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
public class Program
{
static void Main(string[] args)
{
var credentials = new NetworkCredential(username, password, domain);
var server = new TfsTeamProjectCollection(new Uri(serverUrl), credentials);
var version = server.GetService(typeof(VersionControlServer)) as VersionControlServer;
var items = version.GetItems(projectPath, RecursionType.Full);
var fileItems = items.Items.Where(x => x.ItemType == ItemType.File);
foreach (var fileItem in fileItems)
{
var serverItem = fileItem.ServerItem;
//TODO: retrieve and parse annotations
}
}
}
I can't seem to figure out how to retrieve annotations once I have the TFS item. This link explains how to do it by calling TFPT, but after implementing it (tfpt annotate /noprompt <filename>), you are only give the last changeset and code per line, not the owner.
I also found a Microsoft.TeamFoundation.VersionControl.Server namespace that has an Annotation class. I installed TFS on my machine to have access to that DLL, but it doesn't seem like it is of any help to this problem.
How can you programmatically access TFS annotations to determine the owner of a line of code for a file?
You may have to query the branch when a Item's change type is Branch.
For a simple example, there is a scenario
$/Project
/Main`
/a.txt
/Develop
/a.txt (branched from main)
When you query the history of $/project/Develop/a.txt, you can also get the history of $/project/Main/a.txt using following code
void GetAllHistory(string serverItem)
{
var changesets=vcs.QueryHistory(serverItem,
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest,
0,
Microsoft.TeamFoundation.VersionControl.Client.RecursionType.None,
null,
new Microsoft.TeamFoundation.VersionControl.Client.ChangesetVersionSpec(1),
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest,
int.MaxValue,
true,
false);
foreach (var obj in changesets)
{
Microsoft.TeamFoundation.VersionControl.Client.Changeset cs = obj as Microsoft.TeamFoundation.VersionControl.Client.Changeset;
if (cs == null)
{
return;
}
foreach (var change in cs.Changes)
{
if (change.Item.ServerItem != serverItem)
{
return;
}
Console.WriteLine(string.Format("ChangeSetID:{0}\tFile:{1}\tChangeType:{2}", cs.ChangesetId,change.Item.ServerItem, change.ChangeType));
if ((change.ChangeType & Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Branch) == Microsoft.TeamFoundation.VersionControl.Client.ChangeType.Branch)
{
var items=vcs.GetBranchHistory(new Microsoft.TeamFoundation.VersionControl.Client.ItemSpec[]{new Microsoft.TeamFoundation.VersionControl.Client.ItemSpec(serverItem, Microsoft.TeamFoundation.VersionControl.Client.RecursionType.None)},
Microsoft.TeamFoundation.VersionControl.Client.VersionSpec.Latest);
GetAllHistory(items[0][0].Relative.BranchToItem.ServerItem);
}
}
}
}

resource listing

I writing wicket webapp. I want to:
list all resources - videoPreview in the folder
preview it
add link to show in main preview panel.
I read a lot and look examples about resources, but seems like can't understand smthg. I write such funny code:
RepeatingView rv = new RepeatingView("showVideo");
add(rv);
File vidPrevDir = (new File("data/catalog/"+product+"/videoPreview"));
File[] list = vidPrevDir.listFiles();
for (File file : list) {
final String previewFile = file.getName();
AjaxLink link = new AjaxLink(rv.newChildId()){
#Override
public void onClick(AjaxRequestTarget target) {
container.name="iframe";
container.attrs.clear();
container.attrs.put("class", "viewPanel");
container.attrs.put("allowfullscreen", "yes");
container.attrs.put("src", "http://www.youtube.com/embed/"+previewFile.substring(previewFile.indexOf("___"), previewFile.length()-4));
target.add(container);
}
};
rv.add(link);
link.add(new Image("videoPreview", product+"/videoPreview/"+file.getName()));
}
In application i call
getResourceSettings().addResourceFolder("data");
It's work, but i feel bad when i see that. So my question is how to make such things in wicket? Maybe there is resource listing or java.io.File->wicket.Image converter ?
I only found built-in method:
ServletContext context = WicketApplication.get().getServletContext();
Set productList = context.getResourcePaths("/catalog");
It list filenames, not resources, but it is preferable approach, then i use in question.

How to check if a Document Library (SPDocumentLibrary) supports a particular ContentType

I have a SharePoint 2010 site set up locally for debugging with the following topography:
Main (SPSite)
-> Toolbox (SPWeb)
-> MyTool (SPWeb)
I have created and deployed the following to Main:
Custom Field "RequestedBy"
Custom Field "OriginalRequestFileName"
Custom Content Type "RequestContentType" that contains the above two fields in addition to OOB fields
Custom List Definition "RequestListDefinition" based on the above ContentType
VisualWebPart "MyFileUploaderWebPart" that has a custom EditorPart to allow the user to define which document library the file should be uploaded to.
I have created an instance of a list "My Request List" in MyTool that's based on my custom list definition "RequestListDefinition".
In the EditorPart I've got a drop-down list of document libraries.
private void PopulateDocumentLibraryList(DropDownList dropDownList)
{
SPWeb currentWebsite = SPContext.Current.Web;
SPListCollection lists = currentWebsite.GetListsOfType(SPBaseType.DocumentLibrary);
if (lists.Count > 0)
{
List<SPDocumentLibrary> docLibraries = lists.Cast<SPList>()
.Select(list => list as SPDocumentLibrary)
.Where(library => library != null && !library.IsCatalog && !library.IsSiteAssetsLibrary)
.ToList();
dropDownList.DataSource = docLibraries;
dropDownList.DataTextField = "Title";
dropDownList.DataValueField = "ID";
dropDownList.DataBind();
// Default the selected item to the first entry
dropDownList.SelectedIndex = 0;
}
}
I would like to restrict the list of document libraries to only those that are derived from my custom list definition that I've deployed. I thought of doing this by checking the supported content types and thus tried altering the Where clause to:
private void PopulateDocumentLibraryList(DropDownList dropDownList)
{
SPWeb currentWebsite = SPContext.Current.Web;
SPListCollection lists = currentWebsite.GetListsOfType(SPBaseType.DocumentLibrary);
if (lists.Count > 0)
{
SPContentType voucherRequestListContentType = currentWebsite.ContentTypes["VoucherRequestContentType"];
List<SPDocumentLibrary> docLibraries = lists.Cast<SPList>()
.Select(list => list as SPDocumentLibrary)
.Where(library => library != null && !library.IsCatalog && !library.IsSiteAssetsLibrary && library.IsContentTypeAllowed(voucherRequestListContentType))
.ToList();
dropDownList.DataSource = docLibraries;
dropDownList.DataTextField = "Title";
dropDownList.DataValueField = "ID";
dropDownList.DataBind();
// Default the selected item to the first entry
dropDownList.SelectedIndex = 0;
}
}
It bombs out with the following error though:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Value cannot be null.
Parameter name: ct
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: ct
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentNullException: Value cannot be null.
Parameter name: ct]
Microsoft.SharePoint.SPList.IsContentTypeAllowed(SPContentType ct) +26981638
Dominos.OLO.WebParts.FileUploader.<>c__DisplayClass7.<PopulateDocumentLibraryList>b__4(SPDocumentLibrary library) +137
System.Linq.WhereEnumerableIterator`1.MoveNext() +269
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +578
System.Linq.Enumerable.ToList(IEnumerable`1 source) +78
Dominos.OLO.WebParts.FileUploader.DocumentLibrarySelectorEditorPart.PopulateDocumentLibraryList(DropDownList dropDownList) +801
Dominos.OLO.WebParts.FileUploader.DocumentLibrarySelectorEditorPart.CreateChildControls() +154
System.Web.UI.Control.EnsureChildControls() +146
Dominos.OLO.WebParts.FileUploader.DocumentLibrarySelectorEditorPart.SyncChanges() +102
Microsoft.SharePoint.WebPartPages.ToolPane.OnSelectedWebPartChanged(Object sender, WebPartEventArgs e) +283
System.Web.UI.WebControls.WebParts.WebPartEventHandler.Invoke(Object sender, WebPartEventArgs e) +0
Microsoft.SharePoint.WebPartPages.SPWebPartManager.BeginWebPartEditing(WebPart webPart) +96
Microsoft.SharePoint.WebPartPages.SPWebPartManager.ShowToolPaneIfNecessary() +579
Microsoft.SharePoint.WebPartPages.SPWebPartManager.OnPageInitComplete(Object sender, EventArgs e) +296
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Page.OnInitComplete(EventArgs e) +11056990
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1674
This suggests to me that it's failing to find the content type.
Another thought I had was to try and retrieve all lists that are of my custom list definition type "RequestListDefinition". However, SPWeb.GetListsOfType() takes an SPListTemplateType, which is an enum and thus doesn't contain my custom list definition. The documentation for SPListTemplateType (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splisttemplatetype.aspx) suggests using a method that accepts a string or an int instead of SPListTemplateType but I haven't seen any documentation for this.
Can someone please help me work out either:
how I can get just those lists that are derived from my custom list definition; or
how I can get a hold of my custom content type; or
point me in the direction of a better solution for restricting the list of SPDocumentLibrary?
Thanks!!
Point 2:
The SPContentType should be retrieved via currentWebsite.AvailableContentTypes[name]. The ContentTypes property of a SPWeb does only return content types created on this particular web. However, AvailableContentTypes does return all content types available in the current site collection.
Update:
To check whether the list has your content type, you should use the content type collection on the list:
SPContentTypeId ctId = voucherRequestListContentType.Id;
// LINQ where clause:
.Where(library => (...) && library.ContentTypes[ctID] != null);
The method SPList.IsContentTypeAllowed checks if a given content type is supported on the list and not if the content type is part of the list. See the MSDN documentation SPList.IsContentTypeAllowed Method.
I found that IsApplicationList (SP 2013) was helpful in limiting to Document Libraries that were non-system libraries (i.e. IsApplicationList is true for _catalogs, SiteAssets, and SitePages, but not for Shared Documents).
In PowerShell, you can see this by running the following
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Add-PsSnapin Microsoft.SharePoint.PowerShell
$site = Get-SPSite "http://sharePoint2013Url"
$webs = $site.AllWebs
foreach($web in $webs)
{
Write-Host "$($web.Url)"
foreach($list in $web.GetListsOfType([Microsoft.SharePoint.SPBaseType]::DocumentLibrary))
{
Write-Host "$($list.DefaultEditFormUrl) $($list.IsApplicationList)"
}
}

How to pull the finalUri property from an async image lookup result?

In windows phone 7 I'm doing a simple async lookup to find an image by uri and set the returned binary as the source for an image control.
public object SetImageFromUri(string uri)
{
var wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri(uri), wc);
return null;
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
var image = new BitmapImage();
image.SetSource(e.Result);
//e.Result has a property in the memory stream labeled finalUri
//someImageControl.Source = image;
}
}
My question is- how can I pull out the final uri property from the e.Result so I can see what image control it's associated with
Thank you in advance
Instead of passing the WebClient through as the second parameter, pass the Uri (or some other piece of usefule state information)
wc.OpenReadAsync(new Uri(uri), uri);
You can then access this in your callback
var uri = (string)e.UserState;
Due to specific restrictions implemented in the Reflection mechanism, you cannot access internal content from sandboxed code. Ultimately, you would want to use something like this:
FieldInfo f = e.Result.GetType().GetField("_finalUri", BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);
Uri n = (Uri)f.GetValue(e.Result);
However, this will cause a FieldAccessException. If you are not using a redirect URI, then you can simply reuse the parameter that is initially passed to your method. If not, you need to check HttpWebRequest and follow the idea I outlined a couple of days ago.
You could also just bind directly to the Image, and use the LowProfileImageLoader, to avoid it blocking the UI thread during the load. (Remember to set a FallBack image)

WP7 - get compile/build date from code?

In Windows Phone 7, is there a way to get the application build or compile date in code?
I would like to display the date, along with the version number, for support purposes for my application.
If it isn't immediately available, any hints or alternatives? (I guess one is making it an app setting, which is hokey).
You can parse the version number out of Assembly.GetExecutingAssembly().FullName.
The output is of this form
PhoneApp, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null
The build date doesn't appear to be available, and arguably you won't need it if you increment your version number every release. Alteranatively you could store this somewhere else if it's important to your app.
The date (& time) of the build isn't included in an assembly.
If you could get to the file system on the phone you may be able to get a date from this but it may be affected by the marketplace ingestion process (when the code is signed) and so you may not be able to guarantee this.
If you used a * for the build part of the version number and then work out the build date from that. (It's the number of days since 2000-01-01.)
Or, you could add something to your build process to set a property or setting.
Or, if using SVN for your version control system, you could use $WCDATE$ in a template with SubWcRev.exe to set this.
Or, you could add this to the app through the use of T4.
The following in a TT file should do the trick:
<## template language="C#" #>
<## import namespace="System" #>
using System.Windows;
namespace MyNamespace
{
public partial class App : Application
{
public string BuildDate { get { return "<#= DateTime.Now #>"; } }
}
}
To get the App Version on Windows Phone 7+: https://stackoverflow.com/a/22838743/1033581
Here is the WP7 code:
var xmlReaderSettings = new XmlReaderSettings
{
XmlResolver = new XmlXapResolver()
};
using (var xmlReader = XmlReader.Create("WMAppManifest.xml", xmlReaderSettings))
{
xmlReader.ReadToDescendant("App");
return xmlReader.GetAttribute("Version");
}
To get the App Version on Windows Phone 8+: https://stackoverflow.com/a/23387825/1033581
Here is the WP8 code:
using (var stream = new FileStream("WMAppManifest.xml", FileMode.Open, FileAccess.Read))
{
var appVersion = XElement.Load(stream).Descendants("App").FirstOrDefault().Attribute("Version");
return appVersion != null ? appVersion.Value : null;
}
add file BuildDate.txt
project Properties > Build Events
Pre-build event command line: echo %date% %time% > "$(ProjectDir)\BuildDate.txt"
Add code:
private static DateTime UpdatedAt()
{
var streamResourceInfo = Application.GetResourceStream(new Uri("BuildDate.txt", UriKind.Relative));
var reader = new StreamReader(streamResourceInfo.Stream);
string text = reader.ReadToEnd();
var substring = text.Substring(0, text.Length - 6); // text = "11.05.2014 20:44:52,07 \n\r"
var exact = DateTime.ParseExact(substring, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
return exact;
}

Resources