How to change Blogengine.net password in users.xml

by Hozefa 28. August 2012 21:56

Seems the forgot password functionality is not working. I had to reset the password via the ftp upload of users.xml file.

1) Find the users.xml file in app_data. Replace the password to jGl25bVBBBW96Qi9Te4V37Fnqchz/Eu4qB9vKrRIqRg= which will set the password to admin

<Password>jGl25bVBBBW96Qi9Te4V37Fnqchz/Eu4qB9vKrRIqRg=</Password>

2) Login to your blog with your username and password as admin

3) Reset the password for the logged in user

Happy blogging!!!

Tags:

Blog | BlogEngine.NET

JSON Data in Windows 8 Application

by Hozefa 27. August 2012 22:39

Lets explore the JSON Data consumtion example in Windows 8 application using the Flickr JSON API.

There is no WebClient class in new API, but we can make use of the HttpClient class that works in a similar way. We can also provide an asynchronous method to fetch the data.

The new HttpClient class itself resides into the System.Net.Http namespace. Jumping right into the code:

public async Task<string> GetPhotosStream(){    
    HttpClient client = new HttpClient();    
    string url = "http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&nojsoncallback=1&api_key=<yourkey>&text=buildwindows";    
    HttpResponseMessage response = await client.GetAsync(url);    
    return response.Content.ReadAsString();
}

GetAsync() will return a HttpResponseMessage, which contains the returned status code, response headers and returned content, which can be read in a variety of ways.

Parsing the JSON. I prefer to use JSON.net. A returned string can be fed to the JsonObject in its constructor or using Parse() method on its instance. Either way will result in an exception if the JSON string is invalid and couldn’t be parsed.

And this is how you would read the titles of returned photos:

private static List<string> titles = new List<string>(); 
public static async void ExaminePhotos(){    
	string responseText = await GetPhotosStream();    
	JsonObject root = new JsonObject(responseText);    
	bool isSuccess = root.GetNamedString("stat") == "ok";    	
	JsonObject info = root.GetNamedObject("photos");    
	int page = (int)info.GetNamedNumber("page");    
	int totalPages = (int)info.GetNamedNumber("pages");    
	JsonArray photos = info.GetNamedArray("photo");    
	for (uint i = 0; i < photos.Count; i++)    {        
		string title = photos.GetObjectAt(i).GetNamedString("title");        
		titles.Add(title);    
	}
}

 

While the “Named*" methods return typed values (GetNamedString() returns a string, GetNamedNumber() a double, etc.), it’s also possible to get the JSON value by string indexer and later call to its typed value, e.g. json[“stat”].GetString(), which gets useful if you want to check for its type first.

The second part deals with a JsonArray named photo, which gets enumerated and read in a similar manner

Of course, the DataContractJsonSerializer is still here. In fact, it appears to be the same class, just moved into a separate assembly.

string responseText = await GetPhotosStream(); 
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject root;
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(responseText))){    
	root = serializer.ReadObject(stream) as RootObject;
}

 The result is a full object tree that was deserialized from the flickr API JSON string.

Tags: , ,

.NET | Win8 | Windows 8 | WinRT

Code snippet to send Email from C# code

by Hozefa 21. August 2012 06:48
using System.Net.Mail;

The System.Net.Mail class provides a simple interface to for the Email message and add recipients and sender information. This MailMessage is further passed in the Send method of the SMTP client.

private void btnSendEmail_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("hozefam@live.in");
        mail.From = new MailAddress("hozefam@gmail.com", "Hozefa Mangalorewala");
        mail.Subject = "Email Demo from hozefam@gmail.com";
        mail.Body = "This is a demo from  <a href='http://www.hozefam.com'>Hozefam.com</a>";
        mail.IsBodyHtml = true;

        SmtpClient smtp = new SmtpClient("smtp.gmail.com");
        smtp.Credentials = new System.Net.NetworkCredential("YourEmail", "YourPassword");
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
    catch (Exception ex)
    {
        
        throw ex;
    }
}

Change YourEmail and YourPassword to your email and password and make the necessary changes to the email addresses in the MailMessage To and From collection. To add more mail recipents address add mail entry to the mail.To collection.

MailMessage mail = new MailMessage();
mail.To.Add("hozefam@live.in");
mail.To.Add("hozefam@gmail.com");
mail.To.Add(hozefam@hozefam.com);

If you get an error saying, "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

Add an entry to bypass the proxy in the web.config like below :

<system.net>
  <defaultProxy>
  <proxy proxyaddress="YourProxyIpAddress"/>
  </defaultProxy>
</system.net>

also it is advisable to add the port number in the SMTP client like below:

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;

 

Tags:

.NET

Understanding Route and Routing data inside a controller

by Hozefa 15. August 2012 10:39

Default route in Global.asax is expecting the url format to be www.domain.com/Home/action/id or www.domain.com/Home/action

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

where "Default" is the Route name and URL format is the second paramter in MapRoute. The third parameter sets the defaults for the parameters.

Lets say I wish to create anoter Maproute entry which will enable the url www.domain.com/myController to hit the controller named "myController" and pick up the default action of myAction once hit.

routes.MapRoute(
    "myCustomRoute", // Route name
    "myController{action}", // URL with parameters
    new { controller = "Default", action = "myAction" } // Parameter defaults
);

so if we add the above route in entry, the url www.domain.com/myController will hit the myController and then pick up the action = "myAction" from the Parameter defaults specified in the "myCustomRoute" entry.

Lets say my requirement extends and now I wish that url www.domain.com/myController/myValue should hit myController, pick up the default action myAction and pass myValue as a paramter to myAction. Then I will have to modify the route entry so it understands that myValue is actually hooked as a parameter to the default action of "myAction". The modified route entry of "myCustomRoute" will be like:

routes.MapRoute(
    "myCustomRoute", // Route name
    "myController/{value}", // URL with parameters
    new { controller = "myController", action = "myAction", value = UrlParameter.Optional } // Parameter defaults
);

and my Action in myController will look like :

public class myController : Controller
{
    //
    // GET: /Sample/

    public ActionResult myAction(string value)
    {
        return Content("Value passed is " + value);
    }

}

So the url  www.domain.com/myController/myValue will render "Value passed is myValue"

Hope this small example helps to understand the working of Route in MVC3.

Tags: ,

.NET | MVC3

Get Twitter user information using jquery and AJAX calls for JSON

by Hozefa 11. August 2012 12:34

Say you have a place holder to display the results of ajax call like below :

<div>
    <span id="lblUsername">Twitter Handle : </span>
    <input id="txtUsername" type="text" />
    <br />
    <input id="btnTwitterGet" type="button" value="Get Stats" />
    <div id="ShowTwitterStats"></div>

</div>

then on the click of btnTwitterGet, you will call the following ajax that will append the list items of the data returned in success callback.

$("#btnTwitterGet").live("click", function () {
    var twitterHandle = $("#txtUsername").attr("value");
    if (twitterHandle !== null) {
        //Make a ajax call to fetch the Twitter Stats
        $.ajax({
            type: 'GET',
            dataType: 'jsonp',
            url: 'https://api.twitter.com/1/users/show.json',
            data: { screen_name: twitterHandle, include_entities: true },
            success: function (data, textStatus, XMLHttpRequest) {
                if (data !== null && data !== undefined) {
                    $("#ShowTwitterStats").append("<ul id='TwitterStatsList'></ul>");
                    $.each(data, function (key, val) {
                        $("#TwitterStatsList").append("<li>" + key + " : " + val + "</li>");
                    });
                }
            },
            error: function (req, status, error) {
                alert('Error: ' + status);
            }
        });

    }
});

 You can get more json calls to fetch the timeline or the twitter trends. For a complete list of the twitter apis refer to - Twitter APIs REST

Tags: , , ,

jQuery | Twitter

Creating a data layer using LINQ to XML

by Hozefa 11. August 2012 01:39

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. We will take a look on how to perform basic Create, Read, Update and Delete operations on the XML file using LINQ to XML.

Sample structure of ContactsDB.xml file:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Contact Id="1">
    <FirstName>Hozefa</FirstName>
    <LastName>Mangalorewala</LastName>
    <Phone>9860515805</Phone>
    <Email>hozefam@gmail.com</Email>
  </Contact>
  <Contact Id="2">
    <FirstName>James</FirstName>
    <LastName>Bond</LastName>
    <Phone>007</Phone>
    <Email>hero@badguys.com</Email>
  </Contact>
</Contacts>

Using the above structure, will make use of XDocument class to load the XML. XDocment is defined in System.Xml.Linq which represents a XML document.

string sFileName = HttpContext.Current.Server.MapPath("~/Data/ContactsDB.xml");
XDocument xmlDoc = XDocument.Load(sFileName);

XDocument on QuickWatch lists out the xml document structure.

Lets look at Create operation on XML using LINQ:

XElement newContact = new XElement("Contact",
    new XElement("FirstName", oContact.FirstName),
    new XElement("LastName", oContact.LastName),
    new XElement("Phone", oContact.Phone),
    new XElement("Email", oContact.Email));

newContact.SetAttributeValue("Id", GetNextAvailableID());

xmlDoc.Element("Contacts").Add(newContact);
xmlDoc.Save(sFileName);

 This creates a XElement Contact with inner XElements of FirstName, LastName, Phone, Email and Id. Note: Since Id may have requirement to be unique, the snippet above populates the Id by performing a sort logic within GetNextAvailableID().

Now, Read operation on XML using LINQ:

XDocument xmlDoc = XDocument.Load(sFileName);

return (from c in xmlDoc.Descendants("Contact")
        orderby c.Attribute("FirstName")
        where c.Attribute("Id").Value.Equals(Id.ToString())
        select new Contact()
        {
            Id = Convert.ToInt32(c.Attribute("Id").Value),
            FirstName = c.Element("FirstName").Value,
            LastName = c.Element("LastName").Value,
            Phone = c.Element("Phone").Value,
            Email = c.Element("Email").Value
        }).FirstOrDefault();

To return a list of Contacts, just replace the FirstOrDefault() with ToList() and exclude the where condition to refrain a matching Contact lookup.

Now, Update operation on XML using LINQ:

XElement contactElement = xmlDoc.Descendants("Contact")
    .Where(c => c.Attribute("Id").Value.Equals(oContact.Id.ToString()))
    .FirstOrDefault();

if (contactElement != null)
{
    contactElement.SetElementValue("FirstName", oContact.FirstName);
    contactElement.SetElementValue("LastName", oContact.LastName);
    contactElement.SetElementValue("Phone", oContact.Phone);
    contactElement.SetElementValue("Email", oContact.Email);
    xmlDoc.Save(sFileName);
}

and finally the Delete operation using LINQ to XML:

XDocument xmlDoc = XDocument.Load(sFileName);

XElement customerElement = xmlDoc.Descendants("Contact")
    .Where(c => c.Attribute("Id").Value.Equals(oContact.Id.ToString()))
    .FirstOrDefault();

if (customerElement != null) 
{ 
    customerElement.Remove(); 
    xmlDoc.Save(sFileName); 
}

 Using the above methods we can create an abstract application that will perform CRUD operations on XML.

Tags: , ,

.NET | LINQ

Exploring File Upload and Download in MVC 3

by Hozefa 10. August 2012 17:04

For the file upload control on the View, the post action will return a HttpPostedFileBase class object to the Controller. HttpPostedFileBase serves as the base class for classes that provide access to individual files that have been uploaded by a client.

The view for File upload and Submit button on it will be as below:

@using (Html.BeginForm("OpenFile", "Home", FormMethod.Post, 
             new {enctype="multipart/form-data"})) 
{
    <input id="fileControl" type="file" name="Document" />
    <br />
    <input type="submit" value="Open File" />
}

Note:

new {enctype="multipart/form-data"}

is added because when you make a POST request, you have to encode the data that forms the body of the request in some way. HTML forms provide two methods of encoding. The default is application/x-www-form-urlencoded, which is more or less the same as a query string on the end of the URL. multipart/form-data is a more complicated encoding but one which allows entire files to be included in the data. Are far as the client is concerned: Use multipart/form-data when you have an <input type="file">

Now the Home controller action OpenFile will be like,

public FileContentResult OpenFile(HttpPostedFileBase Document)
{
    byte[] data = null; 

    if (Document != null)
    {
        using (Stream inputStream = Document.InputStream)
        {
            MemoryStream memoryStream = inputStream as MemoryStream;
            if (memoryStream == null)
            {
                memoryStream = new MemoryStream();
                inputStream.CopyTo(memoryStream);
            }
            data = memoryStream.ToArray();
        }
    }
    
    return File(data, Document.ContentType, "SampleDoc.pdf");
}

 Default Content-Disposition is attachment in IE. This will prompt for the Save dialog but inorder to open the file on the browser, add Content-Disposition as inline to the Response object before return File()...

Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");

 Find the complete working solution at - FileUploadDemo.zip

Tags:

.NET | MVC3

Wait until all Ajax is completed !!!

by Hozefa 8. August 2012 05:12

Problem is I need to wait for all ajax requests to be done before i execute the next line of code. This can be handled in 2 ways

1) Make the Ajax request synchronous

2) Implement of $.when() in jQuery and handle the next lines in callbacks (success/failure)

To make the Ajax call synchronous

jQuery.ajax({ async: false,....});

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){ 
    // the code here will be executed when all four ajax requests resolve. 
    // a1, a2, a3 and a4 are lists of length 3 containing the response text, 
    // status, and jqXHR object for each of the four ajax calls respectively. 
}

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops. 

Tags:

jQuery

Hello blogging!!!

by Hozefa 8. August 2012 01:20

Attempt to share articles, tips tricks, findings and workarounds in .NET Web development. Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Tags:

Blog | Personal

About Me

Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Facebook - facebook.com/hozefam

Twitter - twitter.com/hozefam

Mail - hozefam@gmail.com

 

Month List

Page List