The following is the process of saving data in JSON file and binding it in front-end. Here I have used,
- ASP.NET MVC 4
- MSSQL 2008 as Database.
- Entity Framework code first approach.
- From nuget added reference Newtonsoft.json and entity framework.
Step 1: Open Visual studio 2013, click New Project.
Under Installed, Templates, Visual C#, click Web and provide the name and click OK as per the following image.
Step 2: After this a window will pop up from Template, select Empty and then select MVC as in the following screenshot,
Step 3: After this point from solution explore click on Solution, Add, then New Project as in the following image,
Step 4: After this a window will pop up, click Installed, Visual C#, then Class Library as in the following image and click OK,
Step 5: Now Rename the Class1 name to Instagram under JsonEntity and write the following code,
- public class Instagram
- {
- [Key]
- public int Id { get; set; }
- public string InstagramId { get; set; }
- public string Text { get; set; }
- public string MediaSharedeUrl { get; set; }
- public string UserName { get; set; }
- public string LinkUrl { get; set; }
- public string MediaType { get; set; }
- public DateTime CreateDate { get; set; }
- public DateTime ModifyDate { get; set; }
- public string Status { get; set; }
- }
After this Add EntityFramework from
Manage NuGet Packages for solution as in the following images,
After this add a new folder with name Context and add a class with name JsonContext (The class has to be public) as in the following image,
Step 6: After this add the following code in the JsonContext.cs class,
- public class JsonContext : DbContext
- {
- public DbSet<Instagram> ObjInstagramDatas { get; set; }
- }
Now in the web.config of the DemoJson project add the following code to create database and table.
- <connectionStrings>
- <add name="JsonContext" connectionString="Data Source=(local); Initial Catalog=JsonDemo; User Id=sa; Password=Admin@321" providerName="System.Data.SqlClient"/>
- </connectionStrings>
Note:
- Here in name I have added "JsonContext", it has to be as per context class name and Initial Catalog=JsonDemo. It will create a database JsonDemo if it do not exist.
Now build the solution and provide the dll reference of the class in the DemoJson Project. And this completes the entity framework code first approach.
Step 7: I have taken a Controller called Home and added the following code and find the comments for better understanding. Also I have added Newtonsoft.json from Manage NuGet Packages for solution.
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- if (!Directory.Exists(Server.MapPath("~/JsonData")))
- {
- Directory.CreateDirectory(Server.MapPath("~/JsonData"));
- System.IO.File.WriteAllText(Server.MapPath("~/JsonData/InstagramData.json"), null);
- }
- var jsonInstagramdata = new StreamReader(Server.MapPath("~/JsonData/InstagramData.json"));
- var rawJsonData = jsonInstagramdata.ReadToEnd();
- jsonInstagramdata.Close();
- var dtlData = JsonConvert.DeserializeObject<List<Instagram>>(rawJsonData);
- if (dtlData != null)
- {
- ViewData["InstagramData"] = dtlData.ToList();
- }
- return View();
- }
- public ActionResult ReadInstagramRecord()
- {
- var count = 0;
- try
- {
- const string hashtag = "ProudToBeIndian";
- const string accessToken = "16741082.1b07669.121a338d0cbe4ff6a5e04543158a4f82";
- var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/v1/tags/" + hashtag + "/media/recent?count=33&access_token=" + accessToken + ""); //Hiting API
- request.Method = "GET";
- using (var response = (HttpWebResponse)request.GetResponse())
- {
- var dataStream = response.GetResponseStream();
- var reader = new StreamReader(dataStream);
- var json = reader.ReadToEnd();
- dynamic instagramDataList = JsonConvert.DeserializeObject(json);
- foreach (var data in instagramDataList.data)
- {
- using (var context = new JsonContext())
- {
- var instagramData = new Instagram();
-
- string img = data.type == "image" ? data.images.standard_resolution.url : data.videos.standard_resolution.url;
- instagramData.Text = data.caption.text;
- instagramData.InstagramId = data.id;
- instagramData.UserName = "https://www.instagram.com/" + data.user.username;
- instagramData.CreateDate = DateTime.Now;
- instagramData.ModifyDate = DateTime.Now;
- instagramData.Status = "Approved";
- instagramData.MediaType = data.type;
- instagramData.MediaSharedeUrl = img;
- instagramData.LinkUrl = data.link;
- var qry = (from s in context.ObjInstagramDatas where s.InstagramId == instagramData.InstagramId select s).FirstOrDefault();
- if (qry != null) continue;
- context.ObjInstagramDatas.Add(instagramData);
- context.SaveChanges();
- count++;
- }
- }
-
- reader.Close();
- if (dataStream != null) dataStream.Close();
- }
- ViewBag.CountData = count;
- return RedirectToAction("Index");
- }
- catch (Exception ex)
- {
- ViewBag.ErrorMessage = "Some exception occured" + ex;
- return View("Index");
- }
- }
-
- public ActionResult UpdateJson()
- {
- using (var context = new JsonContext())
- {
- try
- {
- var getInstaData = context.ObjInstagramDatas.Where(x => x.Status == "Approved").ToList();
- var selectInstaData = getInstaData.AsEnumerable().Where(x => x.Status == "Approved").Select((obj, index) => new Instagram()
- {
- Text = obj.Text,
- MediaSharedeUrl = obj.MediaSharedeUrl,
- MediaType = obj.MediaType,
- Status = obj.Status,
- CreateDate = obj.CreateDate,
- ModifyDate = obj.ModifyDate,
- LinkUrl = obj.LinkUrl,
- UserName = obj.UserName,
- Id = index + 1
- });
- var bindInstaData = selectInstaData.ToList();
-
- var jsonString = JsonConvert.SerializeObject(bindInstaData);
- if (jsonString != null)
- {
- if (!Directory.Exists(Server.MapPath("~/JsonData")))
- {
- Directory.CreateDirectory(Server.MapPath("~/JsonData"));
- }
- }
- System.IO.File.WriteAllText(Server.MapPath("~/JsonData/InstagramData.json"), jsonString);
- return RedirectToAction("Index");
- }
- catch (Exception)
- {
- throw;
- }
- }
- }
- }
Step 8: View for Index page design is as follows:
- @using JsonEntity
- @{
- Layout = null;
- var data = ViewData["InstagramData"];
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Json Demo</title>
- <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" />
- <script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
- </head>
- <body>
- <div class="col-lg-offset-3 col-md-9">
- <h4>@Html.ActionLink("Index", "Index", "Home", null, new { @class = "btn btn-success" }) @Html.ActionLink("Fetch Data", "ReadInstagramRecord", "Home", null, new { @class = "btn btn-primary" }) @Html.ActionLink("Update Json", "UpdateJson", "Home", null, new { @class = "btn btn-primary" })</h4>
- </div>
- <div>
- <table id="example" class="display" cellspacing="0" width="100%">
- <thead>
- <tr>
- <th>Id</th>
- <th>Media Shared Url</th>
- <th>Media Type</th>
- <th>Text</th>
- <th>Status</th>
- </tr>
- </thead>
- <tbody>
- @if (data == null)
- {
- <tr>
- <td>
- No records to show
- </td>
- </tr>
- }
- else
- {
- foreach (var item in (List<Instagram>)data)
- {
- <tr>
- <td>
- @item.Id
- </td>
- <td>
- @if (item.MediaSharedeUrl != null)
- {
- if (item.MediaType == "image")
- {
- <a href="@item.MediaSharedeUrl" target="_blank">View Image</a>
- }
- else
- {
- <a href="@item.MediaSharedeUrl" target="_blank">View Video</a>
- }
- }
- else
- {
- <span>Not Available</span>
- }
- @*<img src="@item.MediaSharedeUrl" style="height:50px;width:50px; " class="img-circle" />*@
- </td>
- <td>
- @item.MediaType
- </td>
- <td>
- @item.Text
- </td>
- <td>
- @item.Status
- </td>
- @*<td>
- <input type="checkbox" class="chcktblInsta" name="chcktblInsta" value="@item.Id" />
- </td>*@
- </tr>
- }
- }
- </tbody>
- </table>
- </div>
-
- <script type="text/javascript">
- $(document).ready(function () {
- $('#example').DataTable();
- });
- </script>
- <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
- <script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
- </body>
- </html>
You can download the sample project from the Google Drive
link.