I came across this problem while I was developing a mobile web application in MVC4. I think most of you all have faced this issue and found a solution as well. But I thought it was worth to share this, becuase this did the trick for me.
In my MVC4 web application , I had my _Layout.cshtml page like this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<meta name="viewport" content="width=device-width" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
@Styles.Render("~/Content/mobileCss", "~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div data-role="page" data-theme="b">
<div data-role="header">
@if (IsSectionDefined("Header")) {
@RenderSection("Header")
} else {
<h1>@ViewBag.Title</h1>
@Html.Partial("_LoginPartial")
}
</div>
<div data-role="content">
@RenderBody()
</div>
</div>
@Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
@RenderSection("scripts", required: false)
</body>
</html>
But inorder to resolve the error, I had to modify the page like below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<meta name="viewport" content="width=device-width" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
@Styles.Render("~/Content/mobileCss", "~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
</head>
<body>
<div data-role="page" data-theme="b">
<div data-role="header">
@if (IsSectionDefined("Header")) {
@RenderSection("Header")
} else {
<h1>@ViewBag.Title</h1>
@Html.Partial("_LoginPartial")
}
</div>
<div data-role="content">
@RenderBody()
</div>
</div>
@RenderSection("scripts", required: false)
</body>
</html>
Note that I changed the place of JQuery script line from section <body> to <head>.
source : http://forums.asp.net/t/1835597.aspx/1
Sunday, December 23, 2012
Monday, December 3, 2012
Windows Phone 7 Photo Upload
Recently I have developed a native Windows Phone 7 program to upload images to remote server.
MainPage.xaml
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="517" Margin="0,6,0,0" Name="listimge" VerticalAlignment="Top" Width="450">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="chk" /><Image Source="{Binding ImageFile}" Width="100" Height="100"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Upload" Height="72" HorizontalAlignment="Left" Margin="150,529,0,0" Name="uploadButton"
VerticalAlignment="Top" Width="160" Click="UploadClick" />
</Grid>
MainPage.xaml.cs
The below method is used to load image files from the Picture Gallery to the ListBox.
private MediaLibrary MyMediaLibrary { get; set; }
private void LoadImageGallery()
{
MyMediaLibrary = new MediaLibrary();
PictureCollection pictures = MyMediaLibrary.Pictures;
foreach (Picture picture in pictures)
{
var image = new BitmapImage();
image.SetSource(picture.GetImage());
var mediaImage = new MediaImage {ImageFile = image};
listimge.Items.Add(mediaImage);
}
}
This method is used to upload the selected images(iterating through the ListBox to find the selected index) to the remote server.
private void UploadClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < listimge.Items.Count; i++)
{
if (listimge.ItemContainerGenerator != null)
{
var item = listimge.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
var tagregCheckBox = FindCheckBox<CheckBox>(item);
if (tagregCheckBox.IsChecked == true)
{
UploadImage(i);
tagregCheckBox.IsChecked = false;
}
}
}
}
Helper function which is used to identify the checked Checkboxses in the ListBox.
private T FindCheckBox<T>(DependencyObject parentElement) where T : DependencyObject
{
int count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{
return (T) child;
}
var result = FindCheckBox<T>(child);
if (result != null)
return result;
}
return null;
}
This method is used to find the image from image gallery, get the stream of the identified image and send it to the remote server.
private void UploadImage(int selectedIndex)
{
const int BLOCK_SIZE = 4096;
var uri = new Uri("http://10.20.10.71/MVCFile/File", UriKind.Absolute);
var webClient = new WebClient();
webClient.AllowReadStreamBuffering = true;
webClient.AllowWriteStreamBuffering = true;
Stream selectedImageStream = MyMediaLibrary.Pictures[selectedIndex].GetImage();
webClient.OpenWriteCompleted += (s, args) =>
{
using (var binaryReader = new BinaryReader(selectedImageStream ))
{
using (var binaryWriter = new BinaryWriter(args.Result))
{
long count = 0;
long fileSize = selectedImageStream .Length;
var bytes = new byte[BLOCK_SIZE];
do
{
bytes = binaryReader.ReadBytes(BLOCK_SIZE);
count += bytes.Length;
binaryWriter.Write(bytes);
} while (count < fileSize);
}
}
};
webClient.WriteStreamClosed += (s, args) => { MessageBox.Show("Send Complete"); };
webClient.OpenWriteAsync(uri, "POST");
}
Finally add the 'LoadImageGallery' method to the constructor of MainPage.
// Constructor
public MainPage()
{
InitializeComponent();
LoadImageGallery();
}
Server side File Uploading Controller
public class FileController : Controller
{
public ActionResult Index()
{
string filename = Server.MapPath(String.Format("{0}.jpg", "YourFileName"));
try
{
using (var fs = new FileStream(filename, FileMode.Create))
{
using (var bw = new BinaryWriter(fs))
{
using (var br = new BinaryReader(Request.InputStream))
{
long bCount = 0;
long fileSize = br.BaseStream.Length;
const int BLOCK_SIZE = 4096;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
}
return Json(new { Result = "Upload Complete" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "Upload Error", Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
}
MainPage.xaml
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="517" Margin="0,6,0,0" Name="listimge" VerticalAlignment="Top" Width="450">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="chk" /><Image Source="{Binding ImageFile}" Width="100" Height="100"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Upload" Height="72" HorizontalAlignment="Left" Margin="150,529,0,0" Name="uploadButton"
VerticalAlignment="Top" Width="160" Click="UploadClick" />
</Grid>
MainPage.xaml.cs
The below method is used to load image files from the Picture Gallery to the ListBox.
private MediaLibrary MyMediaLibrary { get; set; }
private void LoadImageGallery()
{
MyMediaLibrary = new MediaLibrary();
PictureCollection pictures = MyMediaLibrary.Pictures;
foreach (Picture picture in pictures)
{
var image = new BitmapImage();
image.SetSource(picture.GetImage());
var mediaImage = new MediaImage {ImageFile = image};
listimge.Items.Add(mediaImage);
}
}
This method is used to upload the selected images(iterating through the ListBox to find the selected index) to the remote server.
private void UploadClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < listimge.Items.Count; i++)
{
if (listimge.ItemContainerGenerator != null)
{
var item = listimge.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
var tagregCheckBox = FindCheckBox<CheckBox>(item);
if (tagregCheckBox.IsChecked == true)
{
UploadImage(i);
tagregCheckBox.IsChecked = false;
}
}
}
}
Helper function which is used to identify the checked Checkboxses in the ListBox.
private T FindCheckBox<T>(DependencyObject parentElement) where T : DependencyObject
{
int count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{
return (T) child;
}
var result = FindCheckBox<T>(child);
if (result != null)
return result;
}
return null;
}
This method is used to find the image from image gallery, get the stream of the identified image and send it to the remote server.
private void UploadImage(int selectedIndex)
{
const int BLOCK_SIZE = 4096;
var uri = new Uri("http://10.20.10.71/MVCFile/File", UriKind.Absolute);
var webClient = new WebClient();
webClient.AllowReadStreamBuffering = true;
webClient.AllowWriteStreamBuffering = true;
Stream selectedImageStream = MyMediaLibrary.Pictures[selectedIndex].GetImage();
webClient.OpenWriteCompleted += (s, args) =>
{
using (var binaryReader = new BinaryReader(selectedImageStream ))
{
using (var binaryWriter = new BinaryWriter(args.Result))
{
long count = 0;
long fileSize = selectedImageStream .Length;
var bytes = new byte[BLOCK_SIZE];
do
{
bytes = binaryReader.ReadBytes(BLOCK_SIZE);
count += bytes.Length;
binaryWriter.Write(bytes);
} while (count < fileSize);
}
}
};
webClient.WriteStreamClosed += (s, args) => { MessageBox.Show("Send Complete"); };
webClient.OpenWriteAsync(uri, "POST");
}
Finally add the 'LoadImageGallery' method to the constructor of MainPage.
// Constructor
public MainPage()
{
InitializeComponent();
LoadImageGallery();
}
Server side File Uploading Controller
public class FileController : Controller
{
public ActionResult Index()
{
string filename = Server.MapPath(String.Format("{0}.jpg", "YourFileName"));
try
{
using (var fs = new FileStream(filename, FileMode.Create))
{
using (var bw = new BinaryWriter(fs))
{
using (var br = new BinaryReader(Request.InputStream))
{
long bCount = 0;
long fileSize = br.BaseStream.Length;
const int BLOCK_SIZE = 4096;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
}
return Json(new { Result = "Upload Complete" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "Upload Error", Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
}
Monday, November 19, 2012
IE 10 release preview for Windows 7
pre-requisites : windows 7 service pack 1
source : [http://lifehacker.com/5960175/ie-10-release-preview-available-now-for-windows-7?utm_campaign=socialflow_lifehacker_twitter&utm_source=lifehacker_twitter&utm_medium=socialflow]
source : [http://lifehacker.com/5960175/ie-10-release-preview-available-now-for-windows-7?utm_campaign=socialflow_lifehacker_twitter&utm_source=lifehacker_twitter&utm_medium=socialflow]
Making the file input to appear as a button
The file input was a bit of hectic element when it comes to styling. Even though I applied css styles the element was appeared in different ways in different browsers. Finally I came up with this solution when I was developing the HTML5 application with the use of jquery mobile css styles & javascript.
<input type = "button" value = "Choose files" onclick ="javascript:document.getElementById('file').click();">
<input type="file" name="file" id="file" style='visibility: hidden;' name="img" onchange="fileSelected();"/>
File Input resetting function
I have spent sometime to get the file input element reset correctly while I was developing a HTML5 application. I have found several ways of doing it while I was researching, but most of them were not worked as I expect. The below mentioned piece of jquery code worked fine in several desktop as well as mobile browsers. So I thought of sharing it.
works with Chrome, FireFox, Opera ,Safari and IE10 & above
$("#yourfileinput").val("");
works with < IE10
$("#yourfileinput").replaceWith($("#yourfileinput").clone(true));
works with Chrome, FireFox, Opera ,Safari and IE10 & above
$("#yourfileinput").val("");
works with < IE10
$("#yourfileinput").replaceWith($("#yourfileinput").clone(true));
Wednesday, October 24, 2012
Replace partial text string in SQL Text field
Even though this is very simple, I thought of blogging this.
I had a table called tbl_Item which had a Field called URL(nvarchar(200)) having several records like 'http://192.168.0.20:8080/Items/T-shirt.jpg', 'http://192.168.0.20:8080/Items/Jean.jpg'.
I wanted to replace the part of the string which contains '192.168.0.20:8080' to '10.20.10.71'. Here it goes.
UPDATE tbl_Item
SET Url = replace(cast(Url as NVARCHAR(200)),'192.168.0.20:8080','10.20.10.71')
I had a table called tbl_Item which had a Field called URL(nvarchar(200)) having several records like 'http://192.168.0.20:8080/Items/T-shirt.jpg', 'http://192.168.0.20:8080/Items/Jean.jpg'.
I wanted to replace the part of the string which contains '192.168.0.20:8080' to '10.20.10.71'. Here it goes.
UPDATE tbl_Item
SET Url = replace(cast(Url as NVARCHAR(200)),'192.168.0.20:8080','10.20.10.71')
Sunday, September 9, 2012
Android Device specific unique id generation
//generate unique id..
public static String getUniqueID(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String uniqueID = null;
//http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID
uniqueID = android.provider.Settings.Secure.getString(
context.getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
if (uniqueID == null) {
String deviceID = "" + telephonyManager.getDeviceId();
String simSerialID = "" + telephonyManager.getSimSerialNumber();
String androidID = ""
+ android.provider.Settings.Secure.getString(
context.getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidID.hashCode(), ((long) deviceID
.hashCode() << 32)
| simSerialID.hashCode());
if (deviceUuid.toString() != null) {
uniqueID = ((deviceUuid.toString().length() > 0) && (deviceUuid
.toString().length() >= 32)) ? deviceUuid.toString()
.substring(0, 32) : deviceUuid.toString();
}
}
return uniqueID;
}
Sometimes, I have found that the unique id generation for a android device fails. In this case this function is pretty useful as a alternate way of generating a unique id.
Android Activity Navigate Helper
This Navigator class helps to easily navigate from one activity to another including passing parameters. It also dose the navigate back to a previous activity as well. With the use of the HashMap object you can pass
serializable objects to other activities.
public class Navigator {
//navigate form one activity to another with passing parameters
public static void Navigate(Activity activityFrom, Class classTo,
HashMap<String, Serializable> params) {
Controller.instance().PrevActStack().push(
activityFrom.getClass().getName());
Intent intentNavigateTo = new Intent(activityFrom, classTo);
intentNavigateTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Set set = params.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
intentNavigateTo.putExtra((String) me.getKey(), (Serializable) me
.getValue());
}
activityFrom.startActivityForResult(intentNavigateTo, 0);
activityFrom.finish();
params.clear();
}
//navigate form one activity to another without passing parameters
public static void Navigate(Activity activityFrom, Class classTo) {
Controller.instance().PrevActStack().push(
activityFrom.getClass().getName());
Intent intentNavigateTo = new Intent(activityFrom, classTo);
intentNavigateTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityFrom.startActivity(intentNavigateTo);
activityFrom.finish();
}
//navigate back to previous activity with passing parameters
public static void NavigateBack(Activity activityFrom,
HashMap<String, Serializable> params) throws Exception {
if (Controller.instance().PrevActStack().size() == 0) {
throw new Exception("No previous activity found !!");
}
Intent intentNavigateBackTo = new Intent(activityFrom, Class
.forName(Controller.instance().PrevActStack().pop()));
intentNavigateBackTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Set set = params.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
intentNavigateBackTo.putExtra((String) me.getKey(),
(Serializable) me.getValue());
}
activityFrom.startActivity(intentNavigateBackTo);
activityFrom.finish();
params.clear();
}
//navigate back to previous activity without passing parameters
public static void NavigateBack(Activity activityFrom) throws Exception {
if (Controller.instance().PrevActStack().size() == 0) {
throw new Exception("No previous activity found !!");
}
Intent intentNavigateBackTo = new Intent(activityFrom, Class
.forName(Controller.instance().PrevActStack().pop()));
intentNavigateBackTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityFrom.startActivity(intentNavigateBackTo);
activityFrom.finish();
}
}
public class Navigator {
//navigate form one activity to another with passing parameters
public static void Navigate(Activity activityFrom, Class classTo,
HashMap<String, Serializable> params) {
Controller.instance().PrevActStack().push(
activityFrom.getClass().getName());
Intent intentNavigateTo = new Intent(activityFrom, classTo);
intentNavigateTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Set set = params.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
intentNavigateTo.putExtra((String) me.getKey(), (Serializable) me
.getValue());
}
activityFrom.startActivityForResult(intentNavigateTo, 0);
activityFrom.finish();
params.clear();
}
//navigate form one activity to another without passing parameters
public static void Navigate(Activity activityFrom, Class classTo) {
Controller.instance().PrevActStack().push(
activityFrom.getClass().getName());
Intent intentNavigateTo = new Intent(activityFrom, classTo);
intentNavigateTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityFrom.startActivity(intentNavigateTo);
activityFrom.finish();
}
//navigate back to previous activity with passing parameters
public static void NavigateBack(Activity activityFrom,
HashMap<String, Serializable> params) throws Exception {
if (Controller.instance().PrevActStack().size() == 0) {
throw new Exception("No previous activity found !!");
}
Intent intentNavigateBackTo = new Intent(activityFrom, Class
.forName(Controller.instance().PrevActStack().pop()));
intentNavigateBackTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Set set = params.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry me = (Map.Entry) iterator.next();
intentNavigateBackTo.putExtra((String) me.getKey(),
(Serializable) me.getValue());
}
activityFrom.startActivity(intentNavigateBackTo);
activityFrom.finish();
params.clear();
}
//navigate back to previous activity without passing parameters
public static void NavigateBack(Activity activityFrom) throws Exception {
if (Controller.instance().PrevActStack().size() == 0) {
throw new Exception("No previous activity found !!");
}
Intent intentNavigateBackTo = new Intent(activityFrom, Class
.forName(Controller.instance().PrevActStack().pop()));
intentNavigateBackTo.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityFrom.startActivity(intentNavigateBackTo);
activityFrom.finish();
}
}
Subscribe to:
Posts (Atom)