Sam's Dynamics, Power Platform & AI Blog

Friday, 2 December 2016

All Important Code


AngularJS: Service vs provider vs factory: -

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body >
<div ng-controller="MyCtrl">
    {{hellos}}
</div>
<script>
var myApp = angular.module('myApp', []);

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!"
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!"
        }
    };
});
    
//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {

    this.name = 'Default';

    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!"
            }
        }
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});
        

function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
    
    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}

</script>
</body>
</html>


Loader

HTML

<div class='overlay'><div id='loading-img'></div></div>


JQuery
$(".overlay").show();

$('html, body').css('overflowY', 'auto'); 
 CSS
 
<style>
          #loading-img {
          background: url(http://preloaders.net/preloaders/360/Velocity.gif) center center no-repeat;
          height: 100%;
          z-index: 20;
          }
 
          .overlay {
          background: #e9e9e9;
          display: none;
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          opacity: 0.5;
          }
        </style>


Allow SSL

 ServicePointManager.Expect100Continue = true;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

Get using Jquery API

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

    <div id="countryname"></div>

</body>
</html>

/********Jquery Code**/
<script>
(function() {
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })

    .done(function( data ) {
$.each( data.records, function( i, records) {


       var a=  data.records[i].Country;
$('#countryname').append(a+'</br>');
      });
    });
})();
</script>


call angularjs in jQuery



onclick="angular.element(this).scope().methodname()"


Get_Fields_from_CRM


            CrmConnection connection = CrmConnection.Parse(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);
            IOrganizationService service = new OrganizationService(connection);
            OrganizationServiceContext context = new OrganizationServiceContext(service);
            var cases = (from c in context.CreateQuery("account")
                         select c).FirstOrDefault();
            var item = cases.Attributes.Values;


download folders from parature


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace PratureToAzureDownload_file
{
    class Program
    {
        static void Main(string[] args)
        {
            int AccountId = 7987;
            int DeptId = 8177;
            int CSRId = 14948;
            string token = "a0FUOtXbk9G8d0dLy2HlCtNvm8cwbzSiTIxQ1iYD4eQ@nL1PfWbnk9xdPNwm1Iy0igQfs84HT1eywB/F8J@IVSPkMX6dCNqlhnkil7Ezl0o=";
            string urldata = "https://demo.parature.com/api/v1/";
            //var request = (HttpWebRequest)WebRequest.Create(urldata + AccountId + "/" + DeptId + "/Download?_token_=" + token);
            //request.ContentType = "application/json";
            //var response = (HttpWebResponse)request.GetResponse();
            //if (response.StatusCode == HttpStatusCode.OK)
            //{

            //    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //    var dic = XDocument.Parse(responseString).Descendants("Column").ToDictionary(c => c.Attribute("Name").Value, c => c.Value);
            //    var json = new JavaScriptSerializer().Serialize(dic);
            //    var json = JsonConvert.SerializeObject(;

            //}
            //else
            //{
            //    Console.Write("Bad Request");
            //}
            //WebClient c = new WebClient();
            //var data = c.DownloadString(urldata + AccountId + "/" + DeptId + "/Download?_token_=" + token);


            XmlDocument xdoc = new XmlDocument();

            xdoc.Load(urldata + AccountId + "/" + DeptId + "/Download?_token_=" + token);//loading XML in xml doc

            XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("Download");
            List<Entities1> entitylst = new List<Entities1>();
            foreach (XmlElement xNode in xNodelst)//traversing XML
            {
                Entities1 entity = new Entities1();

                foreach (XmlNode x in xNode)
                {

                    if (x.Name == "External_Link")
                    {
                        entity.imgUrl = x.InnerText.ToString();
                    }
                    if (x.Name == "Name")
                    {
                        entity.title = x.InnerText.ToString();

                    }
                    if (x.Name == "Ext")
                    {
                        entity.extenson = x.InnerText.ToString();

                    }
                    if (x.Name == "Folders")
                    {
                        entity.Foldername = x.InnerText.ToString();

                    }

                }
                entity.Href = xNode.Attributes["href"].Value.ToString();
                entitylst.Add(entity);
                var a = xNode.Attributes["href"].Value.ToString();
                saveimg(entity.imgUrl, entity.title, entity.extenson, entity.Foldername);
            }

        }


        static void saveimg(string imgurl, string title, string extenson , string foldername)
        {
            string imageUrl = imgurl;

           
            byte[] imageBytes;

            string directorypath = "C:\\pic\\" + foldername;

            if (!Directory.Exists(directorypath))
            {
                Directory.CreateDirectory(directorypath);
            }
            string location = @"C:\pic\"+ foldername+"\\";
            string saveLocation = location + title + "." + extenson;
            if (imageUrl != null)
            {
                if (imageUrl != "")
                {
                    HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
                    WebResponse imageResponse = imageRequest.GetResponse();

                    Stream responseStream = imageResponse.GetResponseStream();

                    using (BinaryReader br = new BinaryReader(responseStream))
                    {
                        imageBytes = br.ReadBytes(500000);
                        br.Close();
                    }
                    responseStream.Close();
                    imageResponse.Close();

                    FileStream fs = new FileStream(saveLocation, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    try
                    {
                        bw.Write(imageBytes);
                    }
                    finally
                    {
                        fs.Close();
                        bw.Close();
                    }
                }
            }
        }

      

    }
}

public class Entities1
{
    public string imgUrl { get; set; }
    public string Href { get; set; }
    public string title { get; set; }
    public string extenson { get; set; }
    public string Foldername { get; set; }

}



Plugin For Insert


using System;
using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Collections.Generic;
using Microsoft.Xrm.Sdk.Metadata;
using System.Linq;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;


namespace ThinkCrmBlog.DemoPlugin
{
    public class fboNoticeApi : IPlugin
    {

        public string Authtoken = "";
        public static string acessToken;
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            tracer.Trace("Into Imtiyaz plugin to call api FBO");

            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    var targetEntity = (Entity)context.InputParameters["Target"];
                    if (targetEntity.LogicalName != "ife_govfbo_notices")
                        return;
                    Entity fboEntity = service.Retrieve("ife_govfbo_notices", targetEntity.Id, new ColumnSet(true));
                    if (fboEntity.Attributes.Contains("ife_token") && fboEntity.Attributes.Contains("ife_href"))
                    {
                        tracer.Trace("Into  FBO token " + fboEntity.Attributes["ife_token"].ToString());
                        tracer.Trace("Into  FBO link " + fboEntity.Attributes["ife_href"].ToString());
                        var ovrelateddoclist = getFBOnotices(fboEntity.Attributes["ife_href"].ToString(), fboEntity.Attributes["ife_token"].ToString(), tracer);
                        EntityReferenceCollection ovrelateddocEntity = new EntityReferenceCollection();
                        Guid FBOguid = new Guid();
                        int i = 0;
                        tracer.Trace("Into  FBO after response " + ovrelateddoclist.Count());
                        foreach (var c in ovrelateddoclist)
                        {
                            i++;
                            try
                            {
                                                               //  fbon["ife_fbonoticesname"] = c.
                               
                                Entity fbon = new Entity("ife_subgovfbonotices");

                                if (c.documentLink != "" && c.documentLink != null)
                                {
                                    fbon["ife_documentlink"] = (c.documentLink);
                                }
                                if (c.id != "" && c.id != null)
                                {
                                    fbon["ife_id"] = c.id;
                                }
                                if (c.publicationDate != "" && c.publicationDate != null)
                                {
                                    fbon["ife_publicationdate"] = (c.publicationDate);
                                }
                                if (c.title != "" && c.title != null)
                                {
                                    fbon["ife_title"] = (c.title);
                                }

                                fbon["ife_name"] = (i.ToString());
                                EntityReference erf = new EntityReference("ife_govfbo_notices", targetEntity.Id);
                                fbon["ife_fbonoticelistid"] = erf;

                                FBOguid = service.Create(fbon);
                                tracer.Trace("Into  FBO after response added");
                                EntityReference CnTr = new EntityReference();
                                CnTr.LogicalName = "ife_subgovfbonotices";
                                CnTr.Id = FBOguid;
                                ovrelateddocEntity.Add(CnTr);
                            }
                            catch (Exception ex)
                            {
                                tracer.Trace("Into  FBO after response added erreor " + ex.Message);
                            }
                        }
                      
                    }

                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }

   

        public List<DocumentLinks> getFBOnotices(string url, string token, ITracingService trace)
        {
           

            List<DocumentLinks> GovEntitieslist = new List<DocumentLinks>();
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers["Authorization"] = token;
                request.Method = "GET";
                try
                {
                    WebResponse response = request.GetResponse();

                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                        // var json1 = JsonConvert.DeserializeObject<IDictionary<string, RootObjectFBO>>(result);
                        //List<RootObjectFBO> datalist = JsonConvert.DeserializeObject<List<RootObjectFBO>>(result);

                        var json = JsonConvert.DeserializeObject<RootObjectFBO>(result);
                        GovEntitieslist = json.documentLinks;
                    }
                }
                catch (Exception exe)
                { }

            }
            catch (Exception exe)
            {

            }

            return GovEntitieslist;
        }


    }

    //FBO Notices Model

    public class DocumentLinks
    {
        public string documentLink { get; set; }
        public string id { get; set; }
        public string publicationDate { get; set; }
        public string title { get; set; }
    }

    public class RootObjectFBO
    {
        public Links links { get; set; }
        public Meta meta { get; set; }
        public List<DocumentLinks> documentLinks { get; set; }///confusing
    }



}

Send Email code

 public string get(int id)
        {
             
                    SmtpClient MyServer = new SmtpClient();
                    MyServer.Host = "smtp.gmail.com";
                    MyServer.Port = 587;
                    //Server Credentials
                    NetworkCredential NC = new NetworkCredential();
                    NC.UserName = "saddamk206@gmail.com";
                    NC.Password = "saddamk206";
                    //assigned credetial details to server
                    MyServer.Credentials = NC;
                    //create sender address
                    MailAddress from = new MailAddress("saddamk206@gmail.com", "Saddam Khan");
            //create receiver address
            MailAddress receiver = new MailAddress("shussain@moreyeahs.com", "saddam moreyeahs");
                    MailMessage Mymessage = new MailMessage(from, receiver);

                    Mymessage.Subject = "test";

                    //emailTemplate.Replace(mailMessage.ToString(), mailMessage1);
                    //var newbody = mailMessage.ToString() + "</br>Please click the link below to check your appointment:</br>"+ custlink;
                    Mymessage.Body = "this is test msg";
                    Mymessage.IsBodyHtml = true;
                    MyServer.EnableSsl = true;
                    //sends the email
                    MyServer.Send(Mymessage);
            return null;
              
      

    }


crud in MVC

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
    public class Default1Controller : Controller
    {
        private Prod_BuildTrailEntities db = new Prod_BuildTrailEntities();

        //
        // GET: /Default1/

        public ViewResult Index()
        {
            return View(db.UserProjects.ToList());
        }

        //
        // GET: /Default1/Details/5

        public ViewResult Details(int id)
        {
            UserProject userproject = db.UserProjects.Find(id);
            return View(userproject);
        }

        //
        // GET: /Default1/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Default1/Create

        [HttpPost]
        public ActionResult Create(UserProject userproject)
        {
            if (ModelState.IsValid)
            {
                db.UserProjects.Add(userproject);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(userproject);
        }
        
        //
        // GET: /Default1/Edit/5

        public ActionResult Edit(int id)
        {
            UserProject userproject = db.UserProjects.Find(id);
            return View(userproject);
        }

        //
        // POST: /Default1/Edit/5

        [HttpPost]
        public ActionResult Edit(UserProject userproject)
        {
            if (ModelState.IsValid)
            {
                db.Entry(userproject).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(userproject);
        }

        //
        // GET: /Default1/Delete/5

        public ActionResult Delete(int id)
        {
            UserProject userproject = db.UserProjects.Find(id);
            return View(userproject);
        }

        //
        // POST: /Default1/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            UserProject userproject = db.UserProjects.Find(id);
            db.UserProjects.Remove(userproject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}


insert from console

static void Main(string[] args)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = @"Data Source=kk7vcq4n1l.database.windows.net; Initial Catalog=Shopkirana;Persist Security Info=True;  Uid=moreyeahs; Password=wfp@ssw0rd;";
            con.Open();
            SqlCommand com = new SqlCommand();
            com.Connection = con;

            com.CommandType = System.Data.CommandType.Text;
            for (int i = 0; i <= 1000; i++)
            {
                string name = "asd" + i;
                string emailid = "a" + i + "@.com";
                string sql = "insert into Customers(Name,Password,Emailid,Active,Deleted,Warehouseid,DivisionId,CompanyId,Cityid,CreatedDate,UpdatedDate,MonthlyTurnOver,Rating,ClusterId) values('" + name + "','12345','" + emailid + "','true','false','5','0','" + i + "','2','07/20/2011 18:03:40','07/20/2011 18:03:40','10000','5','1')";
                com.CommandText = sql;
                var data = com.ExecuteNonQuery();

            }
            con.Close();
        }

crm case


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Net;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Threading;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;

namespace consoletry
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Url=https://saddamk206.crm8.dynamics.com; Username=saddamk206@saddamk206.onmicrosoft.com; Password=saddamk_206;";
            CrmConnection connection = CrmConnection.Parse(connectionString);
            OrganizationService organisationservice = new OrganizationService(connection);
            OrganizationServiceContext context = new OrganizationServiceContext(organisationservice);

            var cases = from c in context.CreateQuery("incident")
                        select c;

            var ca = cases.FirstOrDefault();


            string title = ca.GetAttributeValue<string>("title");
            Guid caseId = ca.Id;

            Entity incident = new Entity("incident");
            ColumnSet attributes = new ColumnSet(new string[] { "title", "ownerid" });

            incident = organisationservice.Retrieve("incident", caseId, attributes);

            incident["title"] = "TEst Cases";

            organisationservice.Update(incident);

        }
    }
}


youtube at HTML page

<div class=" col-md-6 col-sm-3 text-center">
<iframe width="100%" height="440" src="https://www.youtube.com/embed/GKWQ30DNWMw" frameborder="0" allowfullscreen style="border-radius: 10px;">
</iframe>
  </div>

Connection String

<add name="doctorDb" connectionString="Data Source=M-DEV-PC-18\SQLEXPRESS;Initial Catalog=doctor_Db;Persist Security Info=True;User ID=sa;Password=sa@123" providerName="System.Data.SqlClient" />

Fetch data from DB in DropDown with selected field

<select class="form-control" id="site-name" ng-model="saveData.CityId" required>
                    <option value="">---SELECT---</option>
                    <option value="{{city.CityId}}" ng-selected="saveData.CityId == city.CityId" ng-repeat="city in Cities"> {{city.CityName}}</option>
                </select>

Angular_Mvc_WebAPI_DataBaseConnectivity

Model---
Class--

    public class city
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }
    }
--------------------------------------------------------------------
DBContext---

  public class CityDbContext:DbContext
    {
        public DbSet<city> city { get; set; }
    }
==================================================================
Controller-----

public IEnumerable<city> Get()
        {
            CityDbContext context = new CityDbContext();
            var _city = from p in context.city.AsEnumerable()
                           select p;
            return _city;
        }
==================================================================
Script-----

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
    getCities();
    function getCities() {
        $http({
            method: 'GET',
            url: '/api/cities'
        })
            .success(function (data) {
                if (data != null || data != 'undefined') {
            $scope.cities = data;
        }
            })
}
}]);

===========================================================================


HTML Page-----
<!DOCTYPE html>
<html >
<head>
    <script type="text/javascript"
  src="
http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <script src="Scripts/Controller.js"></script>
        <meta charset="utf-8" />
</head>
<body >
    <div  data-ng-app="myApp">
        <div data-ng-controller="MyCtrl">

                           <table>
                             <tr>
                            <th>Id</th>
                                    <th>Name</th>
                                    <th>Country</th>
                        </tr>
                        <tr  data-ng-repeat="city in cities">
                               <td>{{city.Id}}</td>
                          <td>{{city.Name}}</td
                          <td>{{city.Country}}</td>
                               </tr>
                      </table>

</div>
    </div>
</body>
</html>


Angular_Mvc_WebAPI

HLML Page:-
<!DOCTYPE html>
<html>
<head>
    <script src="
http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="Scripts/Script.js"></script>
</head>

<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Firstname: <input type="text" ng-model="Firstname" /><br /><br />

    Lastname:  <input type="text" ng-model="Lastname" /><br /><br />

    Fullname: {{Firstname+" "+Lastname }}


    <div ng-repeat="studentList in studentLists">

        Id <input type="text" ng-model="studentList.StudentID" /><br />

        Name <input type="text" ng-model="studentList.StudentName" /><br />

    </div>

</div>


</body>

</html>
------------------------------------------------------------------------------------------------------------------


Controller:-
  public class StudentController : ApiController
    {
        public List<Student> Get()
        {
            Student st = new Student();
            st.StudentID = "1";
            st.StudentName = "John";

            Student st1 = new Student();
            st1.StudentID = "2";
            st1.StudentName = "Tony";


            List<Student> lst = new List<Student>();
            lst.Add(st);
            lst.Add(st1);
            return lst;
        }
    }
----------------------------------------------------------------------------------------------------------
Class:

  public class Student
    {
        public string StudentID { get; set; }
        public string StudentName { get; set; }
    }
--------------------------------------------------------------------------------------------------------------

Script:-
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
    $scope.Firstname = "Sameer";
    $scope.Lastname = "Sharma";

    $http.get('api/Student').then(function (value) {
        console.log(value);
        $scope.studentLists = value.data;
    });
}
);


No comments:

Post a Comment

Packaging and Deploying Web Resources: A Practical ALM Workflow for Dynamics 365 JavaScript

You've written the script. You've unit-tested the logic and stepped through it in dev tools. It works perfectly on your form. Now co...