Monday

powershell search string

this is powershell script to search into log files but it could search into any text base files like csv,xml or json: id displays list of files when search string found:
      
cd c:\inetpub\Data\logs
Get-ChildItem -Recurse *.* | Select-String -Pattern "my search string" | Select-Object -Unique Path

Tuesday

sitecore upload image programmatically to media library

here is how controller class looks like:
      
using MyCorp.MyLib.Entities.WebService;
using Sitecore.Configuration;
using Sitecore.Resources.Media;
using Sitecore.SecurityModel;
using Sitecore.Services.Infrastructure.Web.Http;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;


namespace MyCorp.MyLib.Feature.EmailService
{
    [OverrideExceptionFilters]
    public class ImageServiceController : ServicesApiController
    {

        /// <summary>
        /// Save stream as file into sitecore
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="req"></param>
        private void SaveFileIntoSitecore(Stream stream, ImageRequest req ) {

            var mediaCreator = new MediaCreator();
            var options = new MediaCreatorOptions
            {
                AlternateText = req.AltText,
                OverwriteExisting = true,
                FileBased = false,
                Versioned = false,
                IncludeExtensionInItemName = false,
                Database = Factory.GetDatabase("master"),//web?
                Destination = req.DestinationName ///logo.jpg
            };

            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                using (new SecurityDisabler())
                    mediaCreator.CreateFromStream(memoryStream, req.DestinationName, options);
            }

        }


        [HttpPost, OverrideExceptionFilters]
        public async Task<HttpResponseMessage> Upload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data and return an async data.
                var result = await Request.Content.ReadAsMultipartAsync(provider);
                ImageRequest req = new ImageRequest();
                // This illustrates how to get the form data.
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        // return multiple value from FormData
                        if (key == "DestinationName")
                        {
                            req.DestinationName = val;
                        }
                        else if (key == "DestinationFolder")
                        {
                            req.DestinationFolder = val;
                        }
                    }
                }

                if (result.FileData.Any())
                {
                    // This illustrates how to get the file names for uploaded files.
                    foreach (var file in result.FileData)
                    {
                        FileInfo fileInfo = new FileInfo(file.LocalFileName);
                        if (fileInfo.Exists)
                        {
                            //Save every file to sitecore
                            var s = fileInfo.OpenRead();
                            SaveFileIntoSitecore(s, req);

                        }
                    }
                }


                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, req);
                return response;
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

    }
}

   

Monday

javascript next month date formatting coupon source code

  
function NextMonth1() {
        var now = new Date();
        if (now.getMonth() == 11) {
            return new Date(now.getFullYear() + 1, 0, 1);
        } else {
            return new Date(now.getFullYear(), now.getMonth() + 1, 1);
        }
}

function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

var div = document.getElementById('couponText');
div.innerHTML += "Effective till " + formatDate(NextMonth1());

Wednesday

c# return zip stream from api

  
        public Stream GetDataFile(string locationId)
        {
            int cid;
            DateTime tran = DateTime.Now.Date;

            Check(string.IsNullOrWhiteSpace(locationId), "locationId field is missing.");
            Check(!int.TryParse(locationId, out cid), "locationId must be numeric.");


            DataFileRepository repository = new DataFileRepository();
            /*returning stream*/
            var resp = WebOperationContext.Current.OutgoingResponse;
            resp.ContentType = "application/octet-stream";
            resp.Headers.Add("Content-Disposition", "attachment; filename=\"myfile.zip\"");

            return ZipStream(repository.GetCSVStream(cid));
        }

        /// <summary>
        ///  Check condition and generate exception if condition met.
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="exp"></param>
        public void Check(bool condition, string exp)
        {
            if (condition)
            {
                AssertionException up = new AssertionException(exp);
                throw up;
            }
        }

        /// <summary>
        ///  Method for zipping streams 
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public Stream ZipStream(Stream stream)
        {
            stream.Position = 0;
            var ar = new ZipArchive();
            ar.AddItem("myfile.csv", stream, true, FileAttributes.Normal);

            var zip = new TempFileStream();
            ar.Save(zip, false);
            zip.Position = 0;
            return zip;
        }
interface declaration in API webservice is very simple:
      
  [OperationContract]
        [WebGet(UriTemplate = "menu/datafile/{locationId}")]
        Stream GetDataFile(string locationId);
   

IDataReader into csv

        
        /// <summary>
        ///  Method for converting reader into CSV
        /// </summary>
        /// <param name="dataReader"></param>
        /// <param name="includeHeaderAsFirstRow"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public  Stream ToCSV(IDataReader dataReader, bool includeHeaderAsFirstRow, string separator)
        {
            Stream csv = new TempFileStream();
            StreamWriter csvRows = new StreamWriter(csv);
            StringBuilder sb = null;

            if (includeHeaderAsFirstRow)
            {
                sb = new StringBuilder();
                for (int index = 0; index < dataReader.FieldCount; index++)
                {
                    if (dataReader.GetName(index) != null)
                        sb.Append(dataReader.GetName(index));

                    if (index < dataReader.FieldCount - 1)
                        sb.Append(separator);
                }
                csvRows.WriteLine(sb.ToString());
            }

            while (dataReader.Read())
            {
                sb = new StringBuilder();
                for (int index = 0; index < dataReader.FieldCount - 1; index++)
                {
                    if (!dataReader.IsDBNull(index))
                    {
                        string value = dataReader.GetValue(index).ToString();
                        if (dataReader.GetFieldType(index) == typeof(String))
                        {
                            //If double quotes are used in value, ensure each are replaced but 2.
                            if (value.IndexOf("\"") >= 0)
                                value = value.Replace("\"", "\"\"");

                            //If separtor are is in value, ensure it is put in double quotes.
                            if (value.IndexOf(separator) >= 0)
                                value = "\"" + value + "\"";
                        }
                        sb.Append(value);
                    }

                    if (index < dataReader.FieldCount - 1)
                        sb.Append(separator);
                }

                if (!dataReader.IsDBNull(dataReader.FieldCount - 1))
                    sb.Append(dataReader.GetValue(dataReader.FieldCount - 1).ToString().Replace(separator, " "));

                csvRows.WriteLine(sb.ToString());
            }

            csvRows.Flush();
            dataReader.Close();
            return csv;
        }
 

Monday

register dlls into GAC on server 2012

You may noticed that gacutil is missing in on server 2012.There is no clear way to download and install gacutil or have portable gacutil.exe to deploy. This powershell script will register multiple dlls from folder.
   
# adds all dll files from folders into GAC 
# **** Attention *** in case of permission/signature  error Execute this command from powershell to allow run powershell files : Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

# load System.EnterpriseServices assembly
[Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") > $null

# create an instance of publish class
[System.EnterpriseServices.Internal.Publish] $publish = new-object System.EnterpriseServices.Internal.Publish


Get-ChildItem "C:\Program Files (x86)\Microsoft Enterprise Library 5.0\Bin" -Filter *.dll |
Foreach-Object {
    $content = $_.FullName
    Write-Output "registering "+$content;
    $publish.GacInstall($content)
}

Change path if you have to do batch install dlls from another directory.

Wednesday

add xml to xmldocument

     
static string module = @"
    <Module>
      <CustomerSortOrder>60</CustomerSortOrder>
      <LinkText_Customer>{0}</LinkText_Customer>
      <LocationId>4291</LocationId>
      <LocationModuleId>26544</LocationModuleId>
      <ModuleId>30</ModuleId>
      <ModuleName>Menu</ModuleName>
      <NavigateUrl>menu.aspx</NavigateUrl>
      <pageId>20</pageId>
      <IsModuleGroup>1</IsModuleGroup>
      <sort_order>1</sort_order>
      <MenuId>{1}</MenuId>
    </Module>
";
        public string AddWeekMenu(string xml2015, string xml2010) {
            string result = xml2015;
            try
            {
                XmlDocument x2015 = new XmlDocument();
                x2015.LoadXml(xml2015);

                //step 1 find menu tag group
                var menutag = x2015.SelectSingleNode("//Group[Group_Name='Menu']");
                //remove Menu text from second list
                menutag.ChildNodes[0].SelectSingleNode("//LinkText_Customer").InnerText = "";

                XmlDocument x2010 = new XmlDocument();
                x2010.LoadXml(xml2010);
                XmlNodeList m2010 = x2010.SelectNodes("//ChildNavigation[moduleid=30]");

                foreach (XmlNode item in m2010)
                {
                    //append menu links from 2010
                    AppendMenuLink(x2015, menutag, item.SelectSingleNode("ChildLinkText").InnerText, item.SelectSingleNode("ChildLinkCustomPageID").InnerText);

                }

                //updting menu tag  with correct count 
                menutag.SelectSingleNode("//numModules").InnerText = ""+m2010.Count;
                return x2015.OuterXml;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }

            return result;
        }

Tuesday

Game servers sources

sources of lineage 2
java: bitbucket.org/…​com/l2jserver/?at=develop

go: github.com/mikesaidani/l2go

а WOW
github.com/mangoszero/server

handlebars.js subtemplate example


step1.create subtemplate
<script id="nutri" type="text/x-handlebars">
    <p>
     This is subtemplate in Handelbars
     </p>
</script>

step2.register it in javascript

<script type="text/javascript">
    Handlebars.registerPartial('nutri', $('#nutri').html());
</script>

step3. use it into another subtemplate

<script id="package-list-bottom" type="text/x-handlebars-template">
    <div class='po-qty form-el bottom'>        
                <p>
                {{> nutri}}
                </p>
    </div>
</script>

why my app is not popular on appstore?

You finished app uploaded it on appstore and .... nothing happens. You probably was expecting skyrocketing installs and in-app sales but after days,weeks you got some 10,20 installs. And you thinking what is wrong with my app.

The best way to look at this situation is to look at app like art-artifact. Let's say when you have painting picture or sculpture you are not expecting it to look like Rembrant's or Michelangelo's aren't you ? So why it is different in regards of apps ?

Probably because at first look all applications are looking alike and have unified interface and same buttons and UI elements. But the most important things are in details, in iterations between application and user.

The best way to handle this situation is to continue perfecting and creating more apps and make them looks closer to perfect apps every day and learn. As Michelangelo said : "I am still learning."

Monday

c# custom webservice logging and error handling

//step1.declare delagate
public delegate T UnSafeProcedure<T>();

/*step2. add performance and error handling methods */
        public string Concat(params object[] arguments)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in arguments)
            {
                sb.AppendFormat("\"{0}\",", item);
            }
            return sb.ToString();
        }

        public T RunSafe<T>(UnSafeProcedure<T> s, params object[] arguments)
        {
            DateTime st = DateTime.Now;
            try
            {
               return  s();
            }
            catch (Exception e1)
            {
                {
                    Debug.Write("Error," + Concat(arguments) + "\r\n" + e1.ToString());
                }
                return default(T);
            }
            finally
            {
                var sec = DateTime.Now.Subtract(st).TotalSeconds;
                if (sec > 20)
                {
                    string tm = ">20sec,start," + st.ToLongTimeString() + ",End," + DateTime.Now.ToLongTimeString();
                    Debug.Write(tm+ Concat(arguments));
                }
            }
        }

/*3.performance counting procedures will looks like:*/

public Receipt VerifyUser(int Id, string username, string password)
{
           return  RunSafe<Receipt>(delegate()
            {
                //internal procedure that needs to be chcked troubleshooted
                using (var service = Instance())
                {
                    return service.VerifyAccount(Id, username, password);
                }

            }, "VerifyUser,facilityId",Id,"username",username,"password",password);
}

how to add vim pandoc integration for markdown files

autocmd BufEnter *.md exe 'noremap <F5> :silent !start c:\tools\pd.bat  % <CR>'

and autorefresh plugin for chrome: so every time I hit F5 on markdown (.md) file I can see compiled html version in chrome

Where pd.bat file is following:

pandoc "%1" -f markdown -t html -s -o "%1.html"

create sign up form for google group

here is javascrip/html code how to do it:

<script type="text/javascript">
   function msgbox() {   alert("An Invatation has been sent to " + _gel("emailconf").value 
+ ". You will have to confirm the email invitation to join and recieve future emails. 
You can opt out of our group at anytime using the Unsubscribe link in the email."); }
</script>

    Sign up with our google group to receive [product] updates or ask questions.
  <form action="http://groups.google.com/group/whiterocksoftware/boxsubscribe" id="formconf" onsubmit="msgbox()">
  Email: <input type=text name=email id="emailconf">
   <input type="submit" value="Subscribe">
</form>

Thursday

rainmeter slideshow skin tutorial

here is skin I used to show images :
 
[Rainmeter]
Update=100000
BackgroundMode=3
SolidColor=0,0,0,255
BackgroundMode=3
BackgroundMargins=0,34,0,14

[MeasureQuote]
Measure=Plugin
Plugin=QuotePlugin
PathName=c:\temp\trig
Subfolders=1
FileFilter=*.jpg;*.png;*.gif

[MeterQuote]
Meter=Image
MeasureName=MeasureQuote
X=0
Y=0
W=200
PreserveAspectRatio=1
LeftMouseUpAction=[!Refresh]

Friday

c# binary deserialize unable to find assembly version=1.0.0.0, culture=neutral, publickeytoken=null

Got error with binary deserialisation : unable to find assembly xxx version=1.0.0.0, culture=neutral, publickeytoken=null 
It requires to have additional SerializationBinder class .
Here is whole workable storage class:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.Runtime.Serialization;
using System.Reflection;

public static  class Storage {

    public const string ConfigurationName = "dev.settings";
    public static string SettingFileName
    {
        get
        {
            return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ConfigurationName);
        }
    }

    public static  void Save(cProfile gh)
    {
        FileStream writeStream = new FileStream(SettingFileName, FileMode.Create);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(writeStream, gh);
        writeStream.Close();
    }


    public static cProfile  Load() {
        cProfile ret= new cProfile();

        Manager.getInstance().RunSafe (delegate()
        {
            if (File.Exists(SettingFileName))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Binder = new PreMergeToMergedDeserializationBinder();

                FileStream readStream = new FileStream(SettingFileName, FileMode.Open);
                ret = (cProfile)formatter.Deserialize(readStream);
                readStream.Close();
            }
        });
        return ret;


    }


    sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type typeToDeserialize = null;

            // For each assemblyName/typeName that you want to deserialize to
            // a different type, set typeToDeserialize to the desired type.
            String exeAssembly = Assembly.GetExecutingAssembly().FullName;


            // The following line of code returns the type.
            typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
                typeName, exeAssembly));

            return typeToDeserialize;
        }
    }
}





Thursday

"app_name" is not translated in "af" (Afrikaans), "am" (Amharic), "ar" (Arabic), "az" (Azerbaijani), "be" (Belarusian), "bg" (Bulgarian), "bn" (Bengali), "bs" (Bosnian), "ca" (Catalan), "cs" (Czech), "da" (Danish), "de" (German), "el" (Greek), "es" (Spanish), "es-US" (Spanish: United States), "et" (Estonian), "eu" (Basque), "fa" (Persian), "fi" (Finnish), "fr" (French), "fr-CA" (French: Canada), "gl" (Galician), "gu" (Gujarati), "hi" (Hindi), "hr" (Croatian), "hu" (Hungarian), "hy" (Armenian), "in" (Indonesian), "is" (Icelandic), "it" (Italian), "iw" (Hebrew), "ja" (Japanese), "ka" (Georgian), "kk" (Kazakh), "km" (Khmer), "kn" (Kannada), "ko" (Korean), "ky" (Kyrgyz), "lo" (Lao), "lt" (Lithuanian), "lv" (Latvian), "mk" (Macedonian), "ml" (Malayalam), "mn" (Mongolian), "mr" (Marathi), "ms" (Malay), "my" (Burmese), "nb" (Norwegian Bokm?l), "ne" (Nepali), "nl" (Dutch), "pa" (Punjabi), "pl" (Polish), "pt-BR" (Portuguese: Brazil), "pt-PT" (Portuguese: Portugal), "ro" (Romanian), "ru" (Russian), "si" (Sinhala), "sk" (Slovak), "sl" (Slovenian), "sq" (Albanian), "sr" (Serbian), "sv" (Swedish), "sw" (Swahili), "ta" (Tamil), "te" (Telugu), "th" (Thai), "tl" (Tagalog), "tr" (Turkish), "uk" (Ukrainian), "ur" (Urdu), "uz" (Uzbek), "vi" (Vietnamese), "zh-CN" (Chinese: China), "zh-HK" (Chinese: Hong Kong SAR China), "zh-TW" (Chinese: Taiwan), "zu" (Zulu)

I was gettign this error after running build with apache cordova for visual studio : Severity Code
Severity Code Description Project File Line Suppression State
Error C:\Cordova\SpaceRiddle\SpaceRiddle\platforms\android\res\values\strings.xml:3: Error: "app_name" is not translated in "af" (Afrikaans), "am" (Amharic), "ar" (Arabic), "az" (Azerbaijani), "be" (Belarusian), "bg" (Bulgarian), "bn" (Bengali), "bs" (Bosnian), "ca" (Catalan), "cs" (Czech), "da" (Danish), "de" (German), "el" (Greek), "es" (Spanish), "es-US" (Spanish: United States), "et" (Estonian), "eu" (Basque), "fa" (Persian), "fi" (Finnish), "fr" (French), "fr-CA" (French: Canada), "gl" (Galician), "gu" (Gujarati), "hi" (Hindi), "hr" (Croatian), "hu" (Hungarian), "hy" (Armenian), "in" (Indonesian), "is" (Icelandic), "it" (Italian), "iw" (Hebrew), "ja" (Japanese), "ka" (Georgian), "kk" (Kazakh), "km" (Khmer), "kn" (Kannada), "ko" (Korean), "ky" (Kyrgyz), "lo" (Lao), "lt" (Lithuanian), "lv" (Latvian), "mk" (Macedonian), "ml" (Malayalam), "mn" (Mongolian), "mr" (Marathi), "ms" (Malay), "my" (Burmese), "nb" (Norwegian Bokm?l), "ne" (Nepali), "nl" (Dutch), "pa" (Punjabi), "pl" (Polish), "pt-BR" (Portuguese: Brazil), "pt-PT" (Portuguese: Portugal), "ro" (Romanian), "ru" (Russian), "si" (Sinhala), "sk" (Slovak), "sl" (Slovenian), "sq" (Albanian), "sr" (Serbian), "sv" (Swedish), "sw" (Swahili), "ta" (Tamil), "te" (Telugu), "th" (Thai), "tl" (Tagalog), "tr" (Turkish), "uk" (Ukrainian), "ur" (Urdu), "uz" (Uzbek), "vi" (Vietnamese), "zh-CN" (Chinese: China), "zh-HK" (Chinese: Hong Kong SAR China), "zh-TW" (Chinese: Taiwan), "zu" (Zulu) [MissingTranslation] SpaceRiddle 1



In order to resolve this error I had to update problem file : C:\Cordova\SpaceRiddle\SpaceRiddle\platforms\android\res\values\strings.xml 
with adding translatable="false" so final file looks like :

<?xml version='1.0' encoding='utf-8'?>
<resources>
    <string name="app_name" translatable="false">SpaceRiddle</string>
    <string name="launcher_name" translatable="false">@string/app_name</string>
    <string name="activity_name" translatable="false">@string/launcher_name</string>
</resources>

Monday

Configuring Web for ASP.NET 4.5 failed .

To resolve error:
Configuring Web for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.”

I manually created pool for with 4.5, in order to create it I had to do following:
Because there is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv. 
This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5



Sunday

Requested registry access is not allowed Error in webservice or website.



To fix  Requested registry access is not allowed error in webservice or website you need to know name of the event log and here is how to grant access:

Grant permission to create a custom event log
  1. Log on to the computer as an administrator.
  2. Click Start, click Run, type regedit in the Open box, and then click OK. The Registry Editor window appears.
  3. Locate the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog
  1. Right-click Eventlog, and then click Permissions. The Permissions for Eventlog dialog box appears.
  2. Click Advanced. The Advanced Security Settings for Eventlog dialog box appears.
  3. In the Name column, double-click the Users group. The Permission Entry for Eventlog dialog box appears.
  4. Select the Set Value check box, select the Create Subkey check box, and then click OK.
  5. Quit Registry Editor, and then log off from the administrator account.

rainmeter blinking text

Here is instruction how to make blinking text in rainmeter:
1.right click and select  "Edit skin"
2.add following code to template:


[Fade]
Measure=Calc
Formula=Counter% 2 = 1 ? 255 : 0


[MeterSeconds]
Meter=STRING
X=100
Y=50
W=1500
SolidColor=0,0,0,1
StringStyle=Normal
StringAlign=Center
FontColor=255,255,255,[Fade]
FontSize=20
FontFace=#FontName#
AntiAlias=1
Text=CTID
DynamicVariables=1

3.Save tempalate into notepad.
4.Right click and select  "Refresh skin"

Now you have blinking  CTID letters.

Tuesday

Game based on pomodoro technique

Game based on pomodoro technique 
pomodoro technique game

removing E-02 from Excel numbers

this problem can be resolved once per column :
1.highlight the column
2.from ribbon select Data -> Text to Columns -> Fixed length -> Don't create any break lines. Clear any that show up -> Select column data format text -> Finish.
3.Done!

Visual Studio 2015 cordova taco Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: Java heap space

This was resolved by creating system variable in :
Windows button-> search for "system variables"
Open Environment Variables window
click New... name: _JAVA_OPTIONS, value:  -Xmx1G -Xms1G
this should help

Sunday

Meditation Software

Computer Meditation Software

Many software applications have been created in order to help to achieve meditation technique mastery and become guru in Zen,mindfulness,transcendental meditations. Or for using it in yoga practice.There are following main characteristic these applications can be classified:

  • Learning - Guides and software helping people establish technique.
  • Timers - software for measuring time
  • Soundscape -software for creating sounds
  • Biofeedback Software - software and hardware capable for reading human body characteristics


Name Platform Link Description
Calm Android/IOS https://www.calm.com/ Soundscape app
Insight Timer Android/IOS https://insighttimer.com/ guided meditations, music tracks, talks
Learning Meditation Game Android/PC http://www.whiterocksoftware.com/2015/02/learning-meditation-game.html Learning Meditation game,timer, guide.
Omvana Android/IOS http://www.omvana.com/ guided meditations, inspirational speeches, binaural tracks

Wednesday

split large xml file in c#

      
using Microsoft.XLANGs.BaseTypes;
using MyWebComponents;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

[Serializable]
public class MasterProductSplitter
{
    public MasterProductSplitter()
    {
    }

    List<string> ops = new List<string>();

    const string schema = "http://schemas.datacontract.org/2004/07/MyWebACPRecords";
    const string RecordTag = "b:getACPMasterRecords_Result";

    public void Dispose()
    {
        Thread.Sleep(5000);//let's wait until all files closes.
        foreach (var s in ops)
        {
            try
            {
                File.Delete(s);
            }
            catch (Exception ex)
            {
                LogError("Error deleting file :", ex);
            }

        }

    }

    public void InitialiseMsg(XLANGMessage message, DateTime RequestTime)
    {
        Initialise((Stream)message[0].RetrieveAs(typeof(Stream)), RequestTime);
    }

    public int Length { get { return ops.Count; } }
    public int Current;

    public const int MaxCount = 1000;

    public void Initialise(Stream ins, DateTime RequestTime)
    {
        Debug.Write("MasterProductSplitter v1.1 started.");
        ins.Seek(0, SeekOrigin.Begin);
        ops = new List<string>();
        Current = 0;

        XmlTextReader doc = new XmlTextReader(ins);
        int count = MaxCount;//getting 1K records 
        XmlDocument outdoc = new XmlDocument();
        var r = outdoc.CreateElement("e");

        while (!doc.EOF)
        {

            if (doc.Name == RecordTag)
            {
                //wrap Records into <l> tag in case we would need to transfer more infor within a Record.
                XmlElement rootNode = outdoc.CreateElement("l");
                rootNode.InnerXml = doc.ReadOuterXml();
                r.AppendChild(rootNode);

                count -= 1;
                if (count < 0)
                {
                    outdoc.AppendChild(r);
                    count = MaxCount;
                    ops.Add(CreateGlobalProductMsg(outdoc, RequestTime));
                    outdoc = new XmlDocument();
                    r = outdoc.CreateElement("e");
                }
            } else {
                doc.Read();
            }
        }

        if (count != MaxCount)
        {
            outdoc.AppendChild(r);
            ops.Add(CreateGlobalProductMsg(outdoc, RequestTime));
        }

        Debug.Write("MasterProductSplitter:parts created:" + this.Length);
        ins.Seek(0, SeekOrigin.End);
    }


    public bool hasData()
    {
        return Current < Length;
    }


    public void LogError(string message, Exception e)
    {
        LogError(message + "" + e.ToString());
    }
    public void LogError(string err)
    {
        Debug.Write("MasterProductSplitter:Error:" + err);
        EventLog.WriteEntry("Biztalk Server", "MasterProductSplitter:Error:" + err, System.Diagnostics.EventLogEntryType.Error, 1);
    }

    public XmlDocument GetPart()
    {
        XmlDocument xmldoc = new XmlDocument();
        try
        {
            StreamReader sr = new StreamReader(ops[Current]);
            xmldoc.Load(sr);
            Current += 1;
        }
        catch (Exception ex)
        {
            Current += 1;//this part is broken , moving to the next part
            LogError("MasterProductSplitter:Error reading part:", ex);
        }

        return xmldoc;
    }

    public static string CreateGlobalProductMsg(XmlDocument globalProductsMessage, DateTime RequestTime)
    {
        string ret = Path.GetTempFileName();
        using (FileStream res = new FileStream(ret, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 4096))
        {
            StreamWriter sb = new StreamWriter(res);
            sb.Write("<ns0:MasterProductSync xmlns:ns0=\"http://tempuri.org/\"><ns0:masterProducts><![CDATA[<r RequestTime=\"");
            sb.Write(RequestTime.ToString("s"));
            sb.Write("\">");
            sb.Write(globalProductsMessage.InnerXml);
            sb.Write("</r>]]></ns0:masterProducts></ns0:MasterProductSync>");
            res.Flush();
            sb.Flush();
            sb.Close();
            res.Close();
            Debug.Write("Create file:" + ret);
        }
        return ret;
    }



    /// <summary>
    ///  Copy data from one stream into anoter
    /// </summary>
    /// <param name="input"></param>
    /// <param name="output"></param>
    public void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[8 * 1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }



    /// <summary>
    /// Saving Stream Into File
    /// </summary>
    /// <param name="stm"></param>
    /// <param name="filename"></param>
    public static void SaveStreamIntoFile(Stream stm, string filename)
    {
        stm.Seek(0, SeekOrigin.Begin);
        FileStream fileStream = File.Create(filename, (int)stm.Length);
        byte[] bytesInStream = new byte[stm.Length];
        stm.Read(bytesInStream, 0, bytesInStream.Length);
        // Use write method to write to the file specified above
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
        fileStream.Close();
    }

}
   

make ubuntu business casual

to make ubuntu business casual - make it black remove background: gsettings set org.gnome.desktop.background picture-options ...